• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 package android.app.admin;
18 
19 import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
20 
21 import android.Manifest.permission;
22 import android.annotation.CallbackExecutor;
23 import android.annotation.ColorInt;
24 import android.annotation.IntDef;
25 import android.annotation.NonNull;
26 import android.annotation.Nullable;
27 import android.annotation.RequiresFeature;
28 import android.annotation.RequiresPermission;
29 import android.annotation.SdkConstant;
30 import android.annotation.SdkConstant.SdkConstantType;
31 import android.annotation.StringDef;
32 import android.annotation.SuppressLint;
33 import android.annotation.SystemApi;
34 import android.annotation.SystemService;
35 import android.annotation.TestApi;
36 import android.annotation.UserHandleAware;
37 import android.annotation.UserIdInt;
38 import android.annotation.WorkerThread;
39 import android.app.Activity;
40 import android.app.IServiceConnection;
41 import android.app.KeyguardManager;
42 import android.app.admin.SecurityLog.SecurityEvent;
43 import android.compat.annotation.UnsupportedAppUsage;
44 import android.content.ComponentName;
45 import android.content.Context;
46 import android.content.Intent;
47 import android.content.IntentFilter;
48 import android.content.ServiceConnection;
49 import android.content.pm.ApplicationInfo;
50 import android.content.pm.IPackageDataObserver;
51 import android.content.pm.PackageManager;
52 import android.content.pm.PackageManager.NameNotFoundException;
53 import android.content.pm.ParceledListSlice;
54 import android.content.pm.UserInfo;
55 import android.graphics.Bitmap;
56 import android.net.PrivateDnsConnectivityChecker;
57 import android.net.ProxyInfo;
58 import android.net.Uri;
59 import android.os.Build;
60 import android.os.Bundle;
61 import android.os.ParcelFileDescriptor;
62 import android.os.Parcelable;
63 import android.os.PersistableBundle;
64 import android.os.Process;
65 import android.os.RemoteCallback;
66 import android.os.RemoteException;
67 import android.os.ServiceSpecificException;
68 import android.os.UserHandle;
69 import android.os.UserManager;
70 import android.os.UserManager.UserOperationException;
71 import android.os.UserManager.UserOperationResult;
72 import android.provider.CalendarContract;
73 import android.provider.ContactsContract.Directory;
74 import android.provider.Settings;
75 import android.security.AttestedKeyPair;
76 import android.security.Credentials;
77 import android.security.KeyChain;
78 import android.security.KeyChainException;
79 import android.security.keymaster.KeymasterCertificateChain;
80 import android.security.keystore.AttestationUtils;
81 import android.security.keystore.KeyAttestationException;
82 import android.security.keystore.KeyGenParameterSpec;
83 import android.security.keystore.ParcelableKeyGenParameterSpec;
84 import android.security.keystore.StrongBoxUnavailableException;
85 import android.service.restrictions.RestrictionsReceiver;
86 import android.telephony.TelephonyManager;
87 import android.telephony.data.ApnSetting;
88 import android.text.TextUtils;
89 import android.util.ArraySet;
90 import android.util.DebugUtils;
91 import android.util.Log;
92 import android.util.Pair;
93 
94 import com.android.internal.annotations.VisibleForTesting;
95 import com.android.internal.net.NetworkUtilsInternal;
96 import com.android.internal.os.BackgroundThread;
97 import com.android.internal.util.Preconditions;
98 import com.android.org.conscrypt.TrustedCertificateStore;
99 
100 import java.io.ByteArrayInputStream;
101 import java.io.FileNotFoundException;
102 import java.io.IOException;
103 import java.lang.annotation.Retention;
104 import java.lang.annotation.RetentionPolicy;
105 import java.net.InetSocketAddress;
106 import java.net.Proxy;
107 import java.security.KeyFactory;
108 import java.security.KeyPair;
109 import java.security.NoSuchAlgorithmException;
110 import java.security.PrivateKey;
111 import java.security.cert.Certificate;
112 import java.security.cert.CertificateException;
113 import java.security.cert.CertificateFactory;
114 import java.security.cert.X509Certificate;
115 import java.security.spec.InvalidKeySpecException;
116 import java.security.spec.PKCS8EncodedKeySpec;
117 import java.util.ArrayList;
118 import java.util.Arrays;
119 import java.util.Collections;
120 import java.util.HashSet;
121 import java.util.List;
122 import java.util.Map;
123 import java.util.Objects;
124 import java.util.Set;
125 import java.util.concurrent.CompletableFuture;
126 import java.util.concurrent.ExecutionException;
127 import java.util.concurrent.Executor;
128 
129 // TODO(b/172376923) - add CarDevicePolicyManager examples below (or remove reference to it).
130 /**
131  * Public interface for managing policies enforced on a device. Most clients of this class must be
132  * registered with the system as a <a href="{@docRoot}guide/topics/admin/device-admin.html">device
133  * administrator</a>. Additionally, a device administrator may be registered as either a profile or
134  * device owner. A given method is accessible to all device administrators unless the documentation
135  * for that method specifies that it is restricted to either device or profile owners. Any
136  * application calling an api may only pass as an argument a device administrator component it
137  * owns. Otherwise, a {@link SecurityException} will be thrown.
138  *
139  * <p><b>Note: </b>on
140  * {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, some methods can
141  * throw an {@link UnsafeStateException} exception (for example, if the vehicle is moving), so
142  * callers running on automotive builds should wrap every method call under the methods provided by
143  * {@code android.car.admin.CarDevicePolicyManager}.
144  *
145  * <div class="special reference">
146  * <h3>Developer Guides</h3>
147  * <p>
148  * For more information about managing policies for device administration, read the <a href=
149  * "{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a> developer
150  * guide. </div>
151  */
152 @SystemService(Context.DEVICE_POLICY_SERVICE)
153 @RequiresFeature(PackageManager.FEATURE_DEVICE_ADMIN)
154 @SuppressLint("UseIcu")
155 public class DevicePolicyManager {
156 
157     private static String TAG = "DevicePolicyManager";
158 
159     private final Context mContext;
160     private final IDevicePolicyManager mService;
161     private final boolean mParentInstance;
162 
163     /** @hide */
DevicePolicyManager(Context context, IDevicePolicyManager service)164     public DevicePolicyManager(Context context, IDevicePolicyManager service) {
165         this(context, service, false);
166     }
167 
168     /** @hide */
169     @VisibleForTesting
DevicePolicyManager(Context context, IDevicePolicyManager service, boolean parentInstance)170     protected DevicePolicyManager(Context context, IDevicePolicyManager service,
171             boolean parentInstance) {
172         mContext = context;
173         mService = service;
174         mParentInstance = parentInstance;
175     }
176 
177     /** @hide test will override it. */
178     @VisibleForTesting
myUserId()179     protected int myUserId() {
180         return mContext.getUserId();
181     }
182 
183     /**
184      * Activity action: Starts the provisioning flow which sets up a managed profile.
185      *
186      * <p>A managed profile allows data separation for example for the usage of a
187      * device as a personal and corporate device. The user which provisioning is started from and
188      * the managed profile share a launcher.
189      *
190      * <p>This intent will typically be sent by a mobile device management application (MDM).
191      * Provisioning adds a managed profile and sets the MDM as the profile owner who has full
192      * control over the profile.
193      *
194      * <p>It is possible to check if provisioning is allowed or not by querying the method
195      * {@link #isProvisioningAllowed(String)}.
196      *
197      * <p>In version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this intent must contain the
198      * extra {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}.
199      * As of {@link android.os.Build.VERSION_CODES#M}, it should contain the extra
200      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead, although specifying only
201      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported.
202      *
203      * <p>The intent may also contain the following extras:
204      * <ul>
205      * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, optional </li>
206      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional, supported from
207      * {@link android.os.Build.VERSION_CODES#N}</li>
208      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
209      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
210      * <li>{@link #EXTRA_PROVISIONING_SKIP_USER_CONSENT}, optional</li>
211      * <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION}, optional</li>
212      * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
213      * </ul>
214      *
215      * <p>When managed provisioning has completed, broadcasts are sent to the application specified
216      * in the provisioning intent. The
217      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the
218      * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in
219      * the primary profile.
220      *
221      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when managed provisioning has
222      * completed, along with the above broadcast, activity intent
223      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the profile owner.
224      *
225      * <p>If provisioning fails, the managedProfile is removed so the device returns to its
226      * previous state.
227      *
228      * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
229      * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
230      * the provisioning flow was successful, although this doesn't guarantee the full flow will
231      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
232      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
233      */
234     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
235     public static final String ACTION_PROVISION_MANAGED_PROFILE
236         = "android.app.action.PROVISION_MANAGED_PROFILE";
237 
238     /**
239      * Activity action: Starts the provisioning flow which sets up a managed user.
240      *
241      * <p>This intent will typically be sent by a mobile device management application (MDM).
242      * Provisioning configures the user as managed user and sets the MDM as the profile
243      * owner who has full control over the user. Provisioning can only happen before user setup has
244      * been completed. Use {@link #isProvisioningAllowed(String)} to check if provisioning is
245      * allowed.
246      *
247      * <p>The intent contains the following extras:
248      * <ul>
249      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
250      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
251      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
252      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
253      * </ul>
254      *
255      * <p>If provisioning fails, the device returns to its previous state.
256      *
257      * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
258      * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
259      * the provisioning flow was successful, although this doesn't guarantee the full flow will
260      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
261      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
262      *
263      * @hide
264      */
265     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
266     public static final String ACTION_PROVISION_MANAGED_USER
267         = "android.app.action.PROVISION_MANAGED_USER";
268 
269     /**
270      * Activity action: Starts the provisioning flow which sets up a managed device.
271      * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
272      *
273      * <p> During device owner provisioning a device admin app is set as the owner of the device.
274      * A device owner has full control over the device. The device owner can not be modified by the
275      * user.
276      *
277      * <p> A typical use case would be a device that is owned by a company, but used by either an
278      * employee or client.
279      *
280      * <p> An intent with this action can be sent only on an unprovisioned device.
281      * It is possible to check if provisioning is allowed or not by querying the method
282      * {@link #isProvisioningAllowed(String)}.
283      *
284      * <p>The intent contains the following extras:
285      * <ul>
286      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
287      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
288      * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
289      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
290      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
291      * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
292      * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional</li>
293      * </ul>
294      *
295      * <p>When device owner provisioning has completed, an intent of the type
296      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
297      * device owner.
298      *
299      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
300      * completed, along with the above broadcast, activity intent
301      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
302      *
303      * <p>If provisioning fails, the device is factory reset.
304      *
305      * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
306      * of the provisioning flow was successful, although this doesn't guarantee the full flow will
307      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
308      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
309      *
310      * @deprecated to support {@link android.os.Build.VERSION_CODES#S} and later, admin apps must
311      * implement activities with intent filters for the {@link #ACTION_GET_PROVISIONING_MODE} and
312      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} intent actions; using {@link
313      * #ACTION_PROVISION_MANAGED_DEVICE} to start provisioning will cause the provisioning to fail;
314      * to additionally support pre-{@link android.os.Build.VERSION_CODES#S}, admin apps must also
315      * continue to use this constant.
316      */
317     @Deprecated
318     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
319     public static final String ACTION_PROVISION_MANAGED_DEVICE
320         = "android.app.action.PROVISION_MANAGED_DEVICE";
321 
322     /**
323      * Activity action: launch when user provisioning completed, i.e.
324      * {@link #getUserProvisioningState()} returns one of the complete state.
325      *
326      * <p> Please note that the API behavior is not necessarily consistent across various releases,
327      * and devices, as it's contract between SetupWizard and ManagedProvisioning. The default
328      * implementation is that ManagedProvisioning launches SetupWizard in NFC provisioning only.
329      *
330      * <p> The activity must be protected by permission
331      * {@link android.Manifest.permission#BIND_DEVICE_ADMIN}, and the process must hold
332      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE} to be launched.
333      * Only one {@link ComponentName} in the entire system should be enabled, and the rest of the
334      * components are not started by this intent.
335      * @hide
336      */
337     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
338     @SystemApi
339     public static final String ACTION_STATE_USER_SETUP_COMPLETE =
340             "android.app.action.STATE_USER_SETUP_COMPLETE";
341 
342     /**
343      * Activity action: Starts the provisioning flow which sets up a managed device.
344      *
345      * <p>During device owner provisioning, a device admin app is downloaded and set as the owner of
346      * the device. A device owner has full control over the device. The device owner can not be
347      * modified by the user and the only way of resetting the device is via factory reset.
348      *
349      * <p>From version {@link android.os.Build.VERSION_CODES#Q}, the admin app can choose
350      * whether to set up a fully managed device or a managed profile. For the admin app to support
351      * this, it must have an activity with intent filter {@link #ACTION_GET_PROVISIONING_MODE} and
352      * another one with intent filter {@link #ACTION_ADMIN_POLICY_COMPLIANCE}. For example:
353      * <pre>
354      * &lt;activity
355      *     android:name=".GetProvisioningModeActivity"
356      *     android:label="@string/app_name"
357      *     android:permission="android.permission.BIND_DEVICE_ADMIN"&gt;
358      *     &lt;intent-filter&gt;
359      *         &lt;action
360      *             android:name="android.app.action.GET_PROVISIONING_MODE" /&gt;
361      *         &lt;category android:name="android.intent.category.DEFAULT" /&gt;
362      *     &lt;/intent-filter&gt;
363      * &lt;/activity&gt;
364      *
365      * &lt;activity
366      *     android:name=".PolicyComplianceActivity"
367      *     android:label="@string/app_name"
368      *     android:permission="android.permission.BIND_DEVICE_ADMIN"&gt;
369      *     &lt;intent-filter&gt;
370      *         &lt;action
371      *             android:name="android.app.action.ADMIN_POLICY_COMPLIANCE" /&gt;
372      *         &lt;category android:name="android.intent.category.DEFAULT" /&gt;
373      *     &lt;/intent-filter&gt;
374      * &lt;/activity&gt;</pre>
375      *
376      * <p>A typical use case would be a device that is owned by a company, but used by either an
377      * employee or client.
378      *
379      * <p>The provisioning message should be sent to an unprovisioned device.
380      *
381      * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
382      * by a privileged app with the permission
383      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
384      *
385      * <p>The provisioning intent contains the following properties:
386      * <ul>
387      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
388      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
389      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
390      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
391      * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
392      * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
393      * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
394      * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
395      * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
396      * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
397      * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
398      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
399      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
400      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
401      * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
402      * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
403      * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
404      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
405      * <li>{@link #EXTRA_PROVISIONING_USE_MOBILE_DATA}, optional </li>
406      * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional - when not used for
407      * cloud enrollment, NFC or QR provisioning</li>
408      * </ul>
409      *
410      * @hide
411      */
412     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
413     @SystemApi
414     public static final String ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
415             "android.app.action.PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
416 
417     /**
418      * Activity action: Starts the provisioning flow which sets up a financed device.
419      *
420      * <p>During financed device provisioning, a device admin app is downloaded and set as the owner
421      * of the device. A device owner has full control over the device. The device owner can not be
422      * modified by the user.
423      *
424      * <p>A typical use case would be a device that is bought from the reseller through financing
425      * program.
426      *
427      * <p>An intent with this action can be sent only on an unprovisioned device.
428      *
429      * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
430      * by a privileged app with the permission
431      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
432      *
433      * <p>The provisioning intent contains the following properties:
434      * <ul>
435      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
436      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
437      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
438      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
439      * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
440      * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
441      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
442      * </ul>
443      *
444      * @hide
445      */
446     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
447     @SystemApi
448     public static final String ACTION_PROVISION_FINANCED_DEVICE =
449             "android.app.action.PROVISION_FINANCED_DEVICE";
450 
451     /**
452      * Activity action: Finalizes management provisioning, should be used after user-setup
453      * has been completed and {@link #getUserProvisioningState()} returns one of:
454      * <ul>
455      * <li>{@link #STATE_USER_SETUP_INCOMPLETE}</li>
456      * <li>{@link #STATE_USER_SETUP_COMPLETE}</li>
457      * <li>{@link #STATE_USER_PROFILE_COMPLETE}</li>
458      * </ul>
459      *
460      * @hide
461      */
462     @SystemApi
463     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
464     public static final String ACTION_PROVISION_FINALIZATION
465             = "android.app.action.PROVISION_FINALIZATION";
466 
467     /**
468      * Action: Bugreport sharing with device owner has been accepted by the user.
469      *
470      * @hide
471      */
472     public static final String ACTION_BUGREPORT_SHARING_ACCEPTED =
473             "com.android.server.action.REMOTE_BUGREPORT_SHARING_ACCEPTED";
474 
475     /**
476      * Action: Bugreport sharing with device owner has been declined by the user.
477      *
478      * @hide
479      */
480     public static final String ACTION_BUGREPORT_SHARING_DECLINED =
481             "com.android.server.action.REMOTE_BUGREPORT_SHARING_DECLINED";
482 
483     /**
484      * Action: Bugreport has been collected and is dispatched to {@code DevicePolicyManagerService}.
485      *
486      * @hide
487      */
488     public static final String ACTION_REMOTE_BUGREPORT_DISPATCH =
489             "android.intent.action.REMOTE_BUGREPORT_DISPATCH";
490 
491     /**
492      * Extra for shared bugreport's SHA-256 hash.
493      *
494      * @hide
495      */
496     public static final String EXTRA_REMOTE_BUGREPORT_HASH =
497             "android.intent.extra.REMOTE_BUGREPORT_HASH";
498 
499     /**
500      * Extra for remote bugreport notification shown type.
501      *
502      * @hide
503      */
504     public static final String EXTRA_BUGREPORT_NOTIFICATION_TYPE =
505             "android.app.extra.bugreport_notification_type";
506 
507     /**
508      * Default value for preferential network service enabling.
509      *
510      * @hide
511      */
512     public static final boolean PREFERENTIAL_NETWORK_SERVICE_ENABLED_DEFAULT = false;
513 
514     /**
515      * Notification type for a started remote bugreport flow.
516      *
517      * @hide
518      */
519     public static final int NOTIFICATION_BUGREPORT_STARTED = 1;
520 
521     /**
522      * Notification type for a bugreport that has already been accepted to be shared, but is still
523      * being taken.
524      *
525      * @hide
526      */
527     public static final int NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED = 2;
528 
529     /**
530      * Notification type for a bugreport that has been taken and can be shared or declined.
531      *
532      * @hide
533      */
534     public static final int NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED = 3;
535 
536     /**
537      * Default and maximum timeout in milliseconds after which unlocking with weak auth times out,
538      * i.e. the user has to use a strong authentication method like password, PIN or pattern.
539      *
540      * @hide
541      */
542     public static final long DEFAULT_STRONG_AUTH_TIMEOUT_MS = 72 * 60 * 60 * 1000; // 72h
543 
544     /**
545      * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that
546      * allows a mobile device management application or NFC programmer application which starts
547      * managed provisioning to pass data to the management application instance after provisioning.
548      * <p>
549      * If used with {@link #ACTION_PROVISION_MANAGED_PROFILE} it can be used by the application that
550      * sends the intent to pass data to itself on the newly created profile.
551      * If used with {@link #ACTION_PROVISION_MANAGED_DEVICE} it allows passing data to the same
552      * instance of the app on the primary user.
553      * Starting from {@link android.os.Build.VERSION_CODES#M}, if used with
554      * {@link #MIME_TYPE_PROVISIONING_NFC} as part of NFC managed device provisioning, the NFC
555      * message should contain a stringified {@link java.util.Properties} instance, whose string
556      * properties will be converted into a {@link android.os.PersistableBundle} and passed to the
557      * management application after provisioning.
558      *
559      * <p>Admin apps will receive this extra in their {@link #ACTION_GET_PROVISIONING_MODE} and
560      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} intent handlers. Additionally, {@link
561      * #ACTION_GET_PROVISIONING_MODE} may also return this extra which will then be sent over to
562      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE}, alongside the original values that were passed to
563      * {@link #ACTION_GET_PROVISIONING_MODE}.
564      *
565      * <p>
566      * In both cases the application receives the data in
567      * {@link DeviceAdminReceiver#onProfileProvisioningComplete} via an intent with the action
568      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}. The bundle is not changed
569      * during the managed provisioning.
570      */
571     public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE =
572             "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE";
573 
574     /**
575      * A String extra holding the package name of the mobile device management application that
576      * will be set as the profile owner or device owner.
577      *
578      * <p>If an application starts provisioning directly via an intent with action
579      * {@link #ACTION_PROVISION_MANAGED_PROFILE} this package has to match the package name of the
580      * application that started provisioning. The package will be set as profile owner in that case.
581      *
582      * <p>This package is set as device owner when device owner provisioning is started by an NFC
583      * message containing an NFC record with MIME type {@link #MIME_TYPE_PROVISIONING_NFC}.
584      *
585      * <p> When this extra is set, the application must have exactly one device admin receiver.
586      * This receiver will be set as the profile or device owner and active admin.
587      *
588      * @see DeviceAdminReceiver
589      * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}. This extra is still
590      * supported, but only if there is only one device admin receiver in the package that requires
591      * the permission {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
592      */
593     @Deprecated
594     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME
595         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME";
596 
597     /**
598      * A ComponentName extra indicating the device admin receiver of the mobile device management
599      * application that will be set as the profile owner or device owner and active admin.
600      *
601      * <p>If an application starts provisioning directly via an intent with action
602      * {@link #ACTION_PROVISION_MANAGED_PROFILE} or
603      * {@link #ACTION_PROVISION_MANAGED_DEVICE} the package name of this
604      * component has to match the package name of the application that started provisioning.
605      *
606      * <p>This component is set as device owner and active admin when device owner provisioning is
607      * started by an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or by an NFC
608      * message containing an NFC record with MIME type
609      * {@link #MIME_TYPE_PROVISIONING_NFC}. For the NFC record, the component name must be
610      * flattened to a string, via {@link ComponentName#flattenToShortString()}.
611      *
612      * @see DeviceAdminReceiver
613      */
614     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME
615         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME";
616 
617     /**
618      * An {@link android.accounts.Account} extra holding the account to migrate during managed
619      * profile provisioning. If the account supplied is present in the primary user, it will be
620      * copied, along with its credentials to the managed profile and removed from the primary user.
621      *
622      * Use with {@link #ACTION_PROVISION_MANAGED_PROFILE}, with managed account provisioning, or
623      * return as an extra to the intent result from the {@link #ACTION_GET_PROVISIONING_MODE}
624      * activity.
625      */
626 
627     public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
628         = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE";
629 
630     /**
631      * Boolean extra to indicate that the migrated account should be kept. This is used in
632      * conjunction with {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}. If it's set to {@code true},
633      * the account will not be removed from the primary user after it is migrated to the newly
634      * created user or profile.
635      *
636      * <p> Defaults to {@code false}
637      *
638      * <p> Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or set as an extra to the
639      * intent result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
640      *
641      * @see #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
642      */
643     public static final String EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION
644             = "android.app.extra.PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION";
645 
646     /**
647      * @deprecated From {@link android.os.Build.VERSION_CODES#O}, never used while provisioning the
648      * device.
649      */
650     @Deprecated
651     public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
652         = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
653 
654     /**
655      * A integer extra indicating the predominant color to show during the provisioning.
656      * Refer to {@link android.graphics.Color} for how the color is represented.
657      *
658      * <p>Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or
659      * {@link #ACTION_PROVISION_MANAGED_DEVICE}.
660      *
661      * @deprecated Color customization is no longer supported in the provisioning flow.
662      */
663     @Deprecated
664     public static final String EXTRA_PROVISIONING_MAIN_COLOR =
665              "android.app.extra.PROVISIONING_MAIN_COLOR";
666 
667     /**
668      * A Boolean extra that can be used by the mobile device management application to skip the
669      * disabling of system apps during provisioning when set to {@code true}.
670      *
671      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC}, an intent with action
672      * {@link #ACTION_PROVISION_MANAGED_PROFILE} that starts profile owner provisioning or
673      * set as an extra to the intent result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
674      */
675     public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED =
676             "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED";
677 
678     /**
679      * A String extra holding the time zone {@link android.app.AlarmManager} that the device
680      * will be set to.
681      *
682      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
683      * provisioning via an NFC bump.
684      */
685     public static final String EXTRA_PROVISIONING_TIME_ZONE
686         = "android.app.extra.PROVISIONING_TIME_ZONE";
687 
688     /**
689      * A Long extra holding the wall clock time (in milliseconds) to be set on the device's
690      * {@link android.app.AlarmManager}.
691      *
692      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
693      * provisioning via an NFC bump.
694      */
695     public static final String EXTRA_PROVISIONING_LOCAL_TIME
696         = "android.app.extra.PROVISIONING_LOCAL_TIME";
697 
698     /**
699      * A String extra holding the {@link java.util.Locale} that the device will be set to.
700      * Format: xx_yy, where xx is the language code, and yy the country code.
701      *
702      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
703      * provisioning via an NFC bump.
704      */
705     public static final String EXTRA_PROVISIONING_LOCALE
706         = "android.app.extra.PROVISIONING_LOCALE";
707 
708     /**
709      * A String extra holding the ssid of the wifi network that should be used during nfc device
710      * owner provisioning for downloading the mobile device management application.
711      *
712      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
713      * provisioning via an NFC bump.
714      */
715     public static final String EXTRA_PROVISIONING_WIFI_SSID
716         = "android.app.extra.PROVISIONING_WIFI_SSID";
717 
718     /**
719      * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
720      * is hidden or not.
721      *
722      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
723      * provisioning via an NFC bump.
724      */
725     public static final String EXTRA_PROVISIONING_WIFI_HIDDEN
726         = "android.app.extra.PROVISIONING_WIFI_HIDDEN";
727 
728     /**
729      * A String extra indicating the security type of the wifi network in
730      * {@link #EXTRA_PROVISIONING_WIFI_SSID} and could be one of {@code NONE}, {@code WPA},
731      * {@code WEP} or {@code EAP}.
732      *
733      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
734      * provisioning via an NFC bump.
735      */
736     public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE
737         = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE";
738 
739     /**
740      * A String extra holding the password of the wifi network in
741      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
742      *
743      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
744      * provisioning via an NFC bump.
745      */
746     public static final String EXTRA_PROVISIONING_WIFI_PASSWORD =
747             "android.app.extra.PROVISIONING_WIFI_PASSWORD";
748 
749     /**
750      * The EAP method of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
751      * and could be one of {@code PEAP}, {@code TLS}, {@code TTLS}, {@code PWD}, {@code SIM},
752      * {@code AKA} or {@code AKA_PRIME}. This is only used if the
753      * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
754      *
755      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
756      * provisioning via an NFC bump. It can also be used for QR code provisioning.
757      */
758     public static final String EXTRA_PROVISIONING_WIFI_EAP_METHOD =
759             "android.app.extra.PROVISIONING_WIFI_EAP_METHOD";
760 
761     /**
762      * The phase 2 authentication of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
763      * and could be one of {@code NONE}, {@code PAP}, {@code MSCHAP}, {@code MSCHAPV2}, {@code GTC},
764      * {@code SIM}, {@code AKA} or {@code AKA_PRIME}. This is only used if the
765      * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
766      *
767      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
768      * provisioning via an NFC bump. It can also be used for QR code provisioning.
769      */
770     public static final String EXTRA_PROVISIONING_WIFI_PHASE2_AUTH =
771             "android.app.extra.PROVISIONING_WIFI_PHASE2_AUTH";
772 
773     /**
774      * The CA certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This should
775      * be an X.509 certificate Base64 encoded DER format, ie. PEM representation of a certificate
776      * without header, footer and line breaks. <a href=
777      * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only
778      * used if the {@link
779      * #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
780      *
781      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
782      * provisioning via an NFC bump. It can also be used for QR code provisioning.
783      */
784     public static final String EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE =
785             "android.app.extra.PROVISIONING_WIFI_CA_CERTIFICATE";
786 
787     /**
788      * The user certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This
789      * should be an X.509 certificate and private key Base64 encoded DER format, ie. PEM
790      * representation of a certificate and key without header, footer and line breaks. <a href=
791      * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only
792      * used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
793      *
794      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
795      * provisioning via an NFC bump. It can also be used for QR code provisioning.
796      */
797     public static final String EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE =
798             "android.app.extra.PROVISIONING_WIFI_USER_CERTIFICATE";
799 
800     /**
801      * The identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used
802      * if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
803      *
804      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
805      * provisioning via an NFC bump. It can also be used for QR code provisioning.
806      */
807     public static final String EXTRA_PROVISIONING_WIFI_IDENTITY =
808             "android.app.extra.PROVISIONING_WIFI_IDENTITY";
809 
810     /**
811      * The anonymous identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is
812      * only used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
813      *
814      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
815      * provisioning via an NFC bump. It can also be used for QR code provisioning.
816      */
817 
818     public static final String EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY =
819             "android.app.extra.PROVISIONING_WIFI_ANONYMOUS_IDENTITY";
820     /**
821      * The domain of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used if
822      * the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
823      *
824      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
825      * provisioning via an NFC bump. It can also be used for QR code provisioning.
826      */
827     public static final String EXTRA_PROVISIONING_WIFI_DOMAIN =
828             "android.app.extra.PROVISIONING_WIFI_DOMAIN";
829 
830     /**
831      * A String extra holding the proxy host for the wifi network in
832      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
833      *
834      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
835      * provisioning via an NFC bump.
836      */
837     public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST
838         = "android.app.extra.PROVISIONING_WIFI_PROXY_HOST";
839 
840     /**
841      * An int extra holding the proxy port for the wifi network in
842      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
843      *
844      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
845      * provisioning via an NFC bump.
846      */
847     public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT
848         = "android.app.extra.PROVISIONING_WIFI_PROXY_PORT";
849 
850     /**
851      * A String extra holding the proxy bypass for the wifi network in
852      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
853      *
854      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
855      * provisioning via an NFC bump.
856      */
857     public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS
858         = "android.app.extra.PROVISIONING_WIFI_PROXY_BYPASS";
859 
860     /**
861      * A String extra holding the proxy auto-config (PAC) URL for the wifi network in
862      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
863      *
864      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
865      * provisioning via an NFC bump.
866      */
867     public static final String EXTRA_PROVISIONING_WIFI_PAC_URL
868         = "android.app.extra.PROVISIONING_WIFI_PAC_URL";
869 
870     /**
871      * A String extra holding a url that specifies the download location of the device admin
872      * package. When not provided it is assumed that the device admin package is already installed.
873      *
874      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
875      * provisioning via an NFC bump.
876      */
877     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION
878         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION";
879 
880     /**
881      * A String extra holding the localized name of the organization under management.
882      *
883      * The name is displayed only during provisioning.
884      *
885      * <p>Use in an intent with action {@link #ACTION_PROVISION_FINANCED_DEVICE}
886      *
887      * @hide
888      */
889     @SystemApi
890     public static final String EXTRA_PROVISIONING_ORGANIZATION_NAME =
891             "android.app.extra.PROVISIONING_ORGANIZATION_NAME";
892 
893     /**
894      * A String extra holding a url to the website of the device provider so the user can open it
895      * during provisioning. If the url is not HTTPS, an error will be shown.
896      *
897      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
898      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
899      *
900      * @hide
901      */
902     @SystemApi
903     public static final String EXTRA_PROVISIONING_SUPPORT_URL =
904             "android.app.extra.PROVISIONING_SUPPORT_URL";
905 
906     /**
907      * A String extra holding the localized name of the device admin package. It should be the same
908      * as the app label of the package.
909      *
910      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
911      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
912      *
913      * @deprecated This extra is no longer respected in the provisioning flow.
914      * @hide
915      */
916     @Deprecated
917     @SystemApi
918     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL =
919             "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL";
920 
921     /**
922      * A {@link Uri} extra pointing to the app icon of device admin package. This image will be
923      * shown during the provisioning.
924      * <h5>The following URI schemes are accepted:</h5>
925      * <ul>
926      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
927      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
928      * </ul>
929      *
930      * <p> It is the responsibility of the caller to provide an image with a reasonable
931      * pixel density for the device.
932      *
933      * <p> If a content: URI is passed, the intent should have the flag
934      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
935      * {@link android.content.ClipData} of the intent too.
936      *
937      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
938      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
939      *
940      * @deprecated This extra is no longer respected in the provisioning flow.
941      * @hide
942      */
943     @SystemApi
944     @Deprecated
945     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI =
946             "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI";
947 
948     /**
949      * An int extra holding a minimum required version code for the device admin package. If the
950      * device admin is already installed on the device, it will only be re-downloaded from
951      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION} if the version of the
952      * installed package is less than this version code.
953      *
954      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
955      * provisioning via an NFC bump.
956      */
957     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE
958         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE";
959 
960     /**
961      * A String extra holding a http cookie header which should be used in the http request to the
962      * url specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
963      *
964      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
965      * provisioning via an NFC bump.
966      */
967     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER
968         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER";
969 
970     /**
971      * A String extra holding the URL-safe base64 encoded SHA-256 hash of the file at download
972      * location specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
973      *
974      * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM} must be
975      * present. The provided checksum must match the checksum of the file at the download
976      * location. If the checksum doesn't match an error will be shown to the user and the user will
977      * be asked to factory reset the device.
978      *
979      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
980      * provisioning via an NFC bump.
981      *
982      * <p><strong>Note:</strong> for devices running {@link android.os.Build.VERSION_CODES#LOLLIPOP}
983      * and {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} only SHA-1 hash is supported.
984      * Starting from {@link android.os.Build.VERSION_CODES#M}, this parameter accepts SHA-256 in
985      * addition to SHA-1. From {@link android.os.Build.VERSION_CODES#Q}, only SHA-256 hash is
986      * supported.
987      */
988     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM
989         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM";
990 
991     /**
992      * A boolean extra indicating the admin of a fully-managed device opts out of controlling
993      * permission grants for sensor-related permissions,
994      * see {@link #setPermissionGrantState(ComponentName, String, String, int)}.
995      *
996      * The default for this extra is {@code false} - by default, the admin of a fully-managed
997      * device has the ability to grant sensors-related permissions.
998      *
999      * <p>Use only for device owner provisioning.
1000      * @see #ACTION_GET_PROVISIONING_MODE
1001      */
1002     public static final String EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT =
1003             "android.app.extra.PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT";
1004 
1005     /**
1006      * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
1007      * android package archive at the download location specified in {@link
1008      * #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
1009      *
1010      * <p>The signatures of an android package archive can be obtained using
1011      * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
1012      * {@link android.content.pm.PackageManager#GET_SIGNATURES}.
1013      *
1014      * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM} must be
1015      * present. The provided checksum must match the checksum of any signature of the file at
1016      * the download location. If the checksum does not match an error will be shown to the user and
1017      * the user will be asked to factory reset the device.
1018      *
1019      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1020      * provisioning via an NFC bump.
1021      */
1022     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM
1023         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM";
1024 
1025     /**
1026      * Broadcast Action: This broadcast is sent to indicate that provisioning of a managed profile
1027      * has completed successfully.
1028      *
1029      * <p>The broadcast is limited to the primary profile, to the app specified in the provisioning
1030      * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
1031      *
1032      * <p>This intent will contain the following extras
1033      * <ul>
1034      * <li>{@link Intent#EXTRA_USER}, corresponds to the {@link UserHandle} of the managed
1035      * profile.</li>
1036      * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, corresponds to the account requested to
1037      * be migrated at provisioning time, if any.</li>
1038      * </ul>
1039      */
1040     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1041     public static final String ACTION_MANAGED_PROFILE_PROVISIONED
1042         = "android.app.action.MANAGED_PROFILE_PROVISIONED";
1043 
1044     /**
1045      * Activity action: This activity action is sent to indicate that provisioning of a managed
1046      * profile or managed device has completed successfully. It'll be sent at the same time as
1047      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast but this will be
1048      * delivered faster as it's an activity intent.
1049      *
1050      * <p>The intent is only sent to the new device or profile owner.
1051      *
1052      * @see #ACTION_PROVISION_MANAGED_PROFILE
1053      * @see #ACTION_PROVISION_MANAGED_DEVICE
1054      */
1055     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1056     public static final String ACTION_PROVISIONING_SUCCESSFUL =
1057             "android.app.action.PROVISIONING_SUCCESSFUL";
1058 
1059     /**
1060      * A boolean extra indicating whether device encryption can be skipped as part of device owner
1061      * or managed profile provisioning.
1062      *
1063      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
1064      * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
1065      *
1066      * <p>From {@link android.os.Build.VERSION_CODES#N} onwards, this is also supported for an
1067      * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
1068      */
1069     public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION =
1070              "android.app.extra.PROVISIONING_SKIP_ENCRYPTION";
1071 
1072     /**
1073      * A {@link Uri} extra pointing to a logo image. This image will be shown during the
1074      * provisioning. If this extra is not passed, a default image will be shown.
1075      * <h5>The following URI schemes are accepted:</h5>
1076      * <ul>
1077      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1078      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1079      * </ul>
1080      *
1081      * <p> It is the responsibility of the caller to provide an image with a reasonable
1082      * pixel density for the device.
1083      *
1084      * <p> If a content: URI is passed, the intent should have the flag
1085      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1086      * {@link android.content.ClipData} of the intent too.
1087      *
1088      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1089      * {@link #ACTION_PROVISION_MANAGED_DEVICE}
1090      */
1091     public static final String EXTRA_PROVISIONING_LOGO_URI =
1092             "android.app.extra.PROVISIONING_LOGO_URI";
1093 
1094     /**
1095      * A {@link Bundle}[] extra consisting of list of disclaimer headers and disclaimer contents.
1096      * Each {@link Bundle} must have both {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}
1097      * as disclaimer header, and {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} as disclaimer
1098      * content.
1099      *
1100      * <p> The extra typically contains one disclaimer from the company of mobile device
1101      * management application (MDM), and one disclaimer from the organization.
1102      *
1103      * <p> Call {@link Bundle#putParcelableArray(String, Parcelable[])} to put the {@link Bundle}[]
1104      *
1105      * <p> Maximum 3 key-value pairs can be specified. The rest will be ignored.
1106      *
1107      * <p> Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1108      * {@link #ACTION_PROVISION_MANAGED_DEVICE}
1109      */
1110     public static final String EXTRA_PROVISIONING_DISCLAIMERS =
1111             "android.app.extra.PROVISIONING_DISCLAIMERS";
1112 
1113     /**
1114      * A String extra of localized disclaimer header.
1115      *
1116      * <p> The extra is typically the company name of mobile device management application (MDM)
1117      * or the organization name.
1118      *
1119      * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
1120      *
1121      * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
1122      * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
1123      * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT}. Here is the example:
1124      *
1125      * <pre>
1126      *  &lt;meta-data
1127      *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_HEADER"
1128      *      android:resource="@string/disclaimer_header"
1129      * /&gt;</pre>
1130      */
1131     public static final String EXTRA_PROVISIONING_DISCLAIMER_HEADER =
1132             "android.app.extra.PROVISIONING_DISCLAIMER_HEADER";
1133 
1134     /**
1135      * A {@link Uri} extra pointing to disclaimer content.
1136      *
1137      * <h5>The following URI schemes are accepted:</h5>
1138      * <ul>
1139      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1140      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1141      * </ul>
1142      *
1143      * <p> Styled text is supported in the disclaimer content. The content is parsed by
1144      * {@link android.text.Html#fromHtml(String)} and displayed in a
1145      * {@link android.widget.TextView}.
1146      *
1147      * <p> If a <code>content:</code> URI is passed, URI is passed, the intent should have the flag
1148      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1149      * {@link android.content.ClipData} of the intent too.
1150      *
1151      * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
1152      *
1153      * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
1154      * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
1155      * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}. Here is the example:
1156      *
1157      * <pre>
1158      *  &lt;meta-data
1159      *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_CONTENT"
1160      *      android:resource="@string/disclaimer_content"
1161      * /&gt;</pre>
1162      */
1163     public static final String EXTRA_PROVISIONING_DISCLAIMER_CONTENT =
1164             "android.app.extra.PROVISIONING_DISCLAIMER_CONTENT";
1165 
1166     /**
1167      * A boolean extra indicating if the user consent steps from the provisioning flow should be
1168      * skipped. If unspecified, defaults to {@code false}.
1169      *
1170      * It can only be used by an existing device owner trying to create a managed profile via
1171      * {@link #ACTION_PROVISION_MANAGED_PROFILE}. Otherwise it is ignored.
1172      *
1173      * @deprecated this extra is no longer relevant as device owners cannot create managed profiles
1174      */
1175     @Deprecated
1176     public static final String EXTRA_PROVISIONING_SKIP_USER_CONSENT =
1177             "android.app.extra.PROVISIONING_SKIP_USER_CONSENT";
1178 
1179     /**
1180      * A boolean extra indicating if the education screens from the provisioning flow should be
1181      * skipped. If unspecified, defaults to {@code false}.
1182      *
1183      * <p>This extra can be set in the following ways:
1184      * <ul>
1185      * <li>By the admin app when performing the admin-integrated
1186      * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity</li>
1187      * <li>For managed account enrollment</li>
1188      * </ul>
1189      *
1190      * <p>If the education screens are skipped, it is the admin application's responsibility
1191      * to display its own user education screens.
1192      */
1193     public static final String EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS =
1194             "android.app.extra.PROVISIONING_SKIP_EDUCATION_SCREENS";
1195 
1196     /**
1197      * A boolean extra indicating if mobile data should be used during NFC device owner provisioning
1198      * for downloading the mobile device management application. If {@link
1199      * #EXTRA_PROVISIONING_WIFI_SSID} is also specified, wifi network will be used instead.
1200      *
1201      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1202      * provisioning via an NFC bump.
1203      *
1204      * @hide
1205      */
1206     public static final String EXTRA_PROVISIONING_USE_MOBILE_DATA =
1207             "android.app.extra.PROVISIONING_USE_MOBILE_DATA";
1208 
1209     /**
1210      * Possible values for {@link #EXTRA_PROVISIONING_TRIGGER}.
1211      *
1212      * @hide
1213      */
1214     @IntDef(prefix = { "PROVISIONING_TRIGGER_" }, value = {
1215             PROVISIONING_TRIGGER_UNSPECIFIED,
1216             PROVISIONING_TRIGGER_CLOUD_ENROLLMENT,
1217             PROVISIONING_TRIGGER_QR_CODE,
1218             PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER,
1219             PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1220     })
1221     @Retention(RetentionPolicy.SOURCE)
1222     public @interface ProvisioningTrigger {}
1223 
1224     /**
1225      * Flags for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES}.
1226      *
1227      * @hide
1228      */
1229     @IntDef(flag = true, prefix = { "FLAG_SUPPORTED_MODES_" }, value = {
1230             FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED,
1231             FLAG_SUPPORTED_MODES_PERSONALLY_OWNED,
1232             FLAG_SUPPORTED_MODES_DEVICE_OWNER
1233     })
1234     @Retention(RetentionPolicy.SOURCE)
1235     public @interface ProvisioningConfiguration {}
1236 
1237     /**
1238      * A String extra holding the provisioning trigger. It could be one of
1239      * {@link #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT}, {@link #PROVISIONING_TRIGGER_QR_CODE},
1240      * {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} or {@link
1241      * #PROVISIONING_TRIGGER_UNSPECIFIED}.
1242      *
1243      * <p>Use in an intent with action {@link
1244      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}.
1245      * @hide
1246      */
1247     @SystemApi
1248     public static final String EXTRA_PROVISIONING_TRIGGER =
1249             "android.app.extra.PROVISIONING_TRIGGER";
1250 
1251     /**
1252      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1253      * trigger has not been specified.
1254      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1255      * @see #PROVISIONING_TRIGGER_QR_CODE
1256      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1257      * @hide
1258      */
1259     @SystemApi
1260     public static final int PROVISIONING_TRIGGER_UNSPECIFIED = 0;
1261 
1262     /**
1263      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1264      * trigger is cloud enrollment.
1265      * @see #PROVISIONING_TRIGGER_QR_CODE
1266      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1267      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1268      * @hide
1269      */
1270     @SystemApi
1271     public static final int PROVISIONING_TRIGGER_CLOUD_ENROLLMENT = 1;
1272 
1273     /**
1274      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1275      * trigger is the QR code scanner.
1276      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1277      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1278      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1279      * @hide
1280      */
1281     @SystemApi
1282     public static final int PROVISIONING_TRIGGER_QR_CODE = 2;
1283 
1284     /**
1285      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1286      * trigger is persistent device owner enrollment.
1287      * <p>This constant is meant to represent a specific type of managed account provisioning which
1288      * provisions a device to a device owner by invoking the standard provisioning flow (where
1289      * the ManagedProvisioning component downloads and installs the admin app), as opposed to
1290      * relying on the provisioning trigger to handle download and install of the admin app.
1291      * <p>As of {@link android.os.Build.VERSION_CODES#S}, this constant is no longer used in favor
1292      * of the more general {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} which handles all managed
1293      * account provisioning types.
1294      * @deprecated Use the broader {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} instead
1295      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1296      * @see #PROVISIONING_TRIGGER_QR_CODE
1297      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1298      * @hide
1299      */
1300     @SystemApi
1301     @Deprecated
1302     public static final int PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER = 3;
1303 
1304     /**
1305      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1306      * trigger is managed account enrollment.
1307      * <p>
1308      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1309      * @see #PROVISIONING_TRIGGER_QR_CODE
1310      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1311      * @hide
1312      */
1313     @SystemApi
1314     public static final int PROVISIONING_TRIGGER_MANAGED_ACCOUNT = 4;
1315 
1316     /**
1317      * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that provisioning is
1318      * organization-owned.
1319      *
1320      * <p>Using this value indicates the admin app can only be provisioned in either a
1321      * fully-managed device or a corporate-owned work profile. This will cause the admin app's
1322      * {@link #ACTION_GET_PROVISIONING_MODE} activity to have the {@link
1323      * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
1324      * #PROVISIONING_MODE_MANAGED_PROFILE} and {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}.
1325      *
1326      * <p>Also, if this flag is set, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity
1327      * will not receive the {@link #EXTRA_PROVISIONING_IMEI} and {@link
1328      * #EXTRA_PROVISIONING_SERIAL_NUMBER} extras.
1329      *
1330      * <p>This flag can be combined with {@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}. In
1331      * that case, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity will have
1332      * the {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
1333      * #PROVISIONING_MODE_MANAGED_PROFILE}, {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE} and
1334      * {@link #PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE}.
1335      *
1336      * @hide
1337      */
1338     @SystemApi
1339     public static final int FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED = 1;
1340 
1341     /**
1342      * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that provisioning
1343      * is personally-owned.
1344      *
1345      * <p>Using this flag will cause the admin app's {@link #ACTION_GET_PROVISIONING_MODE}
1346      * activity to have the {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra
1347      * contain only {@link #PROVISIONING_MODE_MANAGED_PROFILE}.
1348      *
1349      * <p>This flag can be combined with {@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}. In
1350      * that case, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity will have the
1351      * {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
1352      * #PROVISIONING_MODE_MANAGED_PROFILE}, {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE} and
1353      * {@link #PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE}.
1354      *
1355      * @hide
1356      */
1357     @SystemApi
1358     public static final int FLAG_SUPPORTED_MODES_PERSONALLY_OWNED = 1 << 1;
1359 
1360     /**
1361      * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that the only
1362      * supported provisioning mode is device owner.
1363      *
1364      * @hide
1365      */
1366     @SystemApi
1367     public static final int FLAG_SUPPORTED_MODES_DEVICE_OWNER = 1 << 2;
1368 
1369     /**
1370      * This MIME type is used for starting the device owner provisioning.
1371      *
1372      * <p>During device owner provisioning a device admin app is set as the owner of the device.
1373      * A device owner has full control over the device. The device owner can not be modified by the
1374      * user and the only way of resetting the device is if the device owner app calls a factory
1375      * reset.
1376      *
1377      * <p> A typical use case would be a device that is owned by a company, but used by either an
1378      * employee or client.
1379      *
1380      * <p> The NFC message must be sent to an unprovisioned device.
1381      *
1382      * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
1383      * contains the following properties:
1384      * <ul>
1385      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
1386      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
1387      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
1388      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
1389      * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
1390      * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
1391      * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
1392      * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
1393      * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
1394      * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
1395      * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
1396      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
1397      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
1398      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
1399      * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
1400      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional, supported from {@link
1401      * android.os.Build.VERSION_CODES#M} </li>
1402      * <li>{@link #EXTRA_PROVISIONING_WIFI_EAP_METHOD}, optional, supported from {@link
1403      * android.os.Build.VERSION_CODES#Q}</li>
1404      * <li>{@link #EXTRA_PROVISIONING_WIFI_PHASE2_AUTH}, optional, supported from {@link
1405      * android.os.Build.VERSION_CODES#Q}</li>
1406      * <li>{@link #EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE}, optional, supported from {@link
1407      * android.os.Build.VERSION_CODES#Q}</li>
1408      * <li>{@link #EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE}, optional, supported from {@link
1409      * android.os.Build.VERSION_CODES#Q}</li>
1410      * <li>{@link #EXTRA_PROVISIONING_WIFI_IDENTITY}, optional, supported from {@link
1411      * android.os.Build.VERSION_CODES#Q}</li>
1412      * <li>{@link #EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY}, optional, supported from {@link
1413      * android.os.Build.VERSION_CODES#Q}</li>
1414      * <li>{@link #EXTRA_PROVISIONING_WIFI_DOMAIN}, optional, supported from {@link
1415      * android.os.Build.VERSION_CODES#Q}</li></ul>
1416      *
1417      * <p>
1418      * As of {@link android.os.Build.VERSION_CODES#M}, the properties should contain
1419      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of
1420      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only
1421      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported).
1422      */
1423     public static final String MIME_TYPE_PROVISIONING_NFC
1424         = "application/com.android.managedprovisioning";
1425 
1426     /**
1427      * Activity action: ask the user to add a new device administrator to the system.
1428      * The desired policy is the ComponentName of the policy in the
1429      * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
1430      * bring the user through adding the device administrator to the system (or
1431      * allowing them to reject it).
1432      *
1433      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1434      * field to provide the user with additional explanation (in addition
1435      * to your component's description) about what is being added.
1436      *
1437      * <p>If your administrator is already active, this will ordinarily return immediately (without
1438      * user intervention).  However, if your administrator has been updated and is requesting
1439      * additional uses-policy flags, the user will be presented with the new list.  New policies
1440      * will not be available to the updated administrator until the user has accepted the new list.
1441      */
1442     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1443     public static final String ACTION_ADD_DEVICE_ADMIN
1444             = "android.app.action.ADD_DEVICE_ADMIN";
1445 
1446     /**
1447      * @hide
1448      * Activity action: ask the user to add a new device administrator as the profile owner
1449      * for this user. Only system apps can launch this intent.
1450      *
1451      * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN}
1452      * extra field. This will invoke a UI to bring the user through adding the profile owner admin
1453      * to remotely control restrictions on the user.
1454      *
1455      * <p>The intent must be invoked via {@link Activity#startActivityForResult} to receive the
1456      * result of whether or not the user approved the action. If approved, the result will
1457      * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well
1458      * as a profile owner.
1459      *
1460      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1461      * field to provide the user with additional explanation (in addition
1462      * to your component's description) about what is being added.
1463      *
1464      * <p>If there is already a profile owner active or the caller is not a system app, the
1465      * operation will return a failure result.
1466      */
1467     @SystemApi
1468     public static final String ACTION_SET_PROFILE_OWNER
1469             = "android.app.action.SET_PROFILE_OWNER";
1470 
1471     /**
1472      * @hide
1473      * Name of the profile owner admin that controls the user.
1474      */
1475     @SystemApi
1476     public static final String EXTRA_PROFILE_OWNER_NAME
1477             = "android.app.extra.PROFILE_OWNER_NAME";
1478 
1479     /**
1480      * Broadcast action: send when any policy admin changes a policy.
1481      * This is generally used to find out when a new policy is in effect.
1482      *
1483      * If the profile owner of an organization-owned managed profile changes some user
1484      * restriction explicitly on the parent user, this broadcast will <em>not</em> be
1485      * sent to the parent user.
1486      * @hide
1487      */
1488     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1489     public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
1490             = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
1491 
1492     /**
1493      * Broadcast action: sent when the device owner is set, changed or cleared.
1494      *
1495      * This broadcast is sent only to the primary user.
1496      * @see #ACTION_PROVISION_MANAGED_DEVICE
1497      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
1498      */
1499     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1500     public static final String ACTION_DEVICE_OWNER_CHANGED
1501             = "android.app.action.DEVICE_OWNER_CHANGED";
1502 
1503     /**
1504      * Broadcast action: sent when the factory reset protection (FRP) policy is changed.
1505      *
1506      * @see #setFactoryResetProtectionPolicy
1507      * @hide
1508      */
1509     @RequiresPermission(android.Manifest.permission.MANAGE_FACTORY_RESET_PROTECTION)
1510     @SystemApi
1511     public static final String ACTION_RESET_PROTECTION_POLICY_CHANGED =
1512             "android.app.action.RESET_PROTECTION_POLICY_CHANGED";
1513 
1514     /**
1515      * The ComponentName of the administrator component.
1516      *
1517      * @see #ACTION_ADD_DEVICE_ADMIN
1518      */
1519     public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
1520 
1521     /**
1522      * An optional CharSequence providing additional explanation for why the
1523      * admin is being added.
1524      *
1525      * @see #ACTION_ADD_DEVICE_ADMIN
1526      */
1527     public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
1528 
1529     /**
1530      * Constant to indicate the feature of disabling the camera. Used as argument to
1531      * {@link #createAdminSupportIntent(String)}.
1532      * @see #setCameraDisabled(ComponentName, boolean)
1533      */
1534     public static final String POLICY_DISABLE_CAMERA = "policy_disable_camera";
1535 
1536     /**
1537      * Constant to indicate the feature of disabling screen captures. Used as argument to
1538      * {@link #createAdminSupportIntent(String)}.
1539      * @see #setScreenCaptureDisabled(ComponentName, boolean)
1540      */
1541     public static final String POLICY_DISABLE_SCREEN_CAPTURE = "policy_disable_screen_capture";
1542 
1543     /**
1544      * Constant to indicate the feature of suspending app. Use it as the value of
1545      * {@link #EXTRA_RESTRICTION}.
1546      * @hide
1547      */
1548     public static final String POLICY_SUSPEND_PACKAGES = "policy_suspend_packages";
1549 
1550     /**
1551      * A String indicating a specific restricted feature. Can be a user restriction from the
1552      * {@link UserManager}, e.g. {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the values
1553      * {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
1554      * @see #createAdminSupportIntent(String)
1555      * @hide
1556      */
1557     @SystemApi
1558     public static final String EXTRA_RESTRICTION = "android.app.extra.RESTRICTION";
1559 
1560     /**
1561      * Activity action: have the user enter a new password.
1562      *
1563      * <p>For admin apps, this activity should be launched after using {@link
1564      * #setPasswordQuality(ComponentName, int)}, or {@link
1565      * #setPasswordMinimumLength(ComponentName, int)} to have the user enter a new password that
1566      * meets the current requirements. You can use {@link #isActivePasswordSufficient()} to
1567      * determine whether you need to have the user select a new password in order to meet the
1568      * current constraints. Upon being resumed from this activity, you can check the new
1569      * password characteristics to see if they are sufficient.
1570      *
1571      * <p>Non-admin apps can use {@link #getPasswordComplexity()} to check the current screen lock
1572      * complexity, and use this activity with extra {@link #EXTRA_PASSWORD_COMPLEXITY} to suggest
1573      * to users how complex the app wants the new screen lock to be. Note that both {@link
1574      * #getPasswordComplexity()} and the extra {@link #EXTRA_PASSWORD_COMPLEXITY} require the
1575      * calling app to have the permission {@link permission#REQUEST_PASSWORD_COMPLEXITY}.
1576      *
1577      * <p>If the intent is launched from within a managed profile with a profile
1578      * owner built against {@link android.os.Build.VERSION_CODES#M} or before,
1579      * this will trigger entering a new password for the parent of the profile.
1580      * For all other cases it will trigger entering a new password for the user
1581      * or profile it is launched from.
1582      *
1583      * @see #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1584      */
1585     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1586     public static final String ACTION_SET_NEW_PASSWORD
1587             = "android.app.action.SET_NEW_PASSWORD";
1588 
1589     /**
1590      * An integer indicating the complexity level of the new password an app would like the user to
1591      * set when launching the action {@link #ACTION_SET_NEW_PASSWORD}.
1592      *
1593      * <p>Must be one of
1594      * <ul>
1595      *     <li>{@link #PASSWORD_COMPLEXITY_HIGH}
1596      *     <li>{@link #PASSWORD_COMPLEXITY_MEDIUM}
1597      *     <li>{@link #PASSWORD_COMPLEXITY_LOW}
1598      *     <li>{@link #PASSWORD_COMPLEXITY_NONE}
1599      * </ul>
1600      *
1601      * <p>If an invalid value is used, it will be treated as {@link #PASSWORD_COMPLEXITY_NONE}.
1602      */
1603     @RequiresPermission(android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY)
1604     public static final String EXTRA_PASSWORD_COMPLEXITY =
1605             "android.app.extra.PASSWORD_COMPLEXITY";
1606 
1607     /**
1608      * Constant for {@link #getPasswordComplexity()} and
1609      * {@link #setRequiredPasswordComplexity(int)}: no password.
1610      *
1611      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
1612      * the exact complexity band the password is in.
1613      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
1614      * band which the password must meet.
1615      */
1616     public static final int PASSWORD_COMPLEXITY_NONE = 0;
1617 
1618     /**
1619      * Constant for {@link #getPasswordComplexity()} and
1620      * {@link #setRequiredPasswordComplexity(int)}.
1621      * Define the low password complexity band as:
1622      * <ul>
1623      * <li>pattern
1624      * <li>PIN with repeating (4444) or ordered (1234, 4321, 2468) sequences
1625      * </ul>
1626      *
1627      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
1628      * the exact complexity band the password is in.
1629      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
1630      * band which the password must meet.
1631      *
1632      * @see #PASSWORD_QUALITY_SOMETHING
1633      * @see #PASSWORD_QUALITY_NUMERIC
1634      */
1635     public static final int PASSWORD_COMPLEXITY_LOW = 0x10000;
1636 
1637     /**
1638      * Constant for {@link #getPasswordComplexity()} and
1639      * {@link #setRequiredPasswordComplexity(int)}.
1640      * Define the medium password complexity band as:
1641      * <ul>
1642      * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
1643      * least 4
1644      * <li>alphabetic, length at least 4
1645      * <li>alphanumeric, length at least 4
1646      * </ul>
1647      *
1648      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
1649      * the exact complexity band the password is in.
1650      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
1651      * band which the password must meet.
1652      *
1653      * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX
1654      * @see #PASSWORD_QUALITY_ALPHABETIC
1655      * @see #PASSWORD_QUALITY_ALPHANUMERIC
1656      */
1657     public static final int PASSWORD_COMPLEXITY_MEDIUM = 0x30000;
1658 
1659     /**
1660      * Constant for {@link #getPasswordComplexity()} and
1661      * {@link #setRequiredPasswordComplexity(int)}.
1662      * Define the high password complexity band as:
1663      * <ul>
1664      * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
1665      * least 8
1666      * <li>alphabetic, length at least 6
1667      * <li>alphanumeric, length at least 6
1668      * </ul>
1669      *
1670      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
1671      * the exact complexity band the password is in.
1672      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
1673      * band which the password must meet.
1674      *
1675      * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX
1676      * @see #PASSWORD_QUALITY_ALPHABETIC
1677      * @see #PASSWORD_QUALITY_ALPHANUMERIC
1678      */
1679     public static final int PASSWORD_COMPLEXITY_HIGH = 0x50000;
1680 
1681     /**
1682      * A boolean extra for {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} requesting that only
1683      * device password requirement is enforced during the parent profile password enrolment flow.
1684      * <p> Normally when enrolling password for the parent profile, both the device-wide password
1685      * requirement (requirement set via {@link #getParentProfileInstance(ComponentName)} instance)
1686      * and the profile password requirement are enforced, if the profile currently does not have a
1687      * separate work challenge. By setting this to {@code true}, profile password requirement is
1688      * explicitly disregarded.
1689      *
1690      * @see #isActivePasswordSufficientForDeviceRequirement()
1691      */
1692     public static final String EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY =
1693             "android.app.extra.DEVICE_PASSWORD_REQUIREMENT_ONLY";
1694 
1695     /**
1696      * @hide
1697      */
1698     @Retention(RetentionPolicy.SOURCE)
1699     @IntDef(prefix = {"PASSWORD_COMPLEXITY_"}, value = {
1700             PASSWORD_COMPLEXITY_NONE,
1701             PASSWORD_COMPLEXITY_LOW,
1702             PASSWORD_COMPLEXITY_MEDIUM,
1703             PASSWORD_COMPLEXITY_HIGH,
1704     })
1705     public @interface PasswordComplexity {}
1706 
1707     /**
1708      * Indicates that nearby streaming is not controlled by policy, which means nearby streaming is
1709      * allowed.
1710      */
1711     public static final int NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY = 0;
1712 
1713     /** Indicates that nearby streaming is disabled. */
1714     public static final int NEARBY_STREAMING_DISABLED = 1;
1715 
1716     /** Indicates that nearby streaming is enabled. */
1717     public static final int NEARBY_STREAMING_ENABLED = 2;
1718 
1719     /**
1720      * Indicates that nearby streaming is enabled only to devices offering a comparable level of
1721      * security, with the same authenticated managed account.
1722      */
1723     public static final int NEARBY_STREAMING_SAME_MANAGED_ACCOUNT_ONLY = 3;
1724 
1725     /**
1726      * @hide
1727      */
1728     @Retention(RetentionPolicy.SOURCE)
1729     @IntDef(prefix = {"NEARBY_STREAMING_"}, value = {
1730         NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY,
1731         NEARBY_STREAMING_DISABLED,
1732         NEARBY_STREAMING_ENABLED,
1733         NEARBY_STREAMING_SAME_MANAGED_ACCOUNT_ONLY,
1734     })
1735     public @interface NearbyStreamingPolicy {}
1736 
1737     /**
1738      * Activity action: have the user enter a new password for the parent profile.
1739      * If the intent is launched from within a managed profile, this will trigger
1740      * entering a new password for the parent of the profile. The caller can optionally
1741      * set {@link #EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY} to only enforce device-wide
1742      * password requirement. In all other cases the behaviour is identical to
1743      * {@link #ACTION_SET_NEW_PASSWORD}.
1744      */
1745     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1746     public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1747             = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD";
1748 
1749     /**
1750      * Broadcast action: Tell the status bar to open the device monitoring dialog, e.g. when
1751      * Network logging was enabled and the user tapped the notification.
1752      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1753      * @hide
1754      */
1755     public static final String ACTION_SHOW_DEVICE_MONITORING_DIALOG
1756             = "android.app.action.SHOW_DEVICE_MONITORING_DIALOG";
1757 
1758     /**
1759      * Broadcast Action: Sent after application delegation scopes are changed. The new delegation
1760      * scopes will be sent in an {@code ArrayList<String>} extra identified by the
1761      * {@link #EXTRA_DELEGATION_SCOPES} key.
1762      *
1763      * <p class="note"><b>Note:</b> This is a protected intent that can only be sent by the
1764      * system.</p>
1765      */
1766     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1767     public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED =
1768             "android.app.action.APPLICATION_DELEGATION_SCOPES_CHANGED";
1769 
1770     /**
1771      * An {@code ArrayList<String>} corresponding to the delegation scopes given to an app in the
1772      * {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} broadcast.
1773      */
1774     public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES";
1775 
1776     /**
1777      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1778      * the parent profile to access intents sent from the managed profile.
1779      * That is, when an app in the managed profile calls
1780      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1781      * matching activity in the parent profile.
1782      */
1783     public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
1784 
1785     /**
1786      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1787      * the managed profile to access intents sent from the parent profile.
1788      * That is, when an app in the parent profile calls
1789      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1790      * matching activity in the managed profile.
1791      */
1792     public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
1793 
1794     /**
1795      * Broadcast action: notify that a new local system update policy has been set by the device
1796      * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
1797      */
1798     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1799     public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
1800             = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
1801 
1802     /**
1803      * Broadcast action from ManagedProvisioning to notify that the latest change to
1804      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has been successfully
1805      * applied (cross profile intent filters updated). Only usesd for CTS tests.
1806      * @hide
1807      */
1808     @TestApi
1809     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1810     public static final String ACTION_DATA_SHARING_RESTRICTION_APPLIED =
1811             "android.app.action.DATA_SHARING_RESTRICTION_APPLIED";
1812 
1813     /**
1814      * Broadcast action: notify that a value of {@link Settings.Global#DEVICE_POLICY_CONSTANTS}
1815      * has been changed.
1816      * @hide
1817      */
1818     @TestApi
1819     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1820     public static final String ACTION_DEVICE_POLICY_CONSTANTS_CHANGED =
1821             "android.app.action.DEVICE_POLICY_CONSTANTS_CHANGED";
1822 
1823     /**
1824      * Permission policy to prompt user for new permission requests for runtime permissions.
1825      * Already granted or denied permissions are not affected by this.
1826      */
1827     public static final int PERMISSION_POLICY_PROMPT = 0;
1828 
1829     /**
1830      * Permission policy to always grant new permission requests for runtime permissions.
1831      * Already granted or denied permissions are not affected by this.
1832      */
1833     public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
1834 
1835     /**
1836      * Permission policy to always deny new permission requests for runtime permissions.
1837      * Already granted or denied permissions are not affected by this.
1838      */
1839     public static final int PERMISSION_POLICY_AUTO_DENY = 2;
1840 
1841     /**
1842      * Possible policy values for permissions.
1843      *
1844      * @hide
1845      */
1846     @IntDef(prefix = { "PERMISSION_GRANT_STATE_" }, value = {
1847             PERMISSION_GRANT_STATE_DEFAULT,
1848             PERMISSION_GRANT_STATE_GRANTED,
1849             PERMISSION_GRANT_STATE_DENIED
1850     })
1851     @Retention(RetentionPolicy.SOURCE)
1852     public @interface PermissionGrantState {}
1853 
1854     /**
1855      * Runtime permission state: The user can manage the permission
1856      * through the UI.
1857      */
1858     public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
1859 
1860     /**
1861      * Runtime permission state: The permission is granted to the app
1862      * and the user cannot manage the permission through the UI.
1863      */
1864     public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
1865 
1866     /**
1867      * Runtime permission state: The permission is denied to the app
1868      * and the user cannot manage the permission through the UI.
1869      */
1870     public static final int PERMISSION_GRANT_STATE_DENIED = 2;
1871 
1872     /**
1873      * Delegation of certificate installation and management. This scope grants access to the
1874      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
1875      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair} APIs.
1876      * This scope also grants the ability to read identifiers that the delegating device owner or
1877      * profile owner can obtain. See {@link #getEnrollmentSpecificId()}.
1878      */
1879     public static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
1880 
1881     /**
1882      * Delegation of application restrictions management. This scope grants access to the
1883      * {@link #setApplicationRestrictions} and {@link #getApplicationRestrictions} APIs.
1884      */
1885     public static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions";
1886 
1887     /**
1888      * Delegation of application uninstall block. This scope grants access to the
1889      * {@link #setUninstallBlocked} API.
1890      */
1891     public static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall";
1892 
1893     /**
1894      * Delegation of permission policy and permission grant state. This scope grants access to the
1895      * {@link #setPermissionPolicy}, {@link #getPermissionGrantState},
1896      * and {@link #setPermissionGrantState} APIs.
1897      */
1898     public static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant";
1899 
1900     /**
1901      * Delegation of package access state. This scope grants access to the
1902      * {@link #isApplicationHidden}, {@link #setApplicationHidden}, {@link #isPackageSuspended}, and
1903      * {@link #setPackagesSuspended} APIs.
1904      */
1905     public static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
1906 
1907     /**
1908      * Delegation for enabling system apps. This scope grants access to the {@link #enableSystemApp}
1909      * API.
1910      */
1911     public static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app";
1912 
1913     /**
1914      * Delegation for installing existing packages. This scope grants access to the
1915      * {@link #installExistingPackage} API.
1916      */
1917     public static final String DELEGATION_INSTALL_EXISTING_PACKAGE =
1918             "delegation-install-existing-package";
1919 
1920     /**
1921      * Delegation of management of uninstalled packages. This scope grants access to the
1922      * {@link #setKeepUninstalledPackages} and {@link #getKeepUninstalledPackages} APIs.
1923      */
1924     public static final String DELEGATION_KEEP_UNINSTALLED_PACKAGES =
1925             "delegation-keep-uninstalled-packages";
1926 
1927     /**
1928      * Grants access to {@link #setNetworkLoggingEnabled}, {@link #isNetworkLoggingEnabled} and
1929      * {@link #retrieveNetworkLogs}. Once granted the delegated app will start receiving
1930      * DelegatedAdminReceiver.onNetworkLogsAvailable() callback, and Device owner or Profile Owner
1931      * will no longer receive the DeviceAdminReceiver.onNetworkLogsAvailable() callback.
1932      * There can be at most one app that has this delegation.
1933      * If another app already had delegated network logging access,
1934      * it will lose the delegation when a new app is delegated.
1935      *
1936      * <p> Can only be granted by Device Owner or Profile Owner of a managed profile.
1937      */
1938     public static final String DELEGATION_NETWORK_LOGGING = "delegation-network-logging";
1939 
1940     /**
1941      * Grants access to selection of KeyChain certificates on behalf of requesting apps.
1942      * Once granted the app will start receiving
1943      * {@link DelegatedAdminReceiver#onChoosePrivateKeyAlias}. The caller (PO/DO) will
1944      * no longer receive {@link DeviceAdminReceiver#onChoosePrivateKeyAlias}.
1945      * There can be at most one app that has this delegation.
1946      * If another app already had delegated certificate selection access,
1947      * it will lose the delegation when a new app is delegated.
1948      * <p> The delegaetd app can also call {@link #grantKeyPairToApp} and
1949      * {@link #revokeKeyPairFromApp} to directly grant KeyCain keys to other apps.
1950      * <p> Can be granted by Device Owner or Profile Owner.
1951      */
1952     public static final String DELEGATION_CERT_SELECTION = "delegation-cert-selection";
1953 
1954     /**
1955      * Grants access to {@link #setSecurityLoggingEnabled}, {@link #isSecurityLoggingEnabled},
1956      * {@link #retrieveSecurityLogs}, and {@link #retrievePreRebootSecurityLogs}. Once granted the
1957      * delegated app will start receiving {@link DelegatedAdminReceiver#onSecurityLogsAvailable}
1958      * callback, and Device owner or Profile Owner will no longer receive the
1959      * {@link DeviceAdminReceiver#onSecurityLogsAvailable} callback. There can be at most one app
1960      * that has this delegation. If another app already had delegated security logging access, it
1961      * will lose the delegation when a new app is delegated.
1962      *
1963      * <p> Can only be granted by Device Owner or Profile Owner of an organnization owned and
1964      * managed profile.
1965      */
1966     public static final String DELEGATION_SECURITY_LOGGING = "delegation-security-logging";
1967 
1968     /**
1969      * No management for current user in-effect. This is the default.
1970      * @hide
1971      */
1972     @SystemApi
1973     public static final int STATE_USER_UNMANAGED = 0;
1974 
1975     /**
1976      * Management partially setup, user setup needs to be completed.
1977      * @hide
1978      */
1979     @SystemApi
1980     public static final int STATE_USER_SETUP_INCOMPLETE = 1;
1981 
1982     /**
1983      * Management partially setup, user setup completed.
1984      * @hide
1985      */
1986     @SystemApi
1987     public static final int STATE_USER_SETUP_COMPLETE = 2;
1988 
1989     /**
1990      * Management setup and active on current user.
1991      * @hide
1992      */
1993     @SystemApi
1994     public static final int STATE_USER_SETUP_FINALIZED = 3;
1995 
1996     /**
1997      * Management partially setup on a managed profile.
1998      * @hide
1999      */
2000     @SystemApi
2001     public static final int STATE_USER_PROFILE_COMPLETE = 4;
2002 
2003     /**
2004      * Management setup on a managed profile.
2005      * <p>This is used as an intermediate state after {@link #STATE_USER_PROFILE_COMPLETE} once the
2006      * work profile has been created.
2007      * @hide
2008      */
2009     @SystemApi
2010     public static final int STATE_USER_PROFILE_FINALIZED = 5;
2011 
2012     /**
2013      * @hide
2014      */
2015     @IntDef(prefix = { "STATE_USER_" }, value = {
2016             STATE_USER_UNMANAGED,
2017             STATE_USER_SETUP_INCOMPLETE,
2018             STATE_USER_SETUP_COMPLETE,
2019             STATE_USER_SETUP_FINALIZED,
2020             STATE_USER_PROFILE_COMPLETE,
2021             STATE_USER_PROFILE_FINALIZED
2022     })
2023     @Retention(RetentionPolicy.SOURCE)
2024     public @interface UserProvisioningState {}
2025 
2026     /**
2027      * Result code for {@link #checkProvisioningPreCondition}.
2028      *
2029      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
2030      * {@link #ACTION_PROVISION_MANAGED_PROFILE} and {@link #ACTION_PROVISION_MANAGED_USER}
2031      * when provisioning is allowed.
2032      *
2033      * @hide
2034      */
2035     @TestApi
2036     public static final int CODE_OK = 0;
2037 
2038     /**
2039      * Result code for {@link #checkProvisioningPreCondition}.
2040      *
2041      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the device already has a
2042      * device owner.
2043      *
2044      * @hide
2045      */
2046     @TestApi
2047     public static final int CODE_HAS_DEVICE_OWNER = 1;
2048 
2049     /**
2050      * Result code for {@link #checkProvisioningPreCondition}.
2051      *
2052      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the user has a profile owner
2053      *  and for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the profile owner is already set.
2054      *
2055      * @hide
2056      */
2057     @TestApi
2058     public static final int CODE_USER_HAS_PROFILE_OWNER = 2;
2059 
2060     /**
2061      * Result code for {@link #checkProvisioningPreCondition}.
2062      *
2063      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the user isn't running.
2064      *
2065      * @hide
2066      */
2067     @TestApi
2068     public static final int CODE_USER_NOT_RUNNING = 3;
2069 
2070     /**
2071      * Result code for {@link #checkProvisioningPreCondition}.
2072      *
2073      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} if the device has already been
2074      * setup and for {@link #ACTION_PROVISION_MANAGED_USER} if the user has already been setup.
2075      *
2076      * @hide
2077      */
2078     @TestApi
2079     public static final int CODE_USER_SETUP_COMPLETED = 4;
2080 
2081     /**
2082      * Code used to indicate that the device also has a user other than the system user.
2083      *
2084      * @hide
2085      */
2086     @TestApi
2087     public static final int CODE_NONSYSTEM_USER_EXISTS = 5;
2088 
2089     /**
2090      * Code used to indicate that device has an account that prevents provisioning.
2091      *
2092      * @hide
2093      */
2094     @TestApi
2095     public static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
2096 
2097     /**
2098      * Result code for {@link #checkProvisioningPreCondition}.
2099      *
2100      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} if the user is not a system user.
2101      *
2102      * @hide
2103      */
2104     @TestApi
2105     public static final int CODE_NOT_SYSTEM_USER = 7;
2106 
2107     /**
2108      * Result code for {@link #checkProvisioningPreCondition}.
2109      *
2110      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
2111      * {@link #ACTION_PROVISION_MANAGED_USER} when the device is a watch and is already paired.
2112      *
2113      * @hide
2114      */
2115     @TestApi
2116     public static final int CODE_HAS_PAIRED = 8;
2117 
2118     /**
2119      * Result code for {@link #checkProvisioningPreCondition}.
2120      *
2121      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} and
2122      * {@link #ACTION_PROVISION_MANAGED_USER} on devices which do not support managed users.
2123      *
2124      * @see {@link PackageManager#FEATURE_MANAGED_USERS}
2125      * @hide
2126      */
2127     @TestApi
2128     public static final int CODE_MANAGED_USERS_NOT_SUPPORTED = 9;
2129 
2130     /**
2131      * Result code for {@link #checkProvisioningPreCondition}.
2132      *
2133      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} if the user is a system user and
2134      * for {@link #ACTION_PROVISION_MANAGED_DEVICE} on devices running headless system user mode
2135      * and the user is a system user.
2136      *
2137      * @hide
2138      */
2139     @TestApi
2140     public static final int CODE_SYSTEM_USER = 10;
2141 
2142     /**
2143      * Result code for {@link #checkProvisioningPreCondition}.
2144      *
2145      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the user cannot have more
2146      * managed profiles.
2147      *
2148      * @hide
2149      */
2150     @TestApi
2151     public static final int CODE_CANNOT_ADD_MANAGED_PROFILE = 11;
2152 
2153     /**
2154      * TODO (b/137101239): clean up split system user codes
2155      *
2156      * @hide
2157      * @deprecated not used anymore but can't be removed since it's a @TestApi.
2158      **/
2159     @Deprecated
2160     @TestApi
2161     public static final int CODE_NOT_SYSTEM_USER_SPLIT = 12;
2162 
2163     /**
2164      * Result code for {@link #checkProvisioningPreCondition}.
2165      *
2166      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
2167      * {@link #ACTION_PROVISION_MANAGED_PROFILE} on devices which do not support device
2168      * admins.
2169      *
2170      * @hide
2171      */
2172     @TestApi
2173     public static final int CODE_DEVICE_ADMIN_NOT_SUPPORTED = 13;
2174 
2175     /**
2176      * TODO (b/137101239): clean up split system user codes
2177      * Result code for {@link #checkProvisioningPreCondition}.
2178      *
2179      * @hide
2180      * @deprecated not used anymore but can't be removed since it's a @TestApi.
2181      */
2182     @Deprecated
2183     @TestApi
2184     public static final int CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER = 14;
2185 
2186     /**
2187      * Result code for {@link #checkProvisioningPreCondition}.
2188      *
2189      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
2190      * {@link #ACTION_PROVISION_MANAGED_PROFILE} on devices which do not support provisioning.
2191      *
2192      * @hide
2193      */
2194     @TestApi
2195     public static final int CODE_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS = 15;
2196 
2197     /**
2198      * Result codes for {@link #checkProvisioningPreCondition} indicating all the provisioning pre
2199      * conditions.
2200      *
2201      * @hide
2202      */
2203     @Retention(RetentionPolicy.SOURCE)
2204     @IntDef(prefix = { "CODE_" }, value = {
2205             CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
2206             CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER, CODE_HAS_PAIRED,
2207             CODE_MANAGED_USERS_NOT_SUPPORTED, CODE_SYSTEM_USER, CODE_CANNOT_ADD_MANAGED_PROFILE,
2208             CODE_NOT_SYSTEM_USER_SPLIT, CODE_DEVICE_ADMIN_NOT_SUPPORTED,
2209             CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER,
2210             CODE_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS
2211     })
2212     public @interface ProvisioningPreCondition {}
2213 
2214     /**
2215      * Service-specific error code for {@link #provisionFullyManagedDevice} and
2216      * {@link #createAndProvisionManagedProfile}:
2217      * Indicates the call to {@link #checkProvisioningPreCondition} returned an error code.
2218      *
2219      * @hide
2220      */
2221     @TestApi
2222     public static final int PROVISIONING_RESULT_PRE_CONDITION_FAILED = 1;
2223 
2224     /**
2225      * Service-specific error code for {@link #createAndProvisionManagedProfile}:
2226      * Indicates the call to {@link UserManager#createProfileForUserEvenWhenDisallowed}
2227      * returned {@code null}.
2228      *
2229      * @hide
2230      */
2231     @TestApi
2232     public static final int PROVISIONING_RESULT_PROFILE_CREATION_FAILED = 2;
2233 
2234     /**
2235      * Service-specific error code for {@link #createAndProvisionManagedProfile}:
2236      * Indicates the call to {@link PackageManager#installExistingPackageAsUser} has failed.
2237      *
2238      * @hide
2239      */
2240     @TestApi
2241     public static final int PROVISIONING_RESULT_ADMIN_PACKAGE_INSTALLATION_FAILED = 3;
2242 
2243     /**
2244      * Service-specific error code for {@link #createAndProvisionManagedProfile}:
2245      * Indicates the call to {@link #setProfileOwner} returned {@code false}.
2246      *
2247      * @hide
2248      */
2249     @TestApi
2250     public static final int PROVISIONING_RESULT_SETTING_PROFILE_OWNER_FAILED = 4;
2251 
2252     /**
2253      * Service-specific error code for {@link #createAndProvisionManagedProfile}:
2254      * Indicates that starting the newly created profile has failed.
2255      *
2256      * @hide
2257      */
2258     @TestApi
2259     public static final int PROVISIONING_RESULT_STARTING_PROFILE_FAILED = 5;
2260 
2261     /**
2262      * Service-specific error code for {@link #provisionFullyManagedDevice}:
2263      * Indicates that removing the non required apps have failed.
2264      *
2265      * @hide
2266      */
2267     @TestApi
2268     public static final int PROVISIONING_RESULT_REMOVE_NON_REQUIRED_APPS_FAILED = 6;
2269 
2270     /**
2271      * Service-specific error code for {@link #provisionFullyManagedDevice}:
2272      * Indicates the call to {@link #setDeviceOwner} returned {@code false}.
2273      *
2274      * @hide
2275      */
2276     @TestApi
2277     public static final int PROVISIONING_RESULT_SET_DEVICE_OWNER_FAILED = 7;
2278 
2279     /**
2280      * Service-specific error codes for {@link #createAndProvisionManagedProfile} and
2281      * {@link #provisionFullyManagedDevice} indicating all the errors during provisioning.
2282      *
2283      * @hide
2284      */
2285     @Retention(RetentionPolicy.SOURCE)
2286     @IntDef(prefix = { "PROVISIONING_RESULT_" }, value = {
2287             PROVISIONING_RESULT_PRE_CONDITION_FAILED, PROVISIONING_RESULT_PROFILE_CREATION_FAILED,
2288             PROVISIONING_RESULT_ADMIN_PACKAGE_INSTALLATION_FAILED,
2289             PROVISIONING_RESULT_SETTING_PROFILE_OWNER_FAILED,
2290             PROVISIONING_RESULT_STARTING_PROFILE_FAILED,
2291             PROVISIONING_RESULT_REMOVE_NON_REQUIRED_APPS_FAILED,
2292             PROVISIONING_RESULT_SET_DEVICE_OWNER_FAILED
2293     })
2294     public @interface ProvisioningResult {}
2295 
2296     /**
2297      * Disable all configurable SystemUI features during LockTask mode. This includes,
2298      * <ul>
2299      *     <li>system info area in the status bar (connectivity icons, clock, etc.)
2300      *     <li>notifications (including alerts, icons, and the notification shade)
2301      *     <li>Home button
2302      *     <li>Recents button and UI
2303      *     <li>global actions menu (i.e. power button menu)
2304      *     <li>keyguard
2305      * </ul>
2306      *
2307      * @see #setLockTaskFeatures(ComponentName, int)
2308      */
2309     public static final int LOCK_TASK_FEATURE_NONE = 0;
2310 
2311     /**
2312      * Enable the system info area in the status bar during LockTask mode. The system info area
2313      * usually occupies the right side of the status bar (although this can differ across OEMs). It
2314      * includes all system information indicators, such as date and time, connectivity, battery,
2315      * vibration mode, etc.
2316      *
2317      * @see #setLockTaskFeatures(ComponentName, int)
2318      */
2319     public static final int LOCK_TASK_FEATURE_SYSTEM_INFO = 1;
2320 
2321     /**
2322      * Enable notifications during LockTask mode. This includes notification icons on the status
2323      * bar, heads-up notifications, and the expandable notification shade. Note that the Quick
2324      * Settings panel remains disabled. This feature flag can only be used in combination with
2325      * {@link #LOCK_TASK_FEATURE_HOME}. {@link #setLockTaskFeatures(ComponentName, int)}
2326      * throws an {@link IllegalArgumentException} if this feature flag is defined without
2327      * {@link #LOCK_TASK_FEATURE_HOME}.
2328      *
2329      * @see #setLockTaskFeatures(ComponentName, int)
2330      */
2331     public static final int LOCK_TASK_FEATURE_NOTIFICATIONS = 1 << 1;
2332 
2333     /**
2334      * Enable the Home button during LockTask mode. Note that if a custom launcher is used, it has
2335      * to be registered as the default launcher with
2336      * {@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}, and its
2337      * package needs to be allowlisted for LockTask with
2338      * {@link #setLockTaskPackages(ComponentName, String[])}.
2339      *
2340      * @see #setLockTaskFeatures(ComponentName, int)
2341      */
2342     public static final int LOCK_TASK_FEATURE_HOME = 1 << 2;
2343 
2344     /**
2345      * Enable the Overview button and the Overview screen during LockTask mode. This feature flag
2346      * can only be used in combination with {@link #LOCK_TASK_FEATURE_HOME}, and
2347      * {@link #setLockTaskFeatures(ComponentName, int)} will throw an
2348      * {@link IllegalArgumentException} if this feature flag is defined without
2349      * {@link #LOCK_TASK_FEATURE_HOME}.
2350      *
2351      * @see #setLockTaskFeatures(ComponentName, int)
2352      */
2353     public static final int LOCK_TASK_FEATURE_OVERVIEW = 1 << 3;
2354 
2355     /**
2356      * Enable the global actions dialog during LockTask mode. This is the dialog that shows up when
2357      * the user long-presses the power button, for example. Note that the user may not be able to
2358      * power off the device if this flag is not set.
2359      *
2360      * <p>This flag is enabled by default until {@link #setLockTaskFeatures(ComponentName, int)} is
2361      * called for the first time.
2362      *
2363      * @see #setLockTaskFeatures(ComponentName, int)
2364      */
2365     public static final int LOCK_TASK_FEATURE_GLOBAL_ACTIONS = 1 << 4;
2366 
2367     /**
2368      * Enable the keyguard during LockTask mode. Note that if the keyguard is already disabled with
2369      * {@link #setKeyguardDisabled(ComponentName, boolean)}, setting this flag will have no effect.
2370      * If this flag is not set, the keyguard will not be shown even if the user has a lock screen
2371      * credential.
2372      *
2373      * @see #setLockTaskFeatures(ComponentName, int)
2374      */
2375     public static final int LOCK_TASK_FEATURE_KEYGUARD = 1 << 5;
2376 
2377     /**
2378      * Enable blocking of non-allowlisted activities from being started into a locked task.
2379      *
2380      * @see #setLockTaskFeatures(ComponentName, int)
2381      */
2382     public static final int LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK = 1 << 6;
2383 
2384     /**
2385      * Flags supplied to {@link #setLockTaskFeatures(ComponentName, int)}.
2386      *
2387      * @hide
2388      */
2389     @Retention(RetentionPolicy.SOURCE)
2390     @IntDef(flag = true, prefix = { "LOCK_TASK_FEATURE_" }, value = {
2391             LOCK_TASK_FEATURE_NONE,
2392             LOCK_TASK_FEATURE_SYSTEM_INFO,
2393             LOCK_TASK_FEATURE_NOTIFICATIONS,
2394             LOCK_TASK_FEATURE_HOME,
2395             LOCK_TASK_FEATURE_OVERVIEW,
2396             LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
2397             LOCK_TASK_FEATURE_KEYGUARD,
2398             LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK
2399     })
2400     public @interface LockTaskFeature {}
2401 
2402     /**
2403      * Service action: Action for a service that device owner and profile owner can optionally
2404      * own.  If a device owner or a profile owner has such a service, the system tries to keep
2405      * a bound connection to it, in order to keep their process always running.
2406      * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN}
2407      * permission.
2408      */
2409     @SdkConstant(SdkConstantType.SERVICE_ACTION)
2410     public static final String ACTION_DEVICE_ADMIN_SERVICE
2411             = "android.app.action.DEVICE_ADMIN_SERVICE";
2412 
2413     /** @hide */
2414     @Retention(RetentionPolicy.SOURCE)
2415     @IntDef(flag = true, prefix = {"ID_TYPE_"}, value = {
2416         ID_TYPE_BASE_INFO,
2417         ID_TYPE_SERIAL,
2418         ID_TYPE_IMEI,
2419         ID_TYPE_MEID,
2420         ID_TYPE_INDIVIDUAL_ATTESTATION
2421     })
2422     public @interface AttestationIdType {}
2423 
2424     /**
2425      * Specifies that the device should attest its manufacturer details. For use with
2426      * {@link #generateKeyPair}.
2427      *
2428      * @see #generateKeyPair
2429      */
2430     public static final int ID_TYPE_BASE_INFO = 1;
2431 
2432     /**
2433      * Specifies that the device should attest its serial number. For use with
2434      * {@link #generateKeyPair}.
2435      *
2436      * @see #generateKeyPair
2437      */
2438     public static final int ID_TYPE_SERIAL = 2;
2439 
2440     /**
2441      * Specifies that the device should attest its IMEI. For use with {@link #generateKeyPair}.
2442      *
2443      * @see #generateKeyPair
2444      */
2445     public static final int ID_TYPE_IMEI = 4;
2446 
2447     /**
2448      * Specifies that the device should attest its MEID. For use with {@link #generateKeyPair}.
2449      *
2450      * @see #generateKeyPair
2451      */
2452     public static final int ID_TYPE_MEID = 8;
2453 
2454     /**
2455      * Specifies that the device should attest using an individual attestation certificate.
2456      * For use with {@link #generateKeyPair}.
2457      *
2458      * @see #generateKeyPair
2459      */
2460     public static final int ID_TYPE_INDIVIDUAL_ATTESTATION = 16;
2461 
2462     /**
2463      * Service-specific error code for {@link #generateKeyPair}:
2464      * Indicates the call has failed due to StrongBox unavailability.
2465      * @hide
2466      */
2467     public static final int KEY_GEN_STRONGBOX_UNAVAILABLE = 1;
2468 
2469     /**
2470      * Specifies that the calling app should be granted access to the installed credentials
2471      * immediately. Otherwise, access to the credentials will be gated by user approval.
2472      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
2473      *
2474      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
2475      */
2476     public static final int INSTALLKEY_REQUEST_CREDENTIALS_ACCESS = 1;
2477 
2478     /**
2479      * Specifies that a user can select the key via the Certificate Selection prompt.
2480      * If this flag is not set when calling {@link #installKeyPair}, the key can only be granted
2481      * access by implementing {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
2482      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
2483      *
2484      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
2485      */
2486     public static final int INSTALLKEY_SET_USER_SELECTABLE = 2;
2487 
2488     /**
2489      * Broadcast action: sent when the profile owner is set, changed or cleared.
2490      *
2491      * This broadcast is sent only to the user managed by the new profile owner.
2492      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
2493      */
2494     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2495     public static final String ACTION_PROFILE_OWNER_CHANGED =
2496             "android.app.action.PROFILE_OWNER_CHANGED";
2497 
2498     /** @hide */
2499     @Retention(RetentionPolicy.SOURCE)
2500     @IntDef(prefix = {"PRIVATE_DNS_MODE_"}, value = {
2501             PRIVATE_DNS_MODE_UNKNOWN,
2502             PRIVATE_DNS_MODE_OFF,
2503             PRIVATE_DNS_MODE_OPPORTUNISTIC,
2504             PRIVATE_DNS_MODE_PROVIDER_HOSTNAME
2505     })
2506     public @interface PrivateDnsMode {}
2507 
2508     /**
2509      * Specifies that the Private DNS setting is in an unknown state.
2510      */
2511     public static final int PRIVATE_DNS_MODE_UNKNOWN = 0;
2512 
2513     /**
2514      * Specifies that Private DNS was turned off completely.
2515      */
2516     public static final int PRIVATE_DNS_MODE_OFF = 1;
2517 
2518     /**
2519      * Specifies that the device owner requested opportunistic DNS over TLS
2520      */
2521     public static final int PRIVATE_DNS_MODE_OPPORTUNISTIC = 2;
2522 
2523     /**
2524      * Specifies that the device owner configured a specific host to use for Private DNS.
2525      */
2526     public static final int PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = 3;
2527 
2528     /**
2529      * Callback used in {@link #installSystemUpdate} to indicate that there was an error while
2530      * trying to install an update.
2531      */
2532     public abstract static class InstallSystemUpdateCallback {
2533         /** Represents an unknown error while trying to install an update. */
2534         public static final int UPDATE_ERROR_UNKNOWN = 1;
2535 
2536         /** Represents the update file being intended for different OS version. */
2537         public static final int UPDATE_ERROR_INCORRECT_OS_VERSION = 2;
2538 
2539         /**
2540          * Represents the update file being wrong; e.g. payloads are mismatched, or the wrong
2541          * compression method is used.
2542          */
2543         public static final int UPDATE_ERROR_UPDATE_FILE_INVALID = 3;
2544 
2545         /** Represents that the file could not be found. */
2546         public static final int UPDATE_ERROR_FILE_NOT_FOUND = 4;
2547 
2548         /** Represents the battery being too low to apply an update. */
2549         public static final int UPDATE_ERROR_BATTERY_LOW = 5;
2550 
2551         /**
2552          * Method invoked when there was an error while installing an update.
2553          *
2554          * <p>The given error message is not intended to be user-facing. It is intended to be
2555          * reported back to the IT admin to be read.
2556          */
onInstallUpdateError( @nstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage)2557         public void onInstallUpdateError(
2558                 @InstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage) {
2559         }
2560     }
2561 
2562     /**
2563      * @hide
2564      */
2565     @IntDef(prefix = { "UPDATE_ERROR_" }, value = {
2566             InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN,
2567             InstallSystemUpdateCallback.UPDATE_ERROR_INCORRECT_OS_VERSION,
2568             InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
2569             InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
2570             InstallSystemUpdateCallback.UPDATE_ERROR_BATTERY_LOW
2571     })
2572     @Retention(RetentionPolicy.SOURCE)
2573     public @interface InstallUpdateCallbackErrorConstants {}
2574 
2575     /**
2576      * The selected mode has been set successfully. If the mode is
2577      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} then it implies the supplied host is valid
2578      * and reachable.
2579      */
2580     public static final int PRIVATE_DNS_SET_NO_ERROR = 0;
2581 
2582     /**
2583      * If the {@code privateDnsHost} provided was of a valid hostname but that host was found
2584      * to not support DNS-over-TLS.
2585      */
2586     public static final int PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING = 1;
2587 
2588     /**
2589      * General failure to set the Private DNS mode, not due to one of the reasons listed above.
2590      */
2591     public static final int PRIVATE_DNS_SET_ERROR_FAILURE_SETTING = 2;
2592 
2593     /**
2594      * @hide
2595      */
2596     @IntDef(prefix = {"PRIVATE_DNS_SET_"}, value = {
2597             PRIVATE_DNS_SET_NO_ERROR,
2598             PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING,
2599             PRIVATE_DNS_SET_ERROR_FAILURE_SETTING
2600     })
2601     @Retention(RetentionPolicy.SOURCE)
2602     public @interface PrivateDnsModeErrorCodes {}
2603 
2604     /**
2605      * Activity action: Starts the administrator to get the mode for the provisioning.
2606      * This intent may contain the following extras:
2607      * <ul>
2608      *     <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}</li>
2609      *     <li>{@link #EXTRA_PROVISIONING_IMEI}</li>
2610      *     <li>{@link #EXTRA_PROVISIONING_SERIAL_NUMBER}</li>
2611      * </ul>
2612      *
2613      * <p>The target activity should return one of the following values in
2614      * {@link #EXTRA_PROVISIONING_MODE} as result:
2615      * <ul>
2616      *     <li>{@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}</li>
2617      *     <li>{@link #PROVISIONING_MODE_MANAGED_PROFILE}</li>
2618      * </ul>
2619      *
2620      * <p>If performing fully-managed device provisioning and the admin app desires to show its
2621      * own education screens, the target activity can additionally return
2622      * {@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS} set to <code>true</code>.
2623      *
2624      * <p>The target activity may also return the account that needs to be migrated from primary
2625      * user to managed profile in case of a profile owner provisioning in
2626      * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE} as result.
2627      *
2628      * <p>The target activity may also include the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}
2629      * extra in the intent result. The values of this {@link android.os.PersistableBundle} will be
2630      * sent as an intent extra of the same name to the {@link #ACTION_ADMIN_POLICY_COMPLIANCE}
2631      * activity, along with the values of the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE} extra
2632      * that are already supplied to this activity.
2633      *
2634      * @see #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION
2635      * @see #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED
2636      * @see #ACTION_ADMIN_POLICY_COMPLIANCE
2637      */
2638     public static final String ACTION_GET_PROVISIONING_MODE =
2639             "android.app.action.GET_PROVISIONING_MODE";
2640 
2641     /**
2642      * A string extra holding the IMEI (International Mobile Equipment Identity) of the device.
2643      */
2644     public static final String EXTRA_PROVISIONING_IMEI = "android.app.extra.PROVISIONING_IMEI";
2645 
2646     /**
2647      * A string extra holding the serial number of the device.
2648      */
2649     public static final String EXTRA_PROVISIONING_SERIAL_NUMBER =
2650             "android.app.extra.PROVISIONING_SERIAL_NUMBER";
2651 
2652     /**
2653      * An intent extra holding the provisioning mode returned by the administrator.
2654      * The value of this extra must be one of the values provided in {@link
2655      * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES}, which is provided as an intent extra to
2656      * the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity.
2657      *
2658      * @see #PROVISIONING_MODE_FULLY_MANAGED_DEVICE
2659      * @see #PROVISIONING_MODE_MANAGED_PROFILE
2660      */
2661     public static final String EXTRA_PROVISIONING_MODE =
2662             "android.app.extra.PROVISIONING_MODE";
2663 
2664     /**
2665      * An integer extra indication what provisioning modes should be available for the admin app
2666      * to pick.
2667      *
2668      * <p>The default value is {@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}.
2669      *
2670      * <p>The value of this extra will determine the contents of the {@link
2671      * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array that is passed to the admin app as an
2672      * extra to its {@link #ACTION_GET_PROVISIONING_MODE} activity.
2673      *
2674      * <p>If one of the possible admin app choices is a personally-owned work profile, then the
2675      * IMEI and serial number will not be passed to the admin app's {@link
2676      * #ACTION_GET_PROVISIONING_MODE} activity via the {@link #EXTRA_PROVISIONING_IMEI} and {@link
2677      * #EXTRA_PROVISIONING_SERIAL_NUMBER} respectively.
2678      *
2679      * <p>The allowed flag combinations are:
2680      * <ul>
2681      *     <li>{@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}</li>
2682      *     <li>{@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}</li>
2683      *     <li>{@link #FLAG_SUPPORTED_MODES_DEVICE_OWNER}</li>
2684      *     <li>{@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}
2685      *             | {@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}</li>
2686      * </ul>
2687      *
2688      * <p>This extra is only respected when provided alongside the {@link
2689      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
2690      *
2691      * @see #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED
2692      * @see #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED
2693      * @see #FLAG_SUPPORTED_MODES_DEVICE_OWNER
2694      * @hide
2695      */
2696     @SystemApi
2697     public static final String EXTRA_PROVISIONING_SUPPORTED_MODES =
2698             "android.app.extra.PROVISIONING_SUPPORTED_MODES";
2699 
2700     /**
2701      * A boolean extra which determines whether to skip the ownership disclaimer screen during the
2702      * provisioning flow. The default value is {@code false}.
2703      *
2704      * If the value is {@code true}, the provisioning initiator must display a device ownership
2705      * disclaimer screen similar to that provided in AOSP.
2706      *
2707      * <p>This extra is only respected when provided alongside the {@link
2708      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
2709      *
2710      * @hide
2711      */
2712     @SystemApi
2713     public static final String EXTRA_PROVISIONING_SKIP_OWNERSHIP_DISCLAIMER =
2714             "android.app.extra.PROVISIONING_SKIP_OWNERSHIP_DISCLAIMER";
2715 
2716     /**
2717      * An {@link ArrayList} of {@link Integer} extra specifying the allowed provisioning modes.
2718      * <p>This extra will be passed to the admin app's {@link #ACTION_GET_PROVISIONING_MODE}
2719      * activity, whose result intent must contain {@link #EXTRA_PROVISIONING_MODE} set to one of
2720      * the values in this array.
2721      * <p>If the value set to {@link #EXTRA_PROVISIONING_MODE} is not in the array,
2722      * provisioning will fail.
2723      * @see #PROVISIONING_MODE_MANAGED_PROFILE
2724      * @see #PROVISIONING_MODE_FULLY_MANAGED_DEVICE
2725      */
2726     public static final String EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES =
2727             "android.app.extra.PROVISIONING_ALLOWED_PROVISIONING_MODES";
2728 
2729     /**
2730      * The provisioning mode for fully managed device.
2731      */
2732     public static final int PROVISIONING_MODE_FULLY_MANAGED_DEVICE = 1;
2733 
2734     /**
2735      * The provisioning mode for managed profile.
2736      */
2737     public static final int PROVISIONING_MODE_MANAGED_PROFILE = 2;
2738 
2739     /**
2740      * The provisioning mode for a managed profile on a personal device.
2741      * <p>This mode is only available when the provisioning initiator has explicitly instructed the
2742      * provisioning flow to support managed profile on a personal device provisioning. In that case,
2743      * {@link #PROVISIONING_MODE_MANAGED_PROFILE} corresponds to an organization-owned managed
2744      * profile, whereas this constant corresponds to a personally-owned managed profile.
2745      *
2746      * @see #EXTRA_PROVISIONING_MODE
2747      */
2748     public static final int PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE = 3;
2749 
2750     /**
2751      * A {@code boolean} flag that indicates whether the provisioning flow should return before
2752      * starting the admin app's {@link #ACTION_ADMIN_POLICY_COMPLIANCE} handler. The default value
2753      * is {@code true}.
2754      *
2755      * <p>If this extra is set to {@code true}, then when the provisioning flow returns back to the
2756      * provisioning initiator, provisioning will not be complete. The provisioning initiator can
2757      * use this opportunity to do its own preparatory steps prior to the launch of the admin app's
2758      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} handler. It is the responsibility of the
2759      * provisioning initiator to ensure that the provisioning flow is then resumed and completed.
2760      *
2761      * <p>If this extra is set to {@code false}, then when the provisioning flow returns back to
2762      * the provisioning initiator, provisioning will be complete. Note that device owner
2763      * provisioning is not currently supported for the this scenario.
2764      *
2765      * <p>This extra is only respected when provided alongside the {@link
2766      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
2767      *
2768      * @hide
2769      */
2770     @SystemApi
2771     public static final String EXTRA_PROVISIONING_RETURN_BEFORE_POLICY_COMPLIANCE =
2772             "android.app.extra.PROVISIONING_RETURN_BEFORE_POLICY_COMPLIANCE";
2773 
2774     /**
2775      * Activity action: Starts the administrator to show policy compliance for the provisioning.
2776      * This action is used any time that the administrator has an opportunity to show policy
2777      * compliance before the end of setup wizard. This could happen as part of the admin-integrated
2778      * provisioning flow (in which case this gets sent after {@link #ACTION_GET_PROVISIONING_MODE}),
2779      * or it could happen during provisioning finalization if the administrator supports
2780      * finalization during setup wizard.
2781      *
2782      * <p>Intents with this action may also be supplied with the {@link
2783      * #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE} extra.
2784      *
2785      * @see #ACTION_GET_PROVISIONING_MODE
2786      */
2787     public static final String ACTION_ADMIN_POLICY_COMPLIANCE =
2788             "android.app.action.ADMIN_POLICY_COMPLIANCE";
2789 
2790     /**
2791      * Maximum supported password length. Kind-of arbitrary.
2792      * @hide
2793      */
2794     public static final int MAX_PASSWORD_LENGTH = 16;
2795 
2796     /**
2797      * Service Action: Service implemented by a device owner or profile owner supervision app to
2798      * provide a secondary lockscreen.
2799      * @hide
2800      */
2801     @SystemApi
2802     public static final String ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE =
2803             "android.app.action.BIND_SECONDARY_LOCKSCREEN_SERVICE";
2804 
2805     /**
2806      * Return value for {@link #getPersonalAppsSuspendedReasons} when personal apps are not
2807      * suspended.
2808      */
2809     public static final int PERSONAL_APPS_NOT_SUSPENDED = 0;
2810 
2811     /**
2812      * Flag for {@link #getPersonalAppsSuspendedReasons} return value. Set when personal
2813      * apps are suspended by an admin explicitly via {@link #setPersonalAppsSuspended}.
2814      */
2815     public static final int PERSONAL_APPS_SUSPENDED_EXPLICITLY = 1 << 0;
2816 
2817     /**
2818      * Flag for {@link #getPersonalAppsSuspendedReasons} return value. Set when personal apps are
2819      * suspended by framework because managed profile was off for longer than allowed by policy.
2820      * @see #setManagedProfileMaximumTimeOff
2821      */
2822     public static final int PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT = 1 << 1;
2823 
2824     /**
2825      * @hide
2826      */
2827     @IntDef(flag = true, prefix = { "PERSONAL_APPS_" }, value = {
2828             PERSONAL_APPS_NOT_SUSPENDED,
2829             PERSONAL_APPS_SUSPENDED_EXPLICITLY,
2830             PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT
2831     })
2832     @Retention(RetentionPolicy.SOURCE)
2833     public @interface PersonalAppsSuspensionReason {}
2834 
2835     /**
2836      * The default device owner type for a managed device.
2837      *
2838      * @hide
2839      */
2840     public static final int DEVICE_OWNER_TYPE_DEFAULT = 0;
2841 
2842     /**
2843      * The device owner type for a financed device.
2844      *
2845      * @hide
2846      */
2847     public static final int DEVICE_OWNER_TYPE_FINANCED = 1;
2848 
2849     /**
2850      * Different device owner types for a managed device.
2851      *
2852      * @hide
2853      */
2854     @Retention(RetentionPolicy.SOURCE)
2855     @IntDef(prefix = { "DEVICE_OWNER_TYPE_" }, value = {
2856             DEVICE_OWNER_TYPE_DEFAULT,
2857             DEVICE_OWNER_TYPE_FINANCED
2858     })
2859     public @interface DeviceOwnerType {}
2860 
2861     /** @hide */
2862     @TestApi
2863     public static final int OPERATION_LOCK_NOW = 1;
2864     /** @hide */
2865     @TestApi
2866     public static final int OPERATION_SWITCH_USER = 2;
2867     /** @hide */
2868     @TestApi
2869     public static final int OPERATION_START_USER_IN_BACKGROUND = 3;
2870     /** @hide */
2871     @TestApi
2872     public static final int OPERATION_STOP_USER = 4;
2873     /** @hide */
2874     @TestApi
2875     public static final int OPERATION_CREATE_AND_MANAGE_USER = 5;
2876     /** @hide */
2877     @TestApi
2878     public static final int OPERATION_REMOVE_USER = 6;
2879     /** @hide */
2880     @TestApi
2881     public static final int OPERATION_REBOOT = 7;
2882     /** @hide */
2883     @TestApi
2884     public static final int OPERATION_WIPE_DATA = 8;
2885     /** @hide */
2886     @TestApi
2887     public static final int OPERATION_LOGOUT_USER = 9;
2888     /** @hide */
2889     @TestApi
2890     public static final int OPERATION_SET_USER_RESTRICTION = 10;
2891     /** @hide */
2892     @TestApi
2893     public static final int OPERATION_SET_SYSTEM_SETTING = 11;
2894     /** @hide */
2895     @TestApi
2896     public static final int OPERATION_SET_KEYGUARD_DISABLED = 12;
2897     /** @hide */
2898     @TestApi
2899     public static final int OPERATION_SET_STATUS_BAR_DISABLED = 13;
2900     /** @hide */
2901     @TestApi
2902     public static final int OPERATION_SET_SYSTEM_UPDATE_POLICY = 14;
2903     /** @hide */
2904     @TestApi
2905     public static final int OPERATION_SET_APPLICATION_HIDDEN = 15;
2906     /** @hide */
2907     @TestApi
2908     public static final int OPERATION_SET_APPLICATION_RESTRICTIONS = 16;
2909     /** @hide */
2910     @TestApi
2911     public static final int OPERATION_SET_KEEP_UNINSTALLED_PACKAGES = 17;
2912     /** @hide */
2913     @TestApi
2914     public static final int OPERATION_SET_LOCK_TASK_FEATURES = 18;
2915     /** @hide */
2916     @TestApi
2917     public static final int OPERATION_SET_LOCK_TASK_PACKAGES = 19;
2918     /** @hide */
2919     @TestApi
2920     public static final int OPERATION_SET_PACKAGES_SUSPENDED = 20;
2921     /** @hide */
2922     @TestApi
2923     public static final int OPERATION_SET_TRUST_AGENT_CONFIGURATION = 21;
2924     /** @hide */
2925     @TestApi
2926     public static final int OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES = 22;
2927     /** @hide */
2928     @TestApi
2929     public static final int OPERATION_CLEAR_APPLICATION_USER_DATA = 23;
2930     /** @hide */
2931     @TestApi
2932     public static final int OPERATION_INSTALL_CA_CERT = 24;
2933     /** @hide */
2934     @TestApi
2935     public static final int OPERATION_INSTALL_KEY_PAIR = 25;
2936     /** @hide */
2937     @TestApi
2938     public static final int OPERATION_INSTALL_SYSTEM_UPDATE = 26;
2939     /** @hide */
2940     @TestApi
2941     public static final int OPERATION_REMOVE_ACTIVE_ADMIN = 27;
2942     /** @hide */
2943     @TestApi
2944     public static final int OPERATION_REMOVE_KEY_PAIR = 28;
2945     /** @hide */
2946     @TestApi
2947     public static final int OPERATION_REQUEST_BUGREPORT = 29;
2948     /** @hide */
2949     @TestApi
2950     public static final int OPERATION_SET_ALWAYS_ON_VPN_PACKAGE = 30;
2951     /** @hide */
2952     @TestApi
2953     public static final int OPERATION_SET_CAMERA_DISABLED = 31;
2954     /** @hide */
2955     @TestApi
2956     public static final int OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY = 32;
2957     /** @hide */
2958     @TestApi
2959     public static final int OPERATION_SET_GLOBAL_PRIVATE_DNS = 33;
2960     /** @hide */
2961     @TestApi
2962     public static final int OPERATION_SET_LOGOUT_ENABLED = 34;
2963     /** @hide */
2964     @TestApi
2965     public static final int OPERATION_SET_MASTER_VOLUME_MUTED = 35;
2966     /** @hide */
2967     @TestApi
2968     public static final int OPERATION_SET_OVERRIDE_APNS_ENABLED = 36;
2969     /** @hide */
2970     @TestApi
2971     public static final int OPERATION_SET_PERMISSION_GRANT_STATE = 37;
2972     /** @hide */
2973     @TestApi
2974     public static final int OPERATION_SET_PERMISSION_POLICY = 38;
2975     /** @hide */
2976     @TestApi
2977     public static final int OPERATION_SET_RESTRICTIONS_PROVIDER = 39;
2978     /** @hide */
2979     @TestApi
2980     public static final int OPERATION_UNINSTALL_CA_CERT = 40;
2981 
2982     private static final String PREFIX_OPERATION = "OPERATION_";
2983 
2984     /** @hide */
2985     @IntDef(prefix = PREFIX_OPERATION, value = {
2986             OPERATION_LOCK_NOW,
2987             OPERATION_SWITCH_USER,
2988             OPERATION_START_USER_IN_BACKGROUND,
2989             OPERATION_STOP_USER,
2990             OPERATION_CREATE_AND_MANAGE_USER,
2991             OPERATION_REMOVE_USER,
2992             OPERATION_REBOOT,
2993             OPERATION_WIPE_DATA,
2994             OPERATION_LOGOUT_USER,
2995             OPERATION_SET_USER_RESTRICTION,
2996             OPERATION_SET_SYSTEM_SETTING,
2997             OPERATION_SET_KEYGUARD_DISABLED,
2998             OPERATION_SET_STATUS_BAR_DISABLED,
2999             OPERATION_SET_SYSTEM_UPDATE_POLICY,
3000             OPERATION_SET_APPLICATION_HIDDEN,
3001             OPERATION_SET_APPLICATION_RESTRICTIONS,
3002             OPERATION_SET_KEEP_UNINSTALLED_PACKAGES,
3003             OPERATION_SET_LOCK_TASK_FEATURES,
3004             OPERATION_SET_LOCK_TASK_PACKAGES,
3005             OPERATION_SET_PACKAGES_SUSPENDED,
3006             OPERATION_SET_TRUST_AGENT_CONFIGURATION,
3007             OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES,
3008             OPERATION_CLEAR_APPLICATION_USER_DATA,
3009             OPERATION_INSTALL_CA_CERT,
3010             OPERATION_INSTALL_KEY_PAIR,
3011             OPERATION_INSTALL_SYSTEM_UPDATE,
3012             OPERATION_REMOVE_ACTIVE_ADMIN,
3013             OPERATION_REMOVE_KEY_PAIR,
3014             OPERATION_REQUEST_BUGREPORT,
3015             OPERATION_SET_ALWAYS_ON_VPN_PACKAGE,
3016             OPERATION_SET_CAMERA_DISABLED,
3017             OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY,
3018             OPERATION_SET_GLOBAL_PRIVATE_DNS,
3019             OPERATION_SET_LOGOUT_ENABLED,
3020             OPERATION_SET_MASTER_VOLUME_MUTED,
3021             OPERATION_SET_OVERRIDE_APNS_ENABLED,
3022             OPERATION_SET_PERMISSION_GRANT_STATE,
3023             OPERATION_SET_PERMISSION_POLICY,
3024             OPERATION_SET_RESTRICTIONS_PROVIDER,
3025             OPERATION_UNINSTALL_CA_CERT
3026     })
3027     @Retention(RetentionPolicy.SOURCE)
3028     public static @interface DevicePolicyOperation {
3029     }
3030 
3031     /** @hide */
3032     @TestApi
3033     @NonNull
operationToString(@evicePolicyOperation int operation)3034     public static String operationToString(@DevicePolicyOperation int operation) {
3035         return DebugUtils.constantToString(DevicePolicyManager.class, PREFIX_OPERATION, operation);
3036     }
3037 
3038     private static final String PREFIX_OPERATION_SAFETY_REASON = "OPERATION_SAFETY_REASON_";
3039 
3040     /** @hide */
3041     @IntDef(prefix = PREFIX_OPERATION_SAFETY_REASON, value = {
3042             OPERATION_SAFETY_REASON_NONE,
3043             OPERATION_SAFETY_REASON_DRIVING_DISTRACTION
3044     })
3045     @Retention(RetentionPolicy.SOURCE)
3046     public static @interface OperationSafetyReason {
3047     }
3048 
3049     /** @hide */
3050     @TestApi
3051     public static final int OPERATION_SAFETY_REASON_NONE = -1;
3052 
3053     /**
3054      * Indicates that a {@link UnsafeStateException} was thrown because the operation would distract
3055      * the driver of the vehicle.
3056      */
3057     public static final int OPERATION_SAFETY_REASON_DRIVING_DISTRACTION = 1;
3058 
3059     /** @hide */
3060     @NonNull
3061     @TestApi
operationSafetyReasonToString(@perationSafetyReason int reason)3062     public static String operationSafetyReasonToString(@OperationSafetyReason int reason) {
3063         return DebugUtils.constantToString(DevicePolicyManager.class,
3064                 PREFIX_OPERATION_SAFETY_REASON, reason);
3065     }
3066 
3067     /** @hide */
isValidOperationSafetyReason(@perationSafetyReason int reason)3068     public static boolean isValidOperationSafetyReason(@OperationSafetyReason int reason) {
3069         return reason == OPERATION_SAFETY_REASON_DRIVING_DISTRACTION;
3070     }
3071 
3072     /**
3073      * Checks if it's safe to run operations that can be affected by the given {@code reason}.
3074      *
3075      * <p><b>Note:</b> notice that the operation safety state might change between the time this
3076      * method returns and the operation's method is called, so calls to the latter could still throw
3077      * a {@link UnsafeStateException} even when this method returns {@code true}.
3078      *
3079      * @param reason currently, only supported reason is
3080      * {@link #OPERATION_SAFETY_REASON_DRIVING_DISTRACTION}.
3081      *
3082      * @return whether it's safe to run operations that can be affected by the given {@code reason}.
3083      */
3084     // TODO(b/173541467): should it throw SecurityException if caller is not admin?
isSafeOperation(@perationSafetyReason int reason)3085     public boolean isSafeOperation(@OperationSafetyReason int reason) {
3086         throwIfParentInstance("isSafeOperation");
3087         if (mService == null) return false;
3088 
3089         try {
3090             return mService.isSafeOperation(reason);
3091         } catch (RemoteException e) {
3092             throw e.rethrowFromSystemServer();
3093         }
3094     }
3095 
3096     /** @hide */
resetNewUserDisclaimer()3097     public void resetNewUserDisclaimer() {
3098         if (mService != null) {
3099             try {
3100                 mService.resetNewUserDisclaimer();
3101             } catch (RemoteException e) {
3102                 throw e.rethrowFromSystemServer();
3103             }
3104         }
3105     }
3106 
3107     /**
3108      * Return true if the given administrator component is currently active (enabled) in the system.
3109      *
3110      * @param admin The administrator component to check for.
3111      * @return {@code true} if {@code admin} is currently enabled in the system, {@code false}
3112      *         otherwise
3113      */
isAdminActive(@onNull ComponentName admin)3114     public boolean isAdminActive(@NonNull ComponentName admin) {
3115         throwIfParentInstance("isAdminActive");
3116         return isAdminActiveAsUser(admin, myUserId());
3117     }
3118 
3119     /**
3120      * @see #isAdminActive(ComponentName)
3121      * @hide
3122      */
isAdminActiveAsUser(@onNull ComponentName admin, int userId)3123     public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
3124         if (mService != null) {
3125             try {
3126                 return mService.isAdminActive(admin, userId);
3127             } catch (RemoteException e) {
3128                 throw e.rethrowFromSystemServer();
3129             }
3130         }
3131         return false;
3132     }
3133 
3134     /**
3135      * Return true if the given administrator component is currently being removed
3136      * for the user.
3137      * @hide
3138      */
isRemovingAdmin(@onNull ComponentName admin, int userId)3139     public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
3140         if (mService != null) {
3141             try {
3142                 return mService.isRemovingAdmin(admin, userId);
3143             } catch (RemoteException e) {
3144                 throw e.rethrowFromSystemServer();
3145             }
3146         }
3147         return false;
3148     }
3149 
3150     /**
3151      * Return a list of all currently active device administrators' component
3152      * names.  If there are no administrators {@code null} may be
3153      * returned.
3154      */
getActiveAdmins()3155     public @Nullable List<ComponentName> getActiveAdmins() {
3156         throwIfParentInstance("getActiveAdmins");
3157         return getActiveAdminsAsUser(myUserId());
3158     }
3159 
3160     /**
3161      * @see #getActiveAdmins()
3162      * @hide
3163      */
3164     @UnsupportedAppUsage
getActiveAdminsAsUser(int userId)3165     public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) {
3166         if (mService != null) {
3167             try {
3168                 return mService.getActiveAdmins(userId);
3169             } catch (RemoteException e) {
3170                 throw e.rethrowFromSystemServer();
3171             }
3172         }
3173         return null;
3174     }
3175 
3176     /**
3177      * Used by package administration code to determine if a package can be stopped
3178      * or uninstalled.
3179      * @hide
3180      */
3181     @SystemApi
3182     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
packageHasActiveAdmins(String packageName)3183     public boolean packageHasActiveAdmins(String packageName) {
3184         return packageHasActiveAdmins(packageName, myUserId());
3185     }
3186 
3187     /**
3188      * Used by package administration code to determine if a package can be stopped
3189      * or uninstalled.
3190      * @hide
3191      */
3192     @UnsupportedAppUsage
packageHasActiveAdmins(String packageName, int userId)3193     public boolean packageHasActiveAdmins(String packageName, int userId) {
3194         if (mService != null) {
3195             try {
3196                 return mService.packageHasActiveAdmins(packageName, userId);
3197             } catch (RemoteException e) {
3198                 throw e.rethrowFromSystemServer();
3199             }
3200         }
3201         return false;
3202     }
3203 
3204     /**
3205      * Remove a current administration component.  This can only be called
3206      * by the application that owns the administration component; if you
3207      * try to remove someone else's component, a security exception will be
3208      * thrown.
3209      *
3210      * <p>Note that the operation is not synchronous and the admin might still be active (as
3211      * indicated by {@link #getActiveAdmins()}) by the time this method returns.
3212      *
3213      * @param admin The administration compononent to remove.
3214      * @throws SecurityException if the caller is not in the owner application of {@code admin}.
3215      */
removeActiveAdmin(@onNull ComponentName admin)3216     public void removeActiveAdmin(@NonNull ComponentName admin) {
3217         throwIfParentInstance("removeActiveAdmin");
3218         if (mService != null) {
3219             try {
3220                 mService.removeActiveAdmin(admin, myUserId());
3221             } catch (RemoteException e) {
3222                 throw e.rethrowFromSystemServer();
3223             }
3224         }
3225     }
3226 
3227     /**
3228      * Returns true if an administrator has been granted a particular device policy. This can be
3229      * used to check whether the administrator was activated under an earlier set of policies, but
3230      * requires additional policies after an upgrade.
3231      *
3232      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be an
3233      *            active administrator, or an exception will be thrown.
3234      * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
3235      * @throws SecurityException if {@code admin} is not an active administrator.
3236      */
hasGrantedPolicy(@onNull ComponentName admin, int usesPolicy)3237     public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) {
3238         throwIfParentInstance("hasGrantedPolicy");
3239         if (mService != null) {
3240             try {
3241                 return mService.hasGrantedPolicy(admin, usesPolicy, myUserId());
3242             } catch (RemoteException e) {
3243                 throw e.rethrowFromSystemServer();
3244             }
3245         }
3246         return false;
3247     }
3248 
3249     /**
3250      * Returns true if the Profile Challenge is available to use for the given profile user.
3251      *
3252      * @hide
3253      */
isSeparateProfileChallengeAllowed(int userHandle)3254     public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3255         if (mService != null) {
3256             try {
3257                 return mService.isSeparateProfileChallengeAllowed(userHandle);
3258             } catch (RemoteException e) {
3259                 throw e.rethrowFromSystemServer();
3260             }
3261         }
3262         return false;
3263     }
3264 
3265     /**
3266      * Constant for {@link #setPasswordQuality}: the policy has no requirements
3267      * for the password.  Note that quality constants are ordered so that higher
3268      * values are more restrictive.
3269      */
3270     public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
3271 
3272     /**
3273      * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
3274      * recognition technology.  This implies technologies that can recognize the identity of
3275      * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
3276      * Note that quality constants are ordered so that higher values are more restrictive.
3277      */
3278     public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
3279 
3280     /**
3281      * Constant for {@link #setPasswordQuality}: the policy requires some kind
3282      * of password or pattern, but doesn't care what it is. Note that quality constants
3283      * are ordered so that higher values are more restrictive.
3284      */
3285     public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
3286 
3287     /**
3288      * Constant for {@link #setPasswordQuality}: the user must have entered a
3289      * password containing at least numeric characters.  Note that quality
3290      * constants are ordered so that higher values are more restrictive.
3291      */
3292     public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
3293 
3294     /**
3295      * Constant for {@link #setPasswordQuality}: the user must have entered a
3296      * password containing at least numeric characters with no repeating (4444)
3297      * or ordered (1234, 4321, 2468) sequences.  Note that quality
3298      * constants are ordered so that higher values are more restrictive.
3299      */
3300     public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
3301 
3302     /**
3303      * Constant for {@link #setPasswordQuality}: the user must have entered a
3304      * password containing at least alphabetic (or other symbol) characters.
3305      * Note that quality constants are ordered so that higher values are more
3306      * restrictive.
3307      */
3308     public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
3309 
3310     /**
3311      * Constant for {@link #setPasswordQuality}: the user must have entered a
3312      * password containing at least <em>both></em> numeric <em>and</em>
3313      * alphabetic (or other symbol) characters.  Note that quality constants are
3314      * ordered so that higher values are more restrictive.
3315      */
3316     public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
3317 
3318     /**
3319      * Constant for {@link #setPasswordQuality}: allows the admin to set precisely how many
3320      * characters of various types the password should contain to satisfy the policy. The admin
3321      * should set these requirements via {@link #setPasswordMinimumLetters},
3322      * {@link #setPasswordMinimumNumeric}, {@link #setPasswordMinimumSymbols},
3323      * {@link #setPasswordMinimumUpperCase}, {@link #setPasswordMinimumLowerCase},
3324      * {@link #setPasswordMinimumNonLetter}, and {@link #setPasswordMinimumLength}.
3325      * Note that quality constants are ordered so that higher values are more restrictive.
3326      */
3327     public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
3328 
3329     /**
3330      * Constant for {@link #setPasswordQuality}: the user is not allowed to
3331      * modify password. In case this password quality is set, the password is
3332      * managed by a profile owner. The profile owner can set any password,
3333      * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note
3334      * that quality constants are ordered so that higher values are more
3335      * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is
3336      * the highest.
3337      * @hide
3338      */
3339     public static final int PASSWORD_QUALITY_MANAGED = 0x80000;
3340 
3341     /**
3342      * @hide
3343      *
3344      * adb shell dpm set-{device,profile}-owner will normally not allow installing an owner to
3345      * a user with accounts.  {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED}
3346      * and {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} are the account features
3347      * used by authenticator to exempt their accounts from this:
3348      *
3349      * <ul>
3350      *     <li>Non-test-only DO/PO still can't be installed when there are accounts.
3351      *     <p>In order to make an apk test-only, add android:testOnly="true" to the
3352      *     &lt;application&gt; tag in the manifest.
3353      *
3354      *     <li>Test-only DO/PO can be installed even when there are accounts, as long as all the
3355      *     accounts have the {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} feature.
3356      *     Some authenticators claim to have any features, so to detect it, we also check
3357      *     {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} and disallow installing
3358      *     if any of the accounts have it.
3359      * </ul>
3360      */
3361     @SystemApi
3362     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED =
3363             "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED";
3364 
3365     /** @hide See {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} */
3366     @SystemApi
3367     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED =
3368             "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED";
3369 
3370     /**
3371      * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
3372      * manifest element, which declares that the module should be considered a required app for
3373      * managed users.
3374      * <p>Being declared as a required app prevents removal of this package during the
3375      * provisioning process.
3376      * @hide
3377      */
3378     @SystemApi
3379     public static final String REQUIRED_APP_MANAGED_USER = "android.app.REQUIRED_APP_MANAGED_USER";
3380 
3381     /**
3382      * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
3383      * manifest element, which declares that the module should be considered a required app for
3384      * managed devices.
3385      * <p>Being declared as a required app prevents removal of this package during the
3386      * provisioning process.
3387      * @hide
3388      */
3389     @SystemApi
3390     public static final String REQUIRED_APP_MANAGED_DEVICE =
3391             "android.app.REQUIRED_APP_MANAGED_DEVICE";
3392 
3393     /**
3394      * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
3395      * manifest element, which declares that the module should be considered a required app for
3396      * managed profiles.
3397      * <p>Being declared as a required app prevents removal of this package during the
3398      * provisioning process.
3399      * @hide
3400      */
3401     @SystemApi
3402     public static final String REQUIRED_APP_MANAGED_PROFILE =
3403             "android.app.REQUIRED_APP_MANAGED_PROFILE";
3404 
3405     /**
3406      * Called by an application that is administering the device to set the password restrictions it
3407      * is imposing. After setting this, the user will not be able to enter a new password that is
3408      * not at least as restrictive as what has been set. Note that the current password will remain
3409      * until the user has set a new one, so the change does not take place immediately. To prompt
3410      * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
3411      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after calling this method.
3412      * <p>
3413      * Quality constants are ordered so that higher values are more restrictive; thus the highest
3414      * requested quality constant (between the policy set here, the user's preference, and any other
3415      * considerations) is the one that is in effect.
3416      * <p>
3417      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3418      * password is always treated as empty.
3419      * <p>
3420      * The calling device admin must have requested
3421      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3422      * not, a security exception will be thrown.
3423      * <p>
3424      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
3425      * {@link DevicePolicyManager} instance returned by
3426      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3427      * profile. Apps targeting {@link android.os.Build.VERSION_CODES#S} and above, with the
3428      * exception of a profile owner on an organization-owned device (as can be identified by
3429      * {@link #isOrganizationOwnedDeviceWithManagedProfile}), will get a
3430      * {@code IllegalArgumentException} when calling this method on the parent
3431      * {@link DevicePolicyManager} instance.
3432      *
3433      * <p><strong>Note:</strong> Specifying password requirements using this method clears the
3434      * password complexity requirements set using {@link #setRequiredPasswordComplexity(int)}.
3435      * If this method is called on the {@link DevicePolicyManager} instance returned by
3436      * {@link #getParentProfileInstance(ComponentName)}, then password complexity requirements
3437      * set on the primary {@link DevicePolicyManager} must be cleared first by calling
3438      * {@link #setRequiredPasswordComplexity} with {@link #PASSWORD_COMPLEXITY_NONE) first.
3439      *
3440      * @deprecated Prefer using {@link #setRequiredPasswordComplexity(int)}, to require a password
3441      * that satisfies a complexity level defined by the platform, rather than specifying custom
3442      * password requirement.
3443      * Setting custom, overly-complicated password requirements leads to passwords that are hard
3444      * for users to remember and may not provide any security benefits given as Android uses
3445      * hardware-backed throttling to thwart online and offline brute-forcing of the device's
3446      * screen lock.
3447      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3448      * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED},
3449      *            {@link #PASSWORD_QUALITY_BIOMETRIC_WEAK},
3450      *            {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC},
3451      *            {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
3452      *            {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
3453      * @throws SecurityException if {@code admin} is not an active administrator, if {@code admin}
3454      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} or if the
3455      *             calling app is targeting {@link android.os.Build.VERSION_CODES#S} and above,
3456      *             and is calling the method the {@link DevicePolicyManager} instance returned by
3457      *             {@link #getParentProfileInstance(ComponentName)}.
3458      * @throws IllegalStateException if the caller is trying to set password quality on the parent
3459      *             {@link DevicePolicyManager} instance while password complexity was set on the
3460      *             primary {@link DevicePolicyManager} instance.
3461      */
3462     @Deprecated
setPasswordQuality(@onNull ComponentName admin, int quality)3463     public void setPasswordQuality(@NonNull ComponentName admin, int quality) {
3464         if (mService != null) {
3465             try {
3466                 mService.setPasswordQuality(admin, quality, mParentInstance);
3467             } catch (RemoteException e) {
3468                 throw e.rethrowFromSystemServer();
3469             }
3470         }
3471     }
3472 
3473     /**
3474      * Retrieve the current minimum password quality for a particular admin or all admins that set
3475      * restrictions on this user and its participating profiles. Restrictions on profiles that have
3476      * a separate challenge are not taken into account.
3477      *
3478      * <p>This method can be called on the {@link DevicePolicyManager} instance
3479      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3480      * restrictions on the parent profile.
3481      *
3482      * <p>Note: on devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
3483      * the password is always treated as empty.
3484      *
3485      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3486      *
3487      * @param admin The name of the admin component to check, or {@code null} to aggregate
3488      * all admins.
3489      */
3490     @Deprecated
getPasswordQuality(@ullable ComponentName admin)3491     public int getPasswordQuality(@Nullable ComponentName admin) {
3492         return getPasswordQuality(admin, myUserId());
3493     }
3494 
3495     /** @hide per-user version */
3496     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordQuality(@ullable ComponentName admin, int userHandle)3497     public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) {
3498         if (mService != null) {
3499             try {
3500                 return mService.getPasswordQuality(admin, userHandle, mParentInstance);
3501             } catch (RemoteException e) {
3502                 throw e.rethrowFromSystemServer();
3503             }
3504         }
3505         return PASSWORD_QUALITY_UNSPECIFIED;
3506     }
3507 
3508     /**
3509      * Called by an application that is administering the device to set the minimum allowed password
3510      * length. After setting this, the user will not be able to enter a new password that is not at
3511      * least as restrictive as what has been set. Note that the current password will remain until
3512      * the user has set a new one, so the change does not take place immediately. To prompt the user
3513      * for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
3514      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
3515      * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
3516      * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
3517      * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with
3518      * {@link #setPasswordQuality}. If an app targeting SDK level
3519      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
3520      * password quality to one of these values first, this method will throw
3521      * {@link IllegalStateException}.
3522      * <p>
3523      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3524      * password is always treated as empty.
3525      * <p>
3526      * The calling device admin must have requested
3527      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3528      * not, a security exception will be thrown.
3529      * <p>
3530      *
3531      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
3532      * {@link DevicePolicyManager} instance returned by
3533      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3534      * profile.
3535      *
3536      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3537      *
3538      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3539      * @param length The new desired minimum password length. A value of 0 means there is no
3540      *     restriction.
3541      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3542      *     does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3543      * @throws IllegalStateException if the calling app is targeting SDK level
3544      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
3545      *     quality requirement prior to calling this method.
3546      */
3547     @Deprecated
setPasswordMinimumLength(@onNull ComponentName admin, int length)3548     public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
3549         if (mService != null) {
3550             try {
3551                 mService.setPasswordMinimumLength(admin, length, mParentInstance);
3552             } catch (RemoteException e) {
3553                 throw e.rethrowFromSystemServer();
3554             }
3555         }
3556     }
3557 
3558     /**
3559      * Retrieve the current minimum password length for a particular admin or all admins that set
3560      * restrictions on this user and its participating profiles. Restrictions on profiles that have
3561      * a separate challenge are not taken into account.
3562      *
3563      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3564      * password is always treated as empty.
3565      *
3566      * <p>This method can be called on the {@link DevicePolicyManager} instance
3567      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3568      * restrictions on the parent profile.
3569      *
3570      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3571      *
3572      * @param admin The name of the admin component to check, or {@code null} to aggregate
3573      * all admins.
3574      */
3575     @Deprecated
getPasswordMinimumLength(@ullable ComponentName admin)3576     public int getPasswordMinimumLength(@Nullable ComponentName admin) {
3577         return getPasswordMinimumLength(admin, myUserId());
3578     }
3579 
3580     /** @hide per-user version */
3581     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLength(@ullable ComponentName admin, int userHandle)3582     public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) {
3583         if (mService != null) {
3584             try {
3585                 return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance);
3586             } catch (RemoteException e) {
3587                 throw e.rethrowFromSystemServer();
3588             }
3589         }
3590         return 0;
3591     }
3592 
3593     /**
3594      * Called by an application that is administering the device to set the minimum number of upper
3595      * case letters required in the password. After setting this, the user will not be able to enter
3596      * a new password that is not at least as restrictive as what has been set. Note that the
3597      * current password will remain until the user has set a new one, so the change does not take
3598      * place immediately. To prompt the user for a new password, use
3599      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
3600      * setting this value. This constraint is only imposed if the administrator has also requested
3601      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
3602      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
3603      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
3604      * {@link IllegalStateException}. The default value is 0.
3605      * <p>
3606      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3607      * password is always treated as empty.
3608      * <p>
3609      * The calling device admin must have requested
3610      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3611      * not, a security exception will be thrown.
3612      * <p>
3613      *
3614      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
3615      * {@link DevicePolicyManager} instance returned by
3616      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3617      * profile.
3618      *
3619      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3620      *
3621      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3622      * @param length The new desired minimum number of upper case letters required in the password.
3623      *            A value of 0 means there is no restriction.
3624      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3625      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3626      * @throws IllegalStateException if the calling app is targeting SDK level
3627      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
3628      *     quality requirement prior to calling this method.
3629      */
3630     @Deprecated
setPasswordMinimumUpperCase(@onNull ComponentName admin, int length)3631     public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
3632         if (mService != null) {
3633             try {
3634                 mService.setPasswordMinimumUpperCase(admin, length, mParentInstance);
3635             } catch (RemoteException e) {
3636                 throw e.rethrowFromSystemServer();
3637             }
3638         }
3639     }
3640 
3641     /**
3642      * Retrieve the current number of upper case letters required in the password
3643      * for a particular admin or all admins that set restrictions on this user and
3644      * its participating profiles. Restrictions on profiles that have a separate challenge
3645      * are not taken into account.
3646      * This is the same value as set by
3647      * {@link #setPasswordMinimumUpperCase(ComponentName, int)}
3648      * and only applies when the password quality is
3649      * {@link #PASSWORD_QUALITY_COMPLEX}.
3650      *
3651      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3652      * password is always treated as empty.
3653      *
3654      * <p>This method can be called on the {@link DevicePolicyManager} instance
3655      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3656      * restrictions on the parent profile.
3657      *
3658      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3659      *
3660      * @param admin The name of the admin component to check, or {@code null} to
3661      *            aggregate all admins.
3662      * @return The minimum number of upper case letters required in the
3663      *         password.
3664      */
3665     @Deprecated
getPasswordMinimumUpperCase(@ullable ComponentName admin)3666     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) {
3667         return getPasswordMinimumUpperCase(admin, myUserId());
3668     }
3669 
3670     /** @hide per-user version */
3671     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumUpperCase(@ullable ComponentName admin, int userHandle)3672     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) {
3673         if (mService != null) {
3674             try {
3675                 return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance);
3676             } catch (RemoteException e) {
3677                 throw e.rethrowFromSystemServer();
3678             }
3679         }
3680         return 0;
3681     }
3682 
3683     /**
3684      * Called by an application that is administering the device to set the minimum number of lower
3685      * case letters required in the password. After setting this, the user will not be able to enter
3686      * a new password that is not at least as restrictive as what has been set. Note that the
3687      * current password will remain until the user has set a new one, so the change does not take
3688      * place immediately. To prompt the user for a new password, use
3689      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
3690      * setting this value. This constraint is only imposed if the administrator has also requested
3691      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
3692      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
3693      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
3694      * {@link IllegalStateException}. The default value is 0.
3695      * <p>
3696      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3697      * password is always treated as empty.
3698      * <p>
3699      * The calling device admin must have requested
3700      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3701      * not, a security exception will be thrown.
3702      * <p>
3703      *
3704      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
3705      * {@link DevicePolicyManager} instance returned by
3706      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3707      * profile.
3708      *
3709      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3710      *
3711      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3712      * @param length The new desired minimum number of lower case letters required in the password.
3713      *            A value of 0 means there is no restriction.
3714      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3715      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3716      * @throws IllegalStateException if the calling app is targeting SDK level
3717      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
3718      *     quality requirement prior to calling this method.
3719      */
3720     @Deprecated
setPasswordMinimumLowerCase(@onNull ComponentName admin, int length)3721     public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
3722         if (mService != null) {
3723             try {
3724                 mService.setPasswordMinimumLowerCase(admin, length, mParentInstance);
3725             } catch (RemoteException e) {
3726                 throw e.rethrowFromSystemServer();
3727             }
3728         }
3729     }
3730 
3731     /**
3732      * Retrieve the current number of lower case letters required in the password
3733      * for a particular admin or all admins that set restrictions on this user
3734      * and its participating profiles. Restrictions on profiles that have
3735      * a separate challenge are not taken into account.
3736      * This is the same value as set by
3737      * {@link #setPasswordMinimumLowerCase(ComponentName, int)}
3738      * and only applies when the password quality is
3739      * {@link #PASSWORD_QUALITY_COMPLEX}.
3740      *
3741      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3742      * password is always treated as empty.
3743      *
3744      * <p>This method can be called on the {@link DevicePolicyManager} instance
3745      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3746      * restrictions on the parent profile.
3747      *
3748      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3749      *
3750      * @param admin The name of the admin component to check, or {@code null} to
3751      *            aggregate all admins.
3752      * @return The minimum number of lower case letters required in the
3753      *         password.
3754      */
3755     @Deprecated
getPasswordMinimumLowerCase(@ullable ComponentName admin)3756     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) {
3757         return getPasswordMinimumLowerCase(admin, myUserId());
3758     }
3759 
3760     /** @hide per-user version */
3761     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLowerCase(@ullable ComponentName admin, int userHandle)3762     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) {
3763         if (mService != null) {
3764             try {
3765                 return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance);
3766             } catch (RemoteException e) {
3767                 throw e.rethrowFromSystemServer();
3768             }
3769         }
3770         return 0;
3771     }
3772 
3773     /**
3774      * Called by an application that is administering the device to set the minimum number of
3775      * letters required in the password. After setting this, the user will not be able to enter a
3776      * new password that is not at least as restrictive as what has been set. Note that the current
3777      * password will remain until the user has set a new one, so the change does not take place
3778      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
3779      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
3780      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
3781      * {@link #setPasswordQuality}. If an app targeting SDK level
3782      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
3783      * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
3784      * {@link IllegalStateException}. The default value is 1.
3785      * <p>
3786      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3787      * password is always treated as empty.
3788      * <p>
3789      * The calling device admin must have requested
3790      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3791      * not, a security exception will be thrown.
3792      * <p>
3793      *
3794      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
3795      * {@link DevicePolicyManager} instance returned by
3796      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3797      * profile.
3798      *
3799      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3800      *
3801      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3802      * @param length The new desired minimum number of letters required in the password. A value of
3803      *            0 means there is no restriction.
3804      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3805      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3806      * @throws IllegalStateException if the calling app is targeting SDK level
3807      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
3808      *     quality requirement prior to calling this method.
3809      */
3810     @Deprecated
setPasswordMinimumLetters(@onNull ComponentName admin, int length)3811     public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
3812         if (mService != null) {
3813             try {
3814                 mService.setPasswordMinimumLetters(admin, length, mParentInstance);
3815             } catch (RemoteException e) {
3816                 throw e.rethrowFromSystemServer();
3817             }
3818         }
3819     }
3820 
3821     /**
3822      * Retrieve the current number of letters required in the password
3823      * for a particular admin or all admins that set restrictions on this user
3824      * and its participating profiles. Restrictions on profiles that have
3825      * a separate challenge are not taken into account.
3826      * This is the same value as set by
3827      * {@link #setPasswordMinimumLetters(ComponentName, int)}
3828      * and only applies when the password quality is
3829      * {@link #PASSWORD_QUALITY_COMPLEX}.
3830      *
3831      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3832      * password is always treated as empty.
3833      *
3834      * <p>This method can be called on the {@link DevicePolicyManager} instance
3835      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3836      * restrictions on the parent profile.
3837      *
3838      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3839      *
3840      * @param admin The name of the admin component to check, or {@code null} to
3841      *            aggregate all admins.
3842      * @return The minimum number of letters required in the password.
3843      */
3844     @Deprecated
getPasswordMinimumLetters(@ullable ComponentName admin)3845     public int getPasswordMinimumLetters(@Nullable ComponentName admin) {
3846         return getPasswordMinimumLetters(admin, myUserId());
3847     }
3848 
3849     /** @hide per-user version */
3850     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLetters(@ullable ComponentName admin, int userHandle)3851     public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) {
3852         if (mService != null) {
3853             try {
3854                 return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance);
3855             } catch (RemoteException e) {
3856                 throw e.rethrowFromSystemServer();
3857             }
3858         }
3859         return 0;
3860     }
3861 
3862     /**
3863      * Called by an application that is administering the device to set the minimum number of
3864      * numerical digits required in the password. After setting this, the user will not be able to
3865      * enter a new password that is not at least as restrictive as what has been set. Note that the
3866      * current password will remain until the user has set a new one, so the change does not take
3867      * place immediately. To prompt the user for a new password, use
3868      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
3869      * setting this value. This constraint is only imposed if the administrator has also requested
3870      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
3871      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
3872      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
3873      * {@link IllegalStateException}. The default value is 1.
3874      * <p>
3875      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3876      * password is always treated as empty.
3877      * <p>
3878      * The calling device admin must have requested
3879      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3880      * not, a security exception will be thrown.
3881      * <p>
3882      *
3883      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
3884      * {@link DevicePolicyManager} instance returned by
3885      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3886      * profile.
3887      *
3888      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3889      *
3890      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3891      * @param length The new desired minimum number of numerical digits required in the password. A
3892      *            value of 0 means there is no restriction.
3893      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3894      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3895      * @throws IllegalStateException if the calling app is targeting SDK level
3896      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
3897      *     quality requirement prior to calling this method.
3898      */
3899     @Deprecated
setPasswordMinimumNumeric(@onNull ComponentName admin, int length)3900     public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
3901         if (mService != null) {
3902             try {
3903                 mService.setPasswordMinimumNumeric(admin, length, mParentInstance);
3904             } catch (RemoteException e) {
3905                 throw e.rethrowFromSystemServer();
3906             }
3907         }
3908     }
3909 
3910     /**
3911      * Retrieve the current number of numerical digits required in the password
3912      * for a particular admin or all admins that set restrictions on this user
3913      * and its participating profiles. Restrictions on profiles that have
3914      * a separate challenge are not taken into account.
3915      * This is the same value as set by
3916      * {@link #setPasswordMinimumNumeric(ComponentName, int)}
3917      * and only applies when the password quality is
3918      * {@link #PASSWORD_QUALITY_COMPLEX}.
3919      *
3920      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3921      * password is always treated as empty.
3922      *
3923      * <p>This method can be called on the {@link DevicePolicyManager} instance
3924      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3925      * restrictions on the parent profile.
3926      *
3927      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3928      *
3929      * @param admin The name of the admin component to check, or {@code null} to
3930      *            aggregate all admins.
3931      * @return The minimum number of numerical digits required in the password.
3932      */
3933     @Deprecated
getPasswordMinimumNumeric(@ullable ComponentName admin)3934     public int getPasswordMinimumNumeric(@Nullable ComponentName admin) {
3935         return getPasswordMinimumNumeric(admin, myUserId());
3936     }
3937 
3938     /** @hide per-user version */
3939     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumNumeric(@ullable ComponentName admin, int userHandle)3940     public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) {
3941         if (mService != null) {
3942             try {
3943                 return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance);
3944             } catch (RemoteException e) {
3945                 throw e.rethrowFromSystemServer();
3946             }
3947         }
3948         return 0;
3949     }
3950 
3951     /**
3952      * Called by an application that is administering the device to set the minimum number of
3953      * symbols required in the password. After setting this, the user will not be able to enter a
3954      * new password that is not at least as restrictive as what has been set. Note that the current
3955      * password will remain until the user has set a new one, so the change does not take place
3956      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
3957      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
3958      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
3959      * {@link #setPasswordQuality}. If an app targeting SDK level
3960      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
3961      * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
3962      * {@link IllegalStateException}. The default value is 1.
3963      * <p>
3964      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3965      * password is always treated as empty.
3966      * <p>
3967      * The calling device admin must have requested
3968      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3969      * not, a security exception will be thrown.
3970      * <p>
3971      *
3972      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
3973      * {@link DevicePolicyManager} instance returned by
3974      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3975      * profile.
3976      *
3977      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3978      *
3979      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3980      * @param length The new desired minimum number of symbols required in the password. A value of
3981      *            0 means there is no restriction.
3982      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3983      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3984      * @throws IllegalStateException if the calling app is targeting SDK level
3985      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
3986      *     quality requirement prior to calling this method.
3987      */
3988     @Deprecated
setPasswordMinimumSymbols(@onNull ComponentName admin, int length)3989     public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
3990         if (mService != null) {
3991             try {
3992                 mService.setPasswordMinimumSymbols(admin, length, mParentInstance);
3993             } catch (RemoteException e) {
3994                 throw e.rethrowFromSystemServer();
3995             }
3996         }
3997     }
3998 
3999     /**
4000      * Retrieve the current number of symbols required in the password
4001      * for a particular admin or all admins that set restrictions on this user
4002      * and its participating profiles. Restrictions on profiles that have
4003      * a separate challenge are not taken into account. This is the same value as
4004      * set by {@link #setPasswordMinimumSymbols(ComponentName, int)}
4005      * and only applies when the password quality is
4006      * {@link #PASSWORD_QUALITY_COMPLEX}.
4007      *
4008      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4009      * password is always treated as empty.
4010      *
4011      * <p>This method can be called on the {@link DevicePolicyManager} instance
4012      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4013      * restrictions on the parent profile.
4014      *
4015      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4016      *
4017      * @param admin The name of the admin component to check, or {@code null} to
4018      *            aggregate all admins.
4019      * @return The minimum number of symbols required in the password.
4020      */
4021     @Deprecated
getPasswordMinimumSymbols(@ullable ComponentName admin)4022     public int getPasswordMinimumSymbols(@Nullable ComponentName admin) {
4023         return getPasswordMinimumSymbols(admin, myUserId());
4024     }
4025 
4026     /** @hide per-user version */
4027     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumSymbols(@ullable ComponentName admin, int userHandle)4028     public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) {
4029         if (mService != null) {
4030             try {
4031                 return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance);
4032             } catch (RemoteException e) {
4033                 throw e.rethrowFromSystemServer();
4034             }
4035         }
4036         return 0;
4037     }
4038 
4039     /**
4040      * Called by an application that is administering the device to set the minimum number of
4041      * non-letter characters (numerical digits or symbols) required in the password. After setting
4042      * this, the user will not be able to enter a new password that is not at least as restrictive
4043      * as what has been set. Note that the current password will remain until the user has set a new
4044      * one, so the change does not take place immediately. To prompt the user for a new password,
4045      * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
4046      * setting this value. This constraint is only imposed if the administrator has also requested
4047      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
4048      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
4049      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4050      * {@link IllegalStateException}. The default value is 0.
4051      * <p>
4052      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4053      * password is always treated as empty.
4054      * <p>
4055      * The calling device admin must have requested
4056      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4057      * not, a security exception will be thrown.
4058      * <p>
4059      *
4060      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4061      * {@link DevicePolicyManager} instance returned by
4062      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4063      * profile.
4064      *
4065      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4066      *
4067      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4068      * @param length The new desired minimum number of letters required in the password. A value of
4069      *            0 means there is no restriction.
4070      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4071      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4072      * @throws IllegalStateException if the calling app is targeting SDK level
4073      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4074      *     quality requirement prior to calling this method.
4075      */
4076     @Deprecated
setPasswordMinimumNonLetter(@onNull ComponentName admin, int length)4077     public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
4078         if (mService != null) {
4079             try {
4080                 mService.setPasswordMinimumNonLetter(admin, length, mParentInstance);
4081             } catch (RemoteException e) {
4082                 throw e.rethrowFromSystemServer();
4083             }
4084         }
4085     }
4086 
4087     /**
4088      * Retrieve the current number of non-letter characters required in the password
4089      * for a particular admin or all admins that set restrictions on this user
4090      * and its participating profiles. Restrictions on profiles that have
4091      * a separate challenge are not taken into account.
4092      * This is the same value as set by
4093      * {@link #setPasswordMinimumNonLetter(ComponentName, int)}
4094      * and only applies when the password quality is
4095      * {@link #PASSWORD_QUALITY_COMPLEX}.
4096      *
4097      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4098      * password is always treated as empty.
4099      *
4100      * <p>This method can be called on the {@link DevicePolicyManager} instance
4101      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4102      * restrictions on the parent profile.
4103      *
4104      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4105      *
4106      * @param admin The name of the admin component to check, or {@code null} to
4107      *            aggregate all admins.
4108      * @return The minimum number of letters required in the password.
4109      */
4110     @Deprecated
getPasswordMinimumNonLetter(@ullable ComponentName admin)4111     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) {
4112         return getPasswordMinimumNonLetter(admin, myUserId());
4113     }
4114 
4115     /** @hide per-user version */
4116     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumNonLetter(@ullable ComponentName admin, int userHandle)4117     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) {
4118         if (mService != null) {
4119             try {
4120                 return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance);
4121             } catch (RemoteException e) {
4122                 throw e.rethrowFromSystemServer();
4123             }
4124         }
4125         return 0;
4126     }
4127 
4128     /**
4129      * Returns minimum PasswordMetrics that satisfies all admin policies.
4130      *
4131      * @hide
4132      */
getPasswordMinimumMetrics(@serIdInt int userHandle)4133     public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle) {
4134         return getPasswordMinimumMetrics(userHandle, false);
4135     }
4136 
4137     /**
4138      * Returns minimum PasswordMetrics that satisfies all admin policies.
4139      * If requested, only consider device-wide admin policies and ignore policies set on the
4140      * managed profile instance (as if the managed profile had separate work challenge).
4141      *
4142      * @hide
4143      */
getPasswordMinimumMetrics(@serIdInt int userHandle, boolean deviceWideOnly)4144     public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle,
4145             boolean deviceWideOnly) {
4146         if (mService != null) {
4147             try {
4148                 return mService.getPasswordMinimumMetrics(userHandle, deviceWideOnly);
4149             } catch (RemoteException e) {
4150                 throw e.rethrowFromSystemServer();
4151             }
4152         }
4153         return null;
4154     }
4155 
4156     /**
4157      * Called by an application that is administering the device to set the length of the password
4158      * history. After setting this, the user will not be able to enter a new password that is the
4159      * same as any password in the history. Note that the current password will remain until the
4160      * user has set a new one, so the change does not take place immediately. To prompt the user for
4161      * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
4162      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value.
4163      * <p>
4164      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4165      * password history length is always 0.
4166      * <p>
4167      * The calling device admin must have requested
4168      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4169      * not, a security exception will be thrown.
4170      * <p>
4171      * This method can be called on the {@link DevicePolicyManager} instance returned by
4172      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4173      * profile.
4174      *
4175      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4176      * @param length The new desired length of password history. A value of 0 means there is no
4177      *            restriction.
4178      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4179      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4180      */
4181     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setPasswordHistoryLength(@onNull ComponentName admin, int length)4182     public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
4183         if (mService != null) {
4184             try {
4185                 mService.setPasswordHistoryLength(admin, length, mParentInstance);
4186             } catch (RemoteException e) {
4187                 throw e.rethrowFromSystemServer();
4188             }
4189         }
4190     }
4191 
4192     /**
4193      * Called by a device admin to set the password expiration timeout. Calling this method will
4194      * restart the countdown for password expiration for the given admin, as will changing the
4195      * device password (for all admins).
4196      * <p>
4197      * The provided timeout is the time delta in ms and will be added to the current time. For
4198      * example, to have the password expire 5 days from now, timeout would be 5 * 86400 * 1000 =
4199      * 432000000 ms for timeout.
4200      * <p>
4201      * To disable password expiration, a value of 0 may be used for timeout.
4202      * <p>
4203      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4204      * password expiration is always disabled.
4205      * <p>
4206      * The calling device admin must have requested
4207      * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this method; if it has
4208      * not, a security exception will be thrown.
4209      * <p>
4210      * Note that setting the password will automatically reset the expiration time for all active
4211      * admins. Active admins do not need to explicitly call this method in that case.
4212      * <p>
4213      * This method can be called on the {@link DevicePolicyManager} instance returned by
4214      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4215      * profile.
4216      *
4217      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4218      * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 means
4219      *            there is no restriction (unlimited).
4220      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4221      *             does not use {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD}
4222      */
4223     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setPasswordExpirationTimeout(@onNull ComponentName admin, long timeout)4224     public void setPasswordExpirationTimeout(@NonNull ComponentName admin, long timeout) {
4225         if (mService != null) {
4226             try {
4227                 mService.setPasswordExpirationTimeout(admin, timeout, mParentInstance);
4228             } catch (RemoteException e) {
4229                 throw e.rethrowFromSystemServer();
4230             }
4231         }
4232     }
4233 
4234     /**
4235      * Get the password expiration timeout for the given admin. The expiration timeout is the
4236      * recurring expiration timeout provided in the call to
4237      * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
4238      * aggregate of all participating policy administrators if {@code admin} is null. Admins that
4239      * have set restrictions on profiles that have a separate challenge are not taken into account.
4240      *
4241      * <p>This method can be called on the {@link DevicePolicyManager} instance
4242      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4243      * restrictions on the parent profile.
4244      *
4245      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4246      * password expiration is always disabled and this method always returns 0.
4247      *
4248      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
4249      * @return The timeout for the given admin or the minimum of all timeouts
4250      */
4251     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordExpirationTimeout(@ullable ComponentName admin)4252     public long getPasswordExpirationTimeout(@Nullable ComponentName admin) {
4253         if (mService != null) {
4254             try {
4255                 return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance);
4256             } catch (RemoteException e) {
4257                 throw e.rethrowFromSystemServer();
4258             }
4259         }
4260         return 0;
4261     }
4262 
4263     /**
4264      * Get the current password expiration time for a particular admin or all admins that set
4265      * restrictions on this user and its participating profiles. Restrictions on profiles that have
4266      * a separate challenge are not taken into account. If admin is {@code null}, then a composite
4267      * of all expiration times is returned - which will be the minimum of all of them.
4268      *
4269      * <p>This method can be called on the {@link DevicePolicyManager} instance
4270      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4271      * the password expiration for the parent profile.
4272      *
4273      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4274      * password expiration is always disabled and this method always returns 0.
4275      *
4276      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
4277      * @return The password expiration time, in milliseconds since epoch.
4278      */
4279     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordExpiration(@ullable ComponentName admin)4280     public long getPasswordExpiration(@Nullable ComponentName admin) {
4281         if (mService != null) {
4282             try {
4283                 return mService.getPasswordExpiration(admin, myUserId(), mParentInstance);
4284             } catch (RemoteException e) {
4285                 throw e.rethrowFromSystemServer();
4286             }
4287         }
4288         return 0;
4289     }
4290 
4291     /**
4292      * Retrieve the current password history length for a particular admin or all admins that
4293      * set restrictions on this user and its participating profiles. Restrictions on profiles that
4294      * have a separate challenge are not taken into account.
4295      *
4296      * <p>This method can be called on the {@link DevicePolicyManager} instance
4297      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4298      * restrictions on the parent profile.
4299      *
4300      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4301      * password history length is always 0.
4302      *
4303      * @param admin The name of the admin component to check, or {@code null} to aggregate
4304      * all admins.
4305      * @return The length of the password history
4306      */
4307     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordHistoryLength(@ullable ComponentName admin)4308     public int getPasswordHistoryLength(@Nullable ComponentName admin) {
4309         return getPasswordHistoryLength(admin, myUserId());
4310     }
4311 
4312     /** @hide per-user version */
4313     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
4314     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordHistoryLength(@ullable ComponentName admin, int userHandle)4315     public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) {
4316         if (mService != null) {
4317             try {
4318                 return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance);
4319             } catch (RemoteException e) {
4320                 throw e.rethrowFromSystemServer();
4321             }
4322         }
4323         return 0;
4324     }
4325 
4326     /**
4327      * Return the maximum password length that the device supports for a
4328      * particular password quality.
4329      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4330      * password is always empty and this method always returns 0.
4331      * @param quality The quality being interrogated.
4332      * @return Returns the maximum length that the user can enter.
4333      */
getPasswordMaximumLength(int quality)4334     public int getPasswordMaximumLength(int quality) {
4335         PackageManager pm = mContext.getPackageManager();
4336         if (!pm.hasSystemFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)) {
4337             return 0;
4338         }
4339         return MAX_PASSWORD_LENGTH;
4340     }
4341 
4342     /**
4343      * Determines whether the calling user's current password meets policy requirements
4344      * (e.g. quality, minimum length). The user must be unlocked to perform this check.
4345      *
4346      * <p>Policy requirements which affect this check can be set by admins of the user, but also
4347      * by the admin of a managed profile associated with the calling user (when the managed profile
4348      * doesn't have a separate work challenge). When a managed profile has a separate work
4349      * challenge, its policy requirements only affect the managed profile.
4350      *
4351      * <p>Depending on the user, this method checks the policy requirement against one of the
4352      * following passwords:
4353      * <ul>
4354      * <li>For the primary user or secondary users: the personal keyguard password.
4355      * <li>For managed profiles: a work challenge if set, otherwise the parent user's personal
4356      *     keyguard password.
4357      * <ul/>
4358      * In other words, it's always checking the requirement against the password that is protecting
4359      * the calling user.
4360      *
4361      * <p>Note that this method considers all policy requirements targeting the password in
4362      * question. For example a profile owner might set a requirement on the parent profile i.e.
4363      * personal keyguard but not on the profile itself. When the device has a weak personal keyguard
4364      * password and no separate work challenge, calling this method will return {@code false}
4365      * despite the profile owner not setting a policy on the profile itself. This is because the
4366      * profile's current password is the personal keyguard password, and it does not meet all policy
4367      * requirements.
4368      *
4369      * <p>Device admins must request {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} before
4370      * calling this method. Note, this policy type is deprecated for device admins in Android 9.0
4371      * (API level 28) or higher.
4372      *
4373      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
4374      * {@link #getParentProfileInstance(ComponentName)} in order to determine if the password set on
4375      * the parent profile is sufficient.
4376      *
4377      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4378      * password is always treated as empty - i.e. this method will always return false on such
4379      * devices, provided any password requirements were set.
4380      *
4381      * @return {@code true} if the password meets the policy requirements, {@code false} otherwise
4382      * @throws SecurityException if the calling application isn't an active admin that uses
4383      *     {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4384      * @throws IllegalStateException if the user isn't unlocked
4385      */
isActivePasswordSufficient()4386     public boolean isActivePasswordSufficient() {
4387         if (mService != null) {
4388             try {
4389                 return mService.isActivePasswordSufficient(myUserId(), mParentInstance);
4390             } catch (RemoteException e) {
4391                 throw e.rethrowFromSystemServer();
4392             }
4393         }
4394         return false;
4395     }
4396 
4397     /**
4398      * Called by profile owner of a managed profile to determine whether the current device password
4399      * meets policy requirements set explicitly device-wide.
4400      * <p> This API is similar to {@link #isActivePasswordSufficient()}, with two notable
4401      * differences:
4402      * <ul>
4403      * <li>this API always targets the device password. As a result it should always be called on
4404      *   the {@link #getParentProfileInstance(ComponentName)} instance.</li>
4405      * <li>password policy requirement set on the managed profile is not taken into consideration
4406      *   by this API, even if the device currently does not have a separate work challenge set.</li>
4407      * </ul>
4408      *
4409      * <p>This API is designed to facilite progressive password enrollment flows when the DPC
4410      * imposes both device and profile password policies. DPC applies profile password policy by
4411      * calling {@link #setPasswordQuality(ComponentName, int)} or
4412      * {@link #setRequiredPasswordComplexity} on the regular {@link DevicePolicyManager} instance,
4413      * while it applies device-wide policy by calling {@link #setRequiredPasswordComplexity} on the
4414      * {@link #getParentProfileInstance(ComponentName)} instance. The DPC can utilize this check to
4415      * guide the user to set a device password first taking into consideration the device-wide
4416      * policy only, and then prompt the user to either upgrade it to be fully compliant, or enroll a
4417      * separate work challenge to satisfy the profile password policy only.
4418      *
4419      * <p>The device user must be unlocked (@link {@link UserManager#isUserUnlocked(UserHandle)})
4420      * to perform this check.
4421      *
4422      * @return {@code true} if the device password meets explicit requirement set on it,
4423      *   {@code false} otherwise.
4424      * @throws SecurityException if the calling application is not a profile owner of a managed
4425      *   profile, or if this API is not called on the parent DevicePolicyManager instance.
4426      * @throws IllegalStateException if the user isn't unlocked
4427      * @see #EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY
4428      */
isActivePasswordSufficientForDeviceRequirement()4429     public boolean isActivePasswordSufficientForDeviceRequirement() {
4430         if (!mParentInstance) {
4431             throw new SecurityException("only callable on the parent instance");
4432         }
4433         if (mService != null) {
4434             try {
4435                 return mService.isActivePasswordSufficientForDeviceRequirement();
4436             } catch (RemoteException e) {
4437                 throw e.rethrowFromSystemServer();
4438             }
4439         }
4440         return false;
4441     }
4442 
4443     /**
4444      * Returns how complex the current user's screen lock is.
4445      *
4446      * <p>Note that when called from a profile which uses an unified challenge with its parent, the
4447      * screen lock complexity of the parent will be returned.
4448      *
4449      * <p>Apps need the {@link permission#REQUEST_PASSWORD_COMPLEXITY} permission to call this
4450      * method. On Android {@link android.os.Build.VERSION_CODES#S} and above, the calling
4451      * application does not need this permission if it is a device owner or a profile owner.
4452      *
4453      * <p>This method can be called on the {@link DevicePolicyManager} instance
4454      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4455      * restrictions on the parent profile.
4456      *
4457      * @throws IllegalStateException if the user is not unlocked.
4458      * @throws SecurityException     if the calling application does not have the permission
4459      *                               {@link permission#REQUEST_PASSWORD_COMPLEXITY}, and is not a
4460      *                               device owner or a profile owner.
4461      */
4462     @PasswordComplexity
4463     @RequiresPermission(android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY)
getPasswordComplexity()4464     public int getPasswordComplexity() {
4465         if (mService == null) {
4466             return PASSWORD_COMPLEXITY_NONE;
4467         }
4468 
4469         try {
4470             return mService.getPasswordComplexity(mParentInstance);
4471         } catch (RemoteException e) {
4472             throw e.rethrowFromSystemServer();
4473         }
4474     }
4475 
4476     /**
4477      * Sets a minimum password complexity requirement for the user's screen lock.
4478      * The complexity level is one of the pre-defined levels, and the user is unable to set a
4479      * password with a lower complexity level.
4480      *
4481      * <p>Note that when called on a profile which uses an unified challenge with its parent, the
4482      * complexity would apply to the unified challenge.
4483      *
4484      * <p>This method can be called on the {@link DevicePolicyManager} instance
4485      * returned by {@link #getParentProfileInstance(ComponentName)} in order to set
4486      * restrictions on the parent profile.
4487      *
4488      * <p><strong>Note:</strong> Specifying password requirements using this method clears any
4489      * password requirements set using the obsolete {@link #setPasswordQuality(ComponentName, int)}
4490      * and any of its associated methods.
4491      * Additionally, if there are password requirements set using the obsolete
4492      * {@link #setPasswordQuality(ComponentName, int)} on the parent {@code DevicePolicyManager}
4493      * instance, they must be cleared by calling {@link #setPasswordQuality(ComponentName, int)}
4494      * with {@link #PASSWORD_QUALITY_UNSPECIFIED} on that instance prior to setting complexity
4495      * requirement for the managed profile.
4496      *
4497      * @throws SecurityException if the calling application is not a device owner or a profile
4498      * owner.
4499      * @throws IllegalArgumentException if the complexity level is not one of the four above.
4500      * @throws IllegalStateException if the caller is trying to set password complexity while there
4501      * are password requirements specified using {@link #setPasswordQuality(ComponentName, int)}
4502      * on the parent {@code DevicePolicyManager} instance.
4503      */
setRequiredPasswordComplexity(@asswordComplexity int passwordComplexity)4504     public void setRequiredPasswordComplexity(@PasswordComplexity int passwordComplexity) {
4505         if (mService == null) {
4506             return;
4507         }
4508 
4509         try {
4510             mService.setRequiredPasswordComplexity(passwordComplexity, mParentInstance);
4511         } catch (RemoteException e) {
4512             throw e.rethrowFromSystemServer();
4513         }
4514     }
4515 
4516 
4517     /**
4518      * Gets the password complexity requirement set by {@link #setRequiredPasswordComplexity(int)},
4519      * for the current user.
4520      *
4521      * <p>The difference between this method and {@link #getPasswordComplexity()} is that this
4522      * method simply returns the value set by {@link #setRequiredPasswordComplexity(int)} while
4523      * {@link #getPasswordComplexity()} returns the complexity of the actual password.
4524      *
4525      * <p>This method can be called on the {@link DevicePolicyManager} instance
4526      * returned by {@link #getParentProfileInstance(ComponentName)} in order to get
4527      * restrictions on the parent profile.
4528      *
4529      * @throws SecurityException if the calling application is not a device owner or a profile
4530      * owner.
4531      */
4532     @PasswordComplexity
getRequiredPasswordComplexity()4533     public int getRequiredPasswordComplexity() {
4534         if (mService == null) {
4535             return PASSWORD_COMPLEXITY_NONE;
4536         }
4537 
4538         try {
4539             return mService.getRequiredPasswordComplexity(mParentInstance);
4540         } catch (RemoteException e) {
4541             throw e.rethrowFromSystemServer();
4542         }
4543     }
4544 
4545     /**
4546      * Returns the password complexity that applies to this user, aggregated from other users if
4547      * necessary (for example, if the DPC has set password complexity requirements on the parent
4548      * profile DPM instance of a managed profile user, they would apply to the primary user on the
4549      * device).
4550      * @hide
4551      */
4552     @PasswordComplexity
getAggregatedPasswordComplexityForUser(int userId)4553     public int getAggregatedPasswordComplexityForUser(int userId) {
4554         return getAggregatedPasswordComplexityForUser(userId, false);
4555     }
4556 
4557     /**
4558      * Returns the password complexity that applies to this user, aggregated from other users if
4559      * necessary (for example, if the DPC has set password complexity requirements on the parent
4560      * profile DPM instance of a managed profile user, they would apply to the primary user on the
4561      * device). If {@code deviceWideOnly} is {@code true}, ignore policies set on the
4562      * managed profile DPM instance (as if the managed profile had separate work challenge).
4563      * @hide
4564      */
4565     @PasswordComplexity
getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly)4566     public int getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly) {
4567         if (mService == null) {
4568             return PASSWORD_COMPLEXITY_NONE;
4569         }
4570 
4571         try {
4572             return mService.getAggregatedPasswordComplexityForUser(userId, deviceWideOnly);
4573         } catch (RemoteException e) {
4574             throw e.rethrowFromSystemServer();
4575         }
4576     }
4577 
4578 
4579     /**
4580      * When called by a profile owner of a managed profile returns true if the profile uses unified
4581      * challenge with its parent user.
4582      *
4583      * <strong>Note</strong>: This method is not concerned with password quality and will return
4584      * false if the profile has empty password as a separate challenge.
4585      *
4586      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4587      * @throws SecurityException if {@code admin} is not a profile owner of a managed profile.
4588      * @see UserManager#DISALLOW_UNIFIED_PASSWORD
4589      */
isUsingUnifiedPassword(@onNull ComponentName admin)4590     public boolean isUsingUnifiedPassword(@NonNull ComponentName admin) {
4591         throwIfParentInstance("isUsingUnifiedPassword");
4592         if (mService != null) {
4593             try {
4594                 return mService.isUsingUnifiedPassword(admin);
4595             } catch (RemoteException e) {
4596                 throw e.rethrowFromSystemServer();
4597             }
4598         }
4599         return true;
4600     }
4601 
4602     /**
4603      * Returns whether the given user's credential will be sufficient for all password policy
4604      * requirement, once the user's profile has switched to unified challenge.
4605      *
4606      * <p>This is different from {@link #isActivePasswordSufficient()} since once the profile
4607      * switches to unified challenge, policies set explicitly on the profile will start to affect
4608      * the parent user.
4609      * @param userHandle the user whose password requirement will be checked
4610      * @param profileUser the profile user whose lockscreen challenge will be unified.
4611      * @hide
4612      */
isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser)4613     public boolean isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser) {
4614         if (mService != null) {
4615             try {
4616                 return mService.isPasswordSufficientAfterProfileUnification(userHandle,
4617                         profileUser);
4618             } catch (RemoteException e) {
4619                 throw e.rethrowFromSystemServer();
4620             }
4621         }
4622         return false;
4623     }
4624     /**
4625      * Retrieve the number of times the user has failed at entering a password since that last
4626      * successful password entry.
4627      * <p>
4628      * This method can be called on the {@link DevicePolicyManager} instance returned by
4629      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the number of failed
4630      * password attemts for the parent user.
4631      * <p>
4632      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
4633      * to be able to call this method; if it has not, a security exception will be thrown.
4634      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4635      * password is always empty and this method always returns 0.
4636      *
4637      * @return The number of times user has entered an incorrect password since the last correct
4638      *         password entry.
4639      * @throws SecurityException if the calling application does not own an active administrator
4640      *             that uses {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
4641      */
4642     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getCurrentFailedPasswordAttempts()4643     public int getCurrentFailedPasswordAttempts() {
4644         return getCurrentFailedPasswordAttempts(myUserId());
4645     }
4646 
4647     /**
4648      * Retrieve the number of times the given user has failed at entering a
4649      * password since that last successful password entry.
4650      *
4651      * <p>The calling device admin must have requested
4652      * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call this method; if it has
4653      * not and it is not the system uid, a security exception will be thrown.
4654      *
4655      * @hide
4656      */
4657     @UnsupportedAppUsage
getCurrentFailedPasswordAttempts(int userHandle)4658     public int getCurrentFailedPasswordAttempts(int userHandle) {
4659         if (mService != null) {
4660             try {
4661                 return mService.getCurrentFailedPasswordAttempts(userHandle, mParentInstance);
4662             } catch (RemoteException e) {
4663                 throw e.rethrowFromSystemServer();
4664             }
4665         }
4666         return -1;
4667     }
4668 
4669     /**
4670      * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set.
4671      *
4672      * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set.
4673      * @hide
4674      */
getDoNotAskCredentialsOnBoot()4675     public boolean getDoNotAskCredentialsOnBoot() {
4676         if (mService != null) {
4677             try {
4678                 return mService.getDoNotAskCredentialsOnBoot();
4679             } catch (RemoteException e) {
4680                 throw e.rethrowFromSystemServer();
4681             }
4682         }
4683         return false;
4684     }
4685 
4686     /**
4687      * Setting this to a value greater than zero enables a built-in policy that will perform a
4688      * device or profile wipe after too many incorrect device-unlock passwords have been entered.
4689      * This built-in policy combines watching for failed passwords and wiping the device, and
4690      * requires that you request both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
4691      * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
4692      * <p>
4693      * When this policy is set by a device owner, profile owner of an organization-owned device or
4694      * an admin on the primary user, the device will be factory reset after too many incorrect
4695      * password attempts. When set by a profile owner or an admin on a secondary user or a managed
4696      * profile, only the corresponding user or profile will be wiped.
4697      * <p>
4698      * To implement any other policy (e.g. wiping data for a particular application only, erasing or
4699      * revoking credentials, or reporting the failure to a server), you should implement
4700      * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)} instead. Do not
4701      * use this API, because if the maximum count is reached, the device or profile will be wiped
4702      * immediately, and your callback will not be invoked.
4703      * <p>
4704      * This method can be called on the {@link DevicePolicyManager} instance returned by
4705      * {@link #getParentProfileInstance(ComponentName)} in order to set a value on the parent
4706      * profile.
4707      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4708      * password is always empty and this method has no effect - i.e. the policy is not set.
4709      *
4710      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4711      * @param num The number of failed password attempts at which point the device or profile will
4712      *            be wiped.
4713      * @throws SecurityException if {@code admin} is not an active administrator or does not use
4714      *             both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
4715      *             {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}.
4716      */
4717     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setMaximumFailedPasswordsForWipe(@onNull ComponentName admin, int num)4718     public void setMaximumFailedPasswordsForWipe(@NonNull ComponentName admin, int num) {
4719         if (mService != null) {
4720             try {
4721                 mService.setMaximumFailedPasswordsForWipe(admin, num, mParentInstance);
4722             } catch (RemoteException e) {
4723                 throw e.rethrowFromSystemServer();
4724             }
4725         }
4726     }
4727 
4728     /**
4729      * Retrieve the current maximum number of login attempts that are allowed before the device
4730      * or profile is wiped, for a particular admin or all admins that set restrictions on this user
4731      * and its participating profiles. Restrictions on profiles that have a separate challenge are
4732      * not taken into account.
4733      *
4734      * <p>This method can be called on the {@link DevicePolicyManager} instance
4735      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4736      * the value for the parent profile.
4737      *
4738      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4739      * password is always empty and this method returns a default value (0) indicating that the
4740      * policy is not set.
4741      *
4742      * @param admin The name of the admin component to check, or {@code null} to aggregate
4743      * all admins.
4744      */
4745     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin)4746     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) {
4747         return getMaximumFailedPasswordsForWipe(admin, myUserId());
4748     }
4749 
4750     /** @hide per-user version */
4751     @UnsupportedAppUsage
4752     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin, int userHandle)4753     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) {
4754         if (mService != null) {
4755             try {
4756                 return mService.getMaximumFailedPasswordsForWipe(
4757                         admin, userHandle, mParentInstance);
4758             } catch (RemoteException e) {
4759                 throw e.rethrowFromSystemServer();
4760             }
4761         }
4762         return 0;
4763     }
4764 
4765     /**
4766      * Returns the user that will be wiped first when too many failed attempts are made to unlock
4767      * user {@code userHandle}. That user is either the same as {@code userHandle} or belongs to the
4768      * same profile group. When there is no such policy, returns {@code UserHandle.USER_NULL}.
4769      * E.g. managed profile user may be wiped as a result of failed primary profile password
4770      * attempts when using unified challenge. Primary user may be wiped as a result of failed
4771      * password attempts on the managed profile on an organization-owned device.
4772      * @hide Used only by Keyguard
4773      */
4774     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getProfileWithMinimumFailedPasswordsForWipe(int userHandle)4775     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
4776         if (mService != null) {
4777             try {
4778                 return mService.getProfileWithMinimumFailedPasswordsForWipe(
4779                         userHandle, mParentInstance);
4780             } catch (RemoteException e) {
4781                 throw e.rethrowFromSystemServer();
4782             }
4783         }
4784         return UserHandle.USER_NULL;
4785     }
4786 
4787     /**
4788      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't allow other admins
4789      * to change the password again until the user has entered it.
4790      */
4791     public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
4792 
4793     /**
4794      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't ask for user
4795      * credentials on device boot.
4796      * If the flag is set, the device can be booted without asking for user password.
4797      * The absence of this flag does not change the current boot requirements. This flag
4798      * can be set by the device owner only. If the app is not the device owner, the flag
4799      * is ignored. Once the flag is set, it cannot be reverted back without resetting the
4800      * device to factory defaults.
4801      */
4802     public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
4803 
4804     /**
4805      * Force a new password for device unlock (the password needed to access the entire device) or
4806      * the work profile challenge on the current user. This takes effect immediately.
4807      *
4808      * <p> Before {@link android.os.Build.VERSION_CODES#N}, this API is available to device admin,
4809      * profile owner and device owner. Starting from {@link android.os.Build.VERSION_CODES#N},
4810      * legacy device admin (who is not also profile owner or device owner) can only call this
4811      * API to set a new password if there is currently no password set. Profile owner and device
4812      * owner can continue to force change an existing password as long as the target user is
4813      * unlocked, although device owner will not be able to call this API at all if there is also a
4814      * managed profile on the device.
4815      *
4816      * <p> Between {@link android.os.Build.VERSION_CODES#O},
4817      * {@link android.os.Build.VERSION_CODES#P} and {@link android.os.Build.VERSION_CODES#Q},
4818      * profile owner and devices owner targeting SDK level {@link android.os.Build.VERSION_CODES#O}
4819      * or above who attempt to call this API will receive {@link SecurityException}; they are
4820      * encouraged to migrate to the new {@link #resetPasswordWithToken} API instead.
4821      * Profile owner and device owner targeting older SDK levels are not affected: they continue
4822      * to experience the existing behaviour described in the previous paragraph.
4823      *
4824      * <p><em>Starting from {@link android.os.Build.VERSION_CODES#R}, this API is no longer
4825      * supported in most cases.</em> Device owner and profile owner calling
4826      * this API will receive {@link SecurityException} if they target SDK level
4827      * {@link android.os.Build.VERSION_CODES#O} or above, or they will receive a silent failure
4828      * (API returning {@code false}) if they target lower SDK level.
4829      * For legacy device admins, this API throws {@link SecurityException} if they target SDK level
4830      * {@link android.os.Build.VERSION_CODES#N} or above, and returns {@code false} otherwise. Only
4831      * privileged apps holding RESET_PASSWORD permission which are part of
4832      * the system factory image can still call this API to set a new password if there is currently
4833      * no password set. In this case, if the device already has a password, this API will throw
4834      * {@link SecurityException}.
4835      *
4836      * <p>
4837      * The given password must be sufficient for the current password quality and length constraints
4838      * as returned by {@link #getPasswordQuality(ComponentName)} and
4839      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
4840      * it will be rejected and false returned. Note that the password may be a stronger quality
4841      * (containing alphanumeric characters when the requested quality is only numeric), in which
4842      * case the currently active quality will be increased to match.
4843      *
4844      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
4845      * methods does nothing.
4846      * <p>
4847      * The calling device admin must have requested
4848      * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call this method; if it has
4849      * not, a security exception will be thrown.
4850      *
4851      * @param password The new password for the user. Null or empty clears the password.
4852      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
4853      *            {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
4854      * @return Returns true if the password was applied, or false if it is not acceptable for the
4855      *         current constraints.
4856      * @throws SecurityException if the calling application does not own an active administrator
4857      *             that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
4858      * @throws IllegalStateException if the calling user is locked or has a managed profile.
4859      * @deprecated Please use {@link #resetPasswordWithToken} instead.
4860      */
4861     @Deprecated
4862     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
resetPassword(String password, int flags)4863     public boolean resetPassword(String password, int flags) {
4864         throwIfParentInstance("resetPassword");
4865         if (mService != null) {
4866             try {
4867                 return mService.resetPassword(password, flags);
4868             } catch (RemoteException e) {
4869                 throw e.rethrowFromSystemServer();
4870             }
4871         }
4872         return false;
4873     }
4874 
4875     /**
4876      * Called by a profile or device owner to provision a token which can later be used to reset the
4877      * device lockscreen password (if called by device owner), or managed profile challenge (if
4878      * called by profile owner), via {@link #resetPasswordWithToken}.
4879      * <p>
4880      * If the user currently has a lockscreen password, the provisioned token will not be
4881      * immediately usable; it only becomes active after the user performs a confirm credential
4882      * operation, which can be triggered by {@link KeyguardManager#createConfirmDeviceCredentialIntent}.
4883      * If the user has no lockscreen password, the token is activated immediately. In all cases,
4884      * the active state of the current token can be checked by {@link #isResetPasswordTokenActive}.
4885      * For security reasons, un-activated tokens are only stored in memory and will be lost once
4886      * the device reboots. In this case a new token needs to be provisioned again.
4887      * <p>
4888      * Once provisioned and activated, the token will remain effective even if the user changes
4889      * or clears the lockscreen password.
4890      * <p>
4891      * <em>This token is highly sensitive and should be treated at the same level as user
4892      * credentials. In particular, NEVER store this token on device in plaintext. Do not store
4893      * the plaintext token in device-encrypted storage if it will be needed to reset password on
4894      * file-based encryption devices before user unlocks. Consider carefully how any password token
4895      * will be stored on your server and who will need access to them. Tokens may be the subject of
4896      * legal access requests.
4897      * </em>
4898      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4899      * reset token is not set and this method returns false.
4900      *
4901      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4902      * @param token a secure token a least 32-byte long, which must be generated by a
4903      *        cryptographically strong random number generator.
4904      * @return true if the operation is successful, false otherwise.
4905      * @throws SecurityException if admin is not a device or profile owner.
4906      * @throws IllegalArgumentException if the supplied token is invalid.
4907      */
4908     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setResetPasswordToken(ComponentName admin, byte[] token)4909     public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
4910         throwIfParentInstance("setResetPasswordToken");
4911         if (mService != null) {
4912             try {
4913                 return mService.setResetPasswordToken(admin, token);
4914             } catch (RemoteException e) {
4915                 throw e.rethrowFromSystemServer();
4916             }
4917         }
4918         return false;
4919     }
4920 
4921     /**
4922      * Called by a profile or device owner to revoke the current password reset token.
4923      *
4924      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
4925      * method has no effect - the reset token should not have been set in the first place - and
4926      * false is returned.
4927      *
4928      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4929      * @return true if the operation is successful, false otherwise.
4930      * @throws SecurityException if admin is not a device or profile owner.
4931      */
4932     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
clearResetPasswordToken(ComponentName admin)4933     public boolean clearResetPasswordToken(ComponentName admin) {
4934         throwIfParentInstance("clearResetPasswordToken");
4935         if (mService != null) {
4936             try {
4937                 return mService.clearResetPasswordToken(admin);
4938             } catch (RemoteException e) {
4939                 throw e.rethrowFromSystemServer();
4940             }
4941         }
4942         return false;
4943     }
4944 
4945     /**
4946      * Called by a profile or device owner to check if the current reset password token is active.
4947      *
4948      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
4949      * false is always returned.
4950      *
4951      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4952      * @return true if the token is active, false otherwise.
4953      * @throws SecurityException if admin is not a device or profile owner.
4954      * @throws IllegalStateException if no token has been set.
4955      */
4956     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
isResetPasswordTokenActive(ComponentName admin)4957     public boolean isResetPasswordTokenActive(ComponentName admin) {
4958         throwIfParentInstance("isResetPasswordTokenActive");
4959         if (mService != null) {
4960             try {
4961                 return mService.isResetPasswordTokenActive(admin);
4962             } catch (RemoteException e) {
4963                 throw e.rethrowFromSystemServer();
4964             }
4965         }
4966         return false;
4967     }
4968 
4969     /**
4970      * Called by device or profile owner to force set a new device unlock password or a managed
4971      * profile challenge on current user. This takes effect immediately.
4972      * <p>
4973      * Unlike {@link #resetPassword}, this API can change the password even before the user or
4974      * device is unlocked or decrypted. The supplied token must have been previously provisioned via
4975      * {@link #setResetPasswordToken}, and in active state {@link #isResetPasswordTokenActive}.
4976      * <p>
4977      * The given password must be sufficient for the current password quality and length constraints
4978      * as returned by {@link #getPasswordQuality(ComponentName)} and
4979      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
4980      * it will be rejected and false returned. Note that the password may be a stronger quality, for
4981      * example, a password containing alphanumeric characters when the requested quality is only
4982      * numeric.
4983      * <p>
4984      * Calling with a {@code null} or empty password will clear any existing PIN, pattern or
4985      * password if the current password constraints allow it.
4986      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
4987      * calling this methods has no effect - the password is always empty - and false is returned.
4988      *
4989      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4990      * @param password The new password for the user. {@code null} or empty clears the password.
4991      * @param token the password reset token previously provisioned by
4992      *        {@link #setResetPasswordToken}.
4993      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
4994      *        {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
4995      * @return Returns true if the password was applied, or false if it is not acceptable for the
4996      *         current constraints.
4997      * @throws SecurityException if admin is not a device or profile owner.
4998      * @throws IllegalStateException if the provided token is not valid.
4999      */
5000     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
resetPasswordWithToken(@onNull ComponentName admin, String password, byte[] token, int flags)5001     public boolean resetPasswordWithToken(@NonNull ComponentName admin, String password,
5002             byte[] token, int flags) {
5003         throwIfParentInstance("resetPassword");
5004         if (mService != null) {
5005             try {
5006                 return mService.resetPasswordWithToken(admin, password, token, flags);
5007             } catch (RemoteException e) {
5008                 throw e.rethrowFromSystemServer();
5009             }
5010         }
5011         return false;
5012     }
5013 
5014     /**
5015      * Called by an application that is administering the device to set the maximum time for user
5016      * activity until the device will lock. This limits the length that the user can set. It takes
5017      * effect immediately.
5018      * <p>
5019      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
5020      * to be able to call this method; if it has not, a security exception will be thrown.
5021      * <p>
5022      * This method can be called on the {@link DevicePolicyManager} instance returned by
5023      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5024      * profile.
5025      *
5026      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5027      * @param timeMs The new desired maximum time to lock in milliseconds. A value of 0 means there
5028      *            is no restriction.
5029      * @throws SecurityException if {@code admin} is not an active administrator or it does not use
5030      *             {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
5031      */
setMaximumTimeToLock(@onNull ComponentName admin, long timeMs)5032     public void setMaximumTimeToLock(@NonNull ComponentName admin, long timeMs) {
5033         if (mService != null) {
5034             try {
5035                 mService.setMaximumTimeToLock(admin, timeMs, mParentInstance);
5036             } catch (RemoteException e) {
5037                 throw e.rethrowFromSystemServer();
5038             }
5039         }
5040     }
5041 
5042     /**
5043      * Retrieve the current maximum time to unlock for a particular admin or all admins that set
5044      * restrictions on this user and its participating profiles. Restrictions on profiles that have
5045      * a separate challenge are not taken into account.
5046      *
5047      * <p>This method can be called on the {@link DevicePolicyManager} instance
5048      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5049      * restrictions on the parent profile.
5050      *
5051      * @param admin The name of the admin component to check, or {@code null} to aggregate
5052      * all admins.
5053      * @return time in milliseconds for the given admin or the minimum value (strictest) of
5054      * all admins if admin is null. Returns 0 if there are no restrictions.
5055      */
getMaximumTimeToLock(@ullable ComponentName admin)5056     public long getMaximumTimeToLock(@Nullable ComponentName admin) {
5057         return getMaximumTimeToLock(admin, myUserId());
5058     }
5059 
5060     /** @hide per-user version */
5061     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getMaximumTimeToLock(@ullable ComponentName admin, int userHandle)5062     public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) {
5063         if (mService != null) {
5064             try {
5065                 return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance);
5066             } catch (RemoteException e) {
5067                 throw e.rethrowFromSystemServer();
5068             }
5069         }
5070         return 0;
5071     }
5072 
5073     /**
5074      * Called by a device/profile owner to set the timeout after which unlocking with secondary, non
5075      * strong auth (e.g. fingerprint, face, trust agents) times out, i.e. the user has to use a
5076      * strong authentication method like password, pin or pattern.
5077      *
5078      * <p>This timeout is used internally to reset the timer to require strong auth again after
5079      * specified timeout each time it has been successfully used.
5080      *
5081      * <p>Fingerprint can also be disabled altogether using {@link #KEYGUARD_DISABLE_FINGERPRINT}.
5082      *
5083      * <p>Trust agents can also be disabled altogether using {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
5084      *
5085      * <p>The calling device admin must be a device or profile owner. If it is not,
5086      * a {@link SecurityException} will be thrown.
5087      *
5088      * <p>The calling device admin can verify the value it has set by calling
5089      * {@link #getRequiredStrongAuthTimeout(ComponentName)} and passing in its instance.
5090      *
5091      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
5092      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5093      * profile.
5094      *
5095      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
5096      * calling this methods has no effect - i.e. the timeout is not set.
5097      *
5098      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5099      * @param timeoutMs The new timeout in milliseconds, after which the user will have to unlock
5100      *         with strong authentication method. A value of 0 means the admin is not participating
5101      *         in controlling the timeout.
5102      *         The minimum and maximum timeouts are platform-defined and are typically 1 hour and
5103      *         72 hours, respectively. Though discouraged, the admin may choose to require strong
5104      *         auth at all times using {@link #KEYGUARD_DISABLE_FINGERPRINT} and/or
5105      *         {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
5106      *
5107      * @throws SecurityException if {@code admin} is not a device or profile owner.
5108      */
5109     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setRequiredStrongAuthTimeout(@onNull ComponentName admin, long timeoutMs)5110     public void setRequiredStrongAuthTimeout(@NonNull ComponentName admin,
5111             long timeoutMs) {
5112         if (mService != null) {
5113             try {
5114                 mService.setRequiredStrongAuthTimeout(admin, timeoutMs, mParentInstance);
5115             } catch (RemoteException e) {
5116                 throw e.rethrowFromSystemServer();
5117             }
5118         }
5119     }
5120 
5121     /**
5122      * Determine for how long the user will be able to use secondary, non strong auth for
5123      * authentication, since last strong method authentication (password, pin or pattern) was used.
5124      * After the returned timeout the user is required to use strong authentication method.
5125      *
5126      * <p>This method can be called on the {@link DevicePolicyManager} instance
5127      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5128      * restrictions on the parent profile.
5129      *
5130      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
5131      * 0 is returned to indicate that no timeout is configured.
5132      *
5133      * @param admin The name of the admin component to check, or {@code null} to aggregate
5134      *         across all participating admins.
5135      * @return The timeout in milliseconds or 0 if not configured for the provided admin.
5136      */
5137     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getRequiredStrongAuthTimeout(@ullable ComponentName admin)5138     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin) {
5139         return getRequiredStrongAuthTimeout(admin, myUserId());
5140     }
5141 
5142     /** @hide per-user version */
5143     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5144     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getRequiredStrongAuthTimeout(@ullable ComponentName admin, @UserIdInt int userId)5145     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin, @UserIdInt int userId) {
5146         if (mService != null) {
5147             try {
5148                 return mService.getRequiredStrongAuthTimeout(admin, userId, mParentInstance);
5149             } catch (RemoteException e) {
5150                 throw e.rethrowFromSystemServer();
5151             }
5152         }
5153         return DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5154     }
5155 
5156     /**
5157      * Flag for {@link #lockNow(int)}: also evict the user's credential encryption key from the
5158      * keyring. The user's credential will need to be entered again in order to derive the
5159      * credential encryption key that will be stored back in the keyring for future use.
5160      * <p>
5161      * This flag can only be used by a profile owner when locking a managed profile when
5162      * {@link #getStorageEncryptionStatus} returns {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
5163      * <p>
5164      * In order to secure user data, the user will be stopped and restarted so apps should wait
5165      * until they are next run to perform further actions.
5166      */
5167     public static final int FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY = 1;
5168 
5169     /** @hide */
5170     @Retention(RetentionPolicy.SOURCE)
5171     @IntDef(flag = true, prefix = { "FLAG_EVICT_" }, value = {
5172             FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY
5173     })
5174     public @interface LockNowFlag {}
5175 
5176     /**
5177      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
5178      * this call.
5179      * <p>
5180      * This method secures the device in response to an urgent situation, such as a lost or stolen
5181      * device. After this method is called, the device must be unlocked using strong authentication
5182      * (PIN, pattern, or password). This API is intended for use only by device admins.
5183      * <p>
5184      * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have
5185      * the LOCK_DEVICE permission or the device must have the device admin feature; if neither is
5186      * true, then the method will return without completing any action. Before version
5187      * {@link android.os.Build.VERSION_CODES#R}, the device needed the device admin feature,
5188      * regardless of the caller's permissions.
5189      * <p>
5190      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
5191      * to be able to call this method; if it has not, a security exception will be thrown.
5192      * <p>
5193      * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
5194      * the device. Device admins who find the device in this state can lock an otherwise-insecure
5195      * device by first calling {@link #resetPassword} to set the password and then lock the device.
5196      * <p>
5197      * This method can be called on the {@link DevicePolicyManager} instance returned by
5198      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
5199      * <p>
5200      * NOTE: on {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, this
5201      * method doesn't turn off the screen as it would be a driving safety distraction.
5202      * <p>
5203      * Equivalent to calling {@link #lockNow(int)} with no flags.
5204      *
5205      * @throws SecurityException if the calling application does not own an active administrator
5206      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
5207      */
lockNow()5208     public void lockNow() {
5209         lockNow(0);
5210     }
5211 
5212     /**
5213      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
5214      * this call.
5215      * <p>
5216      * This method secures the device in response to an urgent situation, such as a lost or stolen
5217      * device. After this method is called, the device must be unlocked using strong authentication
5218      * (PIN, pattern, or password). This API is intended for use only by device admins.
5219      * <p>
5220      * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have
5221      * the LOCK_DEVICE permission or the device must have the device admin feature; if neither is
5222      * true, then the method will return without completing any action. Before version
5223      * {@link android.os.Build.VERSION_CODES#R}, the device needed the device admin feature,
5224      * regardless of the caller's permissions.
5225      * <p>
5226      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
5227      * to be able to call this method; if it has not, a security exception will be thrown.
5228      * <p>
5229      * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
5230      * the device. Device admins who find the device in this state can lock an otherwise-insecure
5231      * device by first calling {@link #resetPassword} to set the password and then lock the device.
5232      * <p>
5233      * This method can be called on the {@link DevicePolicyManager} instance returned by
5234      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile as
5235      * well as the managed profile.
5236      * <p>
5237      * NOTE: In order to lock the parent profile and evict the encryption key of the managed
5238      * profile, {@link #lockNow()} must be called twice: First, {@link #lockNow()} should be called
5239      * on the {@link DevicePolicyManager} instance returned by
5240      * {@link #getParentProfileInstance(ComponentName)}, then {@link #lockNow(int)} should be
5241      * called on the {@link DevicePolicyManager} instance associated with the managed profile,
5242      * with the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag.
5243      * Calling the method twice in this order ensures that all users are locked and does not
5244      * stop the device admin on the managed profile from issuing a second call to lock its own
5245      * profile.
5246      * <p>
5247      * NOTE: on {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, this
5248      * method doesn't turn off the screen as it would be a driving safety distraction.
5249      *
5250      * @param flags May be 0 or {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}.
5251      * @throws SecurityException if the calling application does not own an active administrator
5252      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} or the
5253      *             {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is passed by an application
5254      *             that is not a profile
5255      *             owner of a managed profile.
5256      * @throws IllegalArgumentException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is
5257      *             passed when locking the parent profile.
5258      * @throws UnsupportedOperationException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}
5259      *             flag is passed when {@link #getStorageEncryptionStatus} does not return
5260      *             {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
5261      */
lockNow(@ockNowFlag int flags)5262     public void lockNow(@LockNowFlag int flags) {
5263         if (mService != null) {
5264             try {
5265                 mService.lockNow(flags, mParentInstance);
5266             } catch (RemoteException e) {
5267                 throw e.rethrowFromSystemServer();
5268             }
5269         }
5270     }
5271 
5272     /**
5273      * Flag for {@link #wipeData(int)}: also erase the device's external
5274      * storage (such as SD cards).
5275      */
5276     public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
5277 
5278     /**
5279      * Flag for {@link #wipeData(int)}: also erase the factory reset protection
5280      * data.
5281      *
5282      * <p>This flag may only be set by device owner admins; if it is set by
5283      * other admins a {@link SecurityException} will be thrown.
5284      */
5285     public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
5286 
5287     /**
5288      * Flag for {@link #wipeData(int)}: also erase the device's eUICC data.
5289      */
5290     public static final int WIPE_EUICC = 0x0004;
5291 
5292     /**
5293      * Flag for {@link #wipeData(int)}: won't show reason for wiping to the user.
5294      */
5295     public static final int WIPE_SILENTLY = 0x0008;
5296 
5297     /**
5298      * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
5299      * other users will remain unaffected. Calling from the primary user will cause the device to
5300      * reboot, erasing all device data - including all the secondary users and their data - while
5301      * booting up.
5302      * <p>
5303      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
5304      * be able to call this method; if it has not, a security exception will be thrown.
5305      *
5306      * If the caller is a profile owner of an organization-owned managed profile, it may
5307      * additionally call this method on the parent instance.
5308      * Calling this method on the parent {@link DevicePolicyManager} instance would wipe the
5309      * entire device, while calling it on the current profile instance would relinquish the device
5310      * for personal use, removing the managed profile and all policies set by the profile owner.
5311      *
5312      * @param flags Bit mask of additional options: currently supported flags are
5313      *            {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA},
5314      *            {@link #WIPE_EUICC} and {@link #WIPE_SILENTLY}.
5315      * @throws SecurityException if the calling application does not own an active administrator
5316      *            that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} or is not granted the
5317      *            {@link android.Manifest.permission#MASTER_CLEAR} permission.
5318      */
wipeData(int flags)5319     public void wipeData(int flags) {
5320         wipeDataInternal(flags, "");
5321     }
5322 
5323     /**
5324      * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
5325      * other users will remain unaffected, the provided reason for wiping data can be shown to
5326      * user. Calling from the primary user will cause the device to reboot, erasing all device data
5327      * - including all the secondary users and their data - while booting up. In this case, we don't
5328      * show the reason to the user since the device would be factory reset.
5329      * <p>
5330      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
5331      * be able to call this method; if it has not, a security exception will be thrown.
5332      *
5333      * If the caller is a profile owner of an organization-owned managed profile, it may
5334      * additionally call this method on the parent instance.
5335      * Calling this method on the parent {@link DevicePolicyManager} instance would wipe the
5336      * entire device, while calling it on the current profile instance would relinquish the device
5337      * for personal use, removing the managed profile and all policies set by the profile owner.
5338      *
5339      * @param flags Bit mask of additional options: currently supported flags are
5340      *            {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA} and
5341      *            {@link #WIPE_EUICC}.
5342      * @param reason a string that contains the reason for wiping data, which can be
5343      *            presented to the user.
5344      * @throws SecurityException if the calling application does not own an active administrator
5345      *            that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} or is not granted the
5346      *            {@link android.Manifest.permission#MASTER_CLEAR} permission.
5347      * @throws IllegalArgumentException if the input reason string is null or empty, or if
5348      *            {@link #WIPE_SILENTLY} is set.
5349      */
wipeData(int flags, @NonNull CharSequence reason)5350     public void wipeData(int flags, @NonNull CharSequence reason) {
5351         Objects.requireNonNull(reason, "reason string is null");
5352         Preconditions.checkStringNotEmpty(reason, "reason string is empty");
5353         Preconditions.checkArgument((flags & WIPE_SILENTLY) == 0, "WIPE_SILENTLY cannot be set");
5354         wipeDataInternal(flags, reason.toString());
5355     }
5356 
5357     /**
5358      * Internal function for both {@link #wipeData(int)} and
5359      * {@link #wipeData(int, CharSequence)} to call.
5360      *
5361      * @see #wipeData(int)
5362      * @see #wipeData(int, CharSequence)
5363      * @hide
5364      */
wipeDataInternal(int flags, @NonNull String wipeReasonForUser)5365     private void wipeDataInternal(int flags, @NonNull String wipeReasonForUser) {
5366         if (mService != null) {
5367             try {
5368                 mService.wipeDataWithReason(flags, wipeReasonForUser, mParentInstance);
5369             } catch (RemoteException e) {
5370                 throw e.rethrowFromSystemServer();
5371             }
5372         }
5373     }
5374 
5375     /**
5376      * Callable by device owner or profile owner of an organization-owned device, to set a
5377      * factory reset protection (FRP) policy. When a new policy is set, the system
5378      * notifies the FRP management agent of a policy change by broadcasting
5379      * {@code ACTION_RESET_PROTECTION_POLICY_CHANGED}.
5380      *
5381      * @param admin  Which {@link DeviceAdminReceiver} this request is associated with.
5382      * @param policy the new FRP policy, or {@code null} to clear the current policy.
5383      * @throws SecurityException if {@code admin} is not a device owner or a profile owner of
5384      *                           an organization-owned device.
5385      * @throws UnsupportedOperationException if factory reset protection is not
5386      *                           supported on the device.
5387      */
setFactoryResetProtectionPolicy(@onNull ComponentName admin, @Nullable FactoryResetProtectionPolicy policy)5388     public void setFactoryResetProtectionPolicy(@NonNull ComponentName admin,
5389             @Nullable FactoryResetProtectionPolicy policy) {
5390         throwIfParentInstance("setFactoryResetProtectionPolicy");
5391         if (mService != null) {
5392             try {
5393                 mService.setFactoryResetProtectionPolicy(admin, policy);
5394             } catch (RemoteException e) {
5395                 throw e.rethrowFromSystemServer();
5396             }
5397         }
5398     }
5399 
5400     /**
5401      * Callable by device owner or profile owner of an organization-owned device, to retrieve
5402      * the current factory reset protection (FRP) policy set previously by
5403      * {@link #setFactoryResetProtectionPolicy}.
5404      * <p>
5405      * This method can also be called by the FRP management agent on device or with the permission
5406      * {@link android.Manifest.permission#MASTER_CLEAR}, in which case, it can pass {@code null}
5407      * as the ComponentName.
5408      *
5409      * @param admin Which {@link DeviceAdminReceiver} this request is associated with or
5410      *              {@code null} if called by the FRP management agent on device or with the
5411      *              permission {@link android.Manifest.permission#MASTER_CLEAR}.
5412      * @return The current FRP policy object or {@code null} if no policy is set.
5413      * @throws SecurityException if {@code admin} is not a device owner, a profile owner of
5414      *                           an organization-owned device or the FRP management agent.
5415      * @throws UnsupportedOperationException if factory reset protection is not
5416      *                           supported on the device.
5417      */
getFactoryResetProtectionPolicy( @ullable ComponentName admin)5418     public @Nullable FactoryResetProtectionPolicy getFactoryResetProtectionPolicy(
5419             @Nullable ComponentName admin) {
5420         throwIfParentInstance("getFactoryResetProtectionPolicy");
5421         if (mService != null) {
5422             try {
5423                 return mService.getFactoryResetProtectionPolicy(admin);
5424             } catch (RemoteException e) {
5425                 throw e.rethrowFromSystemServer();
5426             }
5427         }
5428         return null;
5429     }
5430 
5431     /**
5432      * Called by an application that is administering the device to set the
5433      * global proxy and exclusion list.
5434      * <p>
5435      * The calling device admin must have requested
5436      * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
5437      * this method; if it has not, a security exception will be thrown.
5438      * Only the first device admin can set the proxy. If a second admin attempts
5439      * to set the proxy, the {@link ComponentName} of the admin originally setting the
5440      * proxy will be returned. If successful in setting the proxy, {@code null} will
5441      * be returned.
5442      * The method can be called repeatedly by the device admin alrady setting the
5443      * proxy to update the proxy and exclusion list.
5444      *
5445      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5446      * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
5447      *            Pass Proxy.NO_PROXY to reset the proxy.
5448      * @param exclusionList a list of domains to be excluded from the global proxy.
5449      * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
5450      *            of the device admin that sets the proxy.
5451      * @hide
5452      */
5453     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setGlobalProxy(@onNull ComponentName admin, Proxy proxySpec, List<String> exclusionList )5454     public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
5455             List<String> exclusionList ) {
5456         throwIfParentInstance("setGlobalProxy");
5457         if (proxySpec == null) {
5458             throw new NullPointerException();
5459         }
5460         if (mService != null) {
5461             try {
5462                 String hostSpec;
5463                 String exclSpec;
5464                 if (proxySpec.equals(Proxy.NO_PROXY)) {
5465                     hostSpec = null;
5466                     exclSpec = null;
5467                 } else {
5468                     if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
5469                         throw new IllegalArgumentException();
5470                     }
5471                     final Pair<String, String> proxyParams =
5472                             getProxyParameters(proxySpec, exclusionList);
5473                     hostSpec = proxyParams.first;
5474                     exclSpec = proxyParams.second;
5475                 }
5476                 return mService.setGlobalProxy(admin, hostSpec, exclSpec);
5477             } catch (RemoteException e) {
5478                 throw e.rethrowFromSystemServer();
5479             }
5480         }
5481         return null;
5482     }
5483 
5484     /**
5485      * Build HTTP proxy parameters for {@link IDevicePolicyManager#setGlobalProxy}.
5486      * @throws IllegalArgumentException Invalid proxySpec
5487      * @hide
5488      */
5489     @VisibleForTesting
getProxyParameters(Proxy proxySpec, List<String> exclusionList)5490     public Pair<String, String> getProxyParameters(Proxy proxySpec, List<String> exclusionList) {
5491         InetSocketAddress sa = (InetSocketAddress) proxySpec.address();
5492         String hostName = sa.getHostName();
5493         int port = sa.getPort();
5494         final List<String> trimmedExclList;
5495         if (exclusionList == null) {
5496             trimmedExclList = Collections.emptyList();
5497         } else {
5498             trimmedExclList = new ArrayList<>(exclusionList.size());
5499             for (String exclDomain : exclusionList) {
5500                 trimmedExclList.add(exclDomain.trim());
5501             }
5502         }
5503         final ProxyInfo info = ProxyInfo.buildDirectProxy(hostName, port, trimmedExclList);
5504         // The hostSpec is built assuming that there is a specified port and hostname,
5505         // but ProxyInfo.isValid() accepts 0 / empty as unspecified: also reject them.
5506         if (port == 0 || TextUtils.isEmpty(hostName) || !info.isValid()) {
5507             throw new IllegalArgumentException();
5508         }
5509 
5510         return new Pair<>(hostName + ":" + port, TextUtils.join(",", trimmedExclList));
5511     }
5512 
5513     /**
5514      * Set a network-independent global HTTP proxy. This is not normally what you want for typical
5515      * HTTP proxies - they are generally network dependent. However if you're doing something
5516      * unusual like general internal filtering this may be useful. On a private network where the
5517      * proxy is not accessible, you may break HTTP using this.
5518      * <p>
5519      * This method requires the caller to be the device owner.
5520      * <p>
5521      * This proxy is only a recommendation and it is possible that some apps will ignore it.
5522      * <p>
5523      * Note: The device owner won't be able to set a global HTTP proxy if there are unaffiliated
5524      * secondary users or profiles on the device. It's recommended that affiliation ids are set for
5525      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
5526      *
5527      * @see ProxyInfo
5528      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5529      * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A
5530      *            {@code null} value will clear the global HTTP proxy.
5531      * @throws SecurityException if {@code admin} is not the device owner.
5532      */
setRecommendedGlobalProxy(@onNull ComponentName admin, @Nullable ProxyInfo proxyInfo)5533     public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
5534             proxyInfo) {
5535         throwIfParentInstance("setRecommendedGlobalProxy");
5536         if (mService != null) {
5537             try {
5538                 mService.setRecommendedGlobalProxy(admin, proxyInfo);
5539             } catch (RemoteException e) {
5540                 throw e.rethrowFromSystemServer();
5541             }
5542         }
5543     }
5544 
5545     /**
5546      * Returns the component name setting the global proxy.
5547      * @return ComponentName object of the device admin that set the global proxy, or {@code null}
5548      *         if no admin has set the proxy.
5549      * @hide
5550      */
getGlobalProxyAdmin()5551     public @Nullable ComponentName getGlobalProxyAdmin() {
5552         if (mService != null) {
5553             try {
5554                 return mService.getGlobalProxyAdmin(myUserId());
5555             } catch (RemoteException e) {
5556                 throw e.rethrowFromSystemServer();
5557             }
5558         }
5559         return null;
5560     }
5561 
5562     /**
5563      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
5564      * indicating that encryption is not supported.
5565      */
5566     public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
5567 
5568     /**
5569      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
5570      * indicating that encryption is supported, but is not currently active.
5571      */
5572     public static final int ENCRYPTION_STATUS_INACTIVE = 1;
5573 
5574     /**
5575      * Result code for {@link #getStorageEncryptionStatus}:
5576      * indicating that encryption is not currently active, but is currently
5577      * being activated.  This is only reported by devices that support
5578      * encryption of data and only when the storage is currently
5579      * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
5580      * to become encrypted will never return this value.
5581      */
5582     public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
5583 
5584     /**
5585      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
5586      * indicating that encryption is active.
5587      * <p>
5588      * Also see {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
5589      */
5590     public static final int ENCRYPTION_STATUS_ACTIVE = 3;
5591 
5592     /**
5593      * Result code for {@link #getStorageEncryptionStatus}:
5594      * indicating that encryption is active, but an encryption key has not
5595      * been set by the user.
5596      */
5597     public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
5598 
5599     /**
5600      * Result code for {@link #getStorageEncryptionStatus}:
5601      * indicating that encryption is active and the encryption key is tied to the user or profile.
5602      * <p>
5603      * This value is only returned to apps targeting API level 24 and above. For apps targeting
5604      * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the
5605      * encryption key is specific to the user or profile.
5606      */
5607     public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5;
5608 
5609     /**
5610      * Activity action: begin the process of encrypting data on the device.  This activity should
5611      * be launched after using {@link #setStorageEncryption} to request encryption be activated.
5612      * After resuming from this activity, use {@link #getStorageEncryption}
5613      * to check encryption status.  However, on some devices this activity may never return, as
5614      * it may trigger a reboot and in some cases a complete data wipe of the device.
5615      */
5616     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
5617     public static final String ACTION_START_ENCRYPTION
5618             = "android.app.action.START_ENCRYPTION";
5619 
5620     /**
5621      * Activity action: launch the DPC to check policy compliance. This intent is launched when
5622      * the user taps on the notification about personal apps suspension. When handling this intent
5623      * the DPC must check if personal apps should still be suspended and either unsuspend them or
5624      * instruct the user on how to resolve the noncompliance causing the suspension.
5625      *
5626      * @see #setPersonalAppsSuspended
5627      */
5628     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
5629     public static final String ACTION_CHECK_POLICY_COMPLIANCE =
5630             "android.app.action.CHECK_POLICY_COMPLIANCE";
5631 
5632     /**
5633      * Broadcast action: notify managed provisioning that new managed user is created.
5634      *
5635      * @hide
5636      */
5637     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5638     public static final String ACTION_MANAGED_USER_CREATED =
5639             "android.app.action.MANAGED_USER_CREATED";
5640 
5641     /**
5642      * Broadcast action: notify system that a new (Android) user was added when the device is
5643      * managed by a device owner, so receivers can show the proper disclaimer to the (human) user.
5644      *
5645      * @hide
5646      */
5647     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5648     public static final String ACTION_SHOW_NEW_USER_DISCLAIMER =
5649             "android.app.action.ACTION_SHOW_NEW_USER_DISCLAIMER";
5650 
5651     /**
5652      * Widgets are enabled in keyguard
5653      */
5654     public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
5655 
5656     /**
5657      * Disable all keyguard widgets. Has no effect starting from
5658      * {@link android.os.Build.VERSION_CODES#LOLLIPOP} since keyguard widget is only supported
5659      * on Android versions lower than 5.0.
5660      */
5661     public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
5662 
5663     /**
5664      * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
5665      */
5666     public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
5667 
5668     /**
5669      * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
5670      */
5671     public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
5672 
5673     /**
5674      * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
5675      */
5676     public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
5677 
5678     /**
5679      * Disable trust agents on secure keyguard screens (e.g. PIN/Pattern/Password).
5680      * By setting this flag alone, all trust agents are disabled. If the admin then wants to
5681      * allowlist specific features of some trust agent, {@link #setTrustAgentConfiguration} can be
5682      * used in conjuction to set trust-agent-specific configurations.
5683      */
5684     public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
5685 
5686     /**
5687      * Disable fingerprint authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
5688      */
5689     public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
5690 
5691     /**
5692      * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
5693      * This flag has no effect starting from version {@link android.os.Build.VERSION_CODES#N}
5694      */
5695     public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
5696 
5697     /**
5698      * Disable face authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
5699      */
5700     public static final int KEYGUARD_DISABLE_FACE = 1 << 7;
5701 
5702     /**
5703      * Disable iris authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
5704      */
5705     public static final int KEYGUARD_DISABLE_IRIS = 1 << 8;
5706 
5707     /**
5708      * NOTE: Please remember to update the DevicePolicyManagerTest's testKeyguardDisabledFeatures
5709      * CTS test when adding to the list above.
5710      */
5711 
5712     /**
5713      * Disable all biometric authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
5714      */
5715     public static final int KEYGUARD_DISABLE_BIOMETRICS =
5716             DevicePolicyManager.KEYGUARD_DISABLE_FACE
5717             | DevicePolicyManager.KEYGUARD_DISABLE_IRIS
5718             | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
5719 
5720     /**
5721      * Disable all current and future keyguard customizations.
5722      */
5723     public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
5724 
5725     /**
5726      * Keyguard features that when set on a non-organization-owned managed profile that doesn't
5727      * have its own challenge will affect the profile's parent user. These can also be set on the
5728      * managed profile's parent {@link DevicePolicyManager} instance to explicitly control the
5729      * parent user.
5730      *
5731      * <p>
5732      * Organization-owned managed profile supports disabling additional keyguard features on the
5733      * parent user as defined in {@link #ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY}.
5734      *
5735      * @hide
5736      */
5737     public static final int NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
5738             DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
5739             | DevicePolicyManager.KEYGUARD_DISABLE_BIOMETRICS;
5740 
5741     /**
5742      * Keyguard features that when set by the profile owner of an organization-owned managed
5743      * profile will affect the profile's parent user if set on the managed profile's parent
5744      * {@link DevicePolicyManager} instance.
5745      *
5746      * @hide
5747      */
5748     public static final int ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY =
5749             DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA
5750                     | DevicePolicyManager.KEYGUARD_DISABLE_SECURE_NOTIFICATIONS;
5751 
5752     /**
5753      * Keyguard features that when set on a normal or organization-owned managed profile, have
5754      * the potential to affect the profile's parent user.
5755      *
5756      * @hide
5757      */
5758     public static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
5759             DevicePolicyManager.NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER
5760                     | DevicePolicyManager.ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY;
5761 
5762     /**
5763      * @deprecated This method does not actually modify the storage encryption of the device.
5764      * It has never affected the encryption status of a device.
5765      *
5766      * Called by an application that is administering the device to request that the storage system
5767      * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
5768      * <p>
5769      * When multiple device administrators attempt to control device encryption, the most secure,
5770      * supported setting will always be used. If any device administrator requests device
5771      * encryption, it will be enabled; Conversely, if a device administrator attempts to disable
5772      * device encryption while another device administrator has enabled it, the call to disable will
5773      * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
5774      * <p>
5775      * This policy controls encryption of the secure (application data) storage area. Data written
5776      * to other storage areas may or may not be encrypted, and this policy does not require or
5777      * control the encryption of any other storage areas. There is one exception: If
5778      * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the
5779      * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be
5780      * written to disk within the encrypted storage area.
5781      * <p>
5782      * Important Note: On some devices, it is possible to encrypt storage without requiring the user
5783      * to create a device PIN or Password. In this case, the storage is encrypted, but the
5784      * encryption key may not be fully secured. For maximum security, the administrator should also
5785      * require (and check for) a pattern, PIN, or password.
5786      *
5787      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5788      * @param encrypt true to request encryption, false to release any previous request
5789      * @return the new total request status (for all active admins), or {@link
5790      *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user.
5791      *         Will be one of {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link
5792      *         #ENCRYPTION_STATUS_INACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value
5793      *         of the requests; use {@link #getStorageEncryptionStatus()} to query the actual device
5794      *         state.
5795      *
5796      * @throws SecurityException if {@code admin} is not an active administrator or does not use
5797      *             {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE}
5798      */
5799     @Deprecated
setStorageEncryption(@onNull ComponentName admin, boolean encrypt)5800     public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
5801         throwIfParentInstance("setStorageEncryption");
5802         if (mService != null) {
5803             try {
5804                 return mService.setStorageEncryption(admin, encrypt);
5805             } catch (RemoteException e) {
5806                 throw e.rethrowFromSystemServer();
5807             }
5808         }
5809         return ENCRYPTION_STATUS_UNSUPPORTED;
5810     }
5811 
5812     /**
5813      * @deprecated This method only returns the value set by {@link #setStorageEncryption}.
5814      * It does not actually reflect the storage encryption status.
5815      * Use {@link #getStorageEncryptionStatus} for that.
5816      *
5817      * Called by an application that is administering the device to
5818      * determine the requested setting for secure storage.
5819      *
5820      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
5821      * this will return the requested encryption setting as an aggregate of all active
5822      * administrators.
5823      * @return true if the admin(s) are requesting encryption, false if not.
5824      */
5825     @Deprecated
getStorageEncryption(@ullable ComponentName admin)5826     public boolean getStorageEncryption(@Nullable ComponentName admin) {
5827         throwIfParentInstance("getStorageEncryption");
5828         if (mService != null) {
5829             try {
5830                 return mService.getStorageEncryption(admin, myUserId());
5831             } catch (RemoteException e) {
5832                 throw e.rethrowFromSystemServer();
5833             }
5834         }
5835         return false;
5836     }
5837 
5838     /**
5839      * Called by an application that is administering the device to
5840      * determine the current encryption status of the device.
5841      * <p>
5842      * Depending on the returned status code, the caller may proceed in different
5843      * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
5844      * storage system does not support encryption.  If the
5845      * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
5846      * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
5847      * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
5848      * storage system has enabled encryption but no password is set so further action
5849      * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING},
5850      * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER},
5851      * no further action is required.
5852      *
5853      * @return current status of encryption. The value will be one of
5854      * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
5855      * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5856      * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
5857      */
getStorageEncryptionStatus()5858     public int getStorageEncryptionStatus() {
5859         throwIfParentInstance("getStorageEncryptionStatus");
5860         return getStorageEncryptionStatus(myUserId());
5861     }
5862 
5863     /** @hide per-user version */
5864     @UnsupportedAppUsage
getStorageEncryptionStatus(int userHandle)5865     public int getStorageEncryptionStatus(int userHandle) {
5866         if (mService != null) {
5867             try {
5868                 return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle);
5869             } catch (RemoteException e) {
5870                 throw e.rethrowFromSystemServer();
5871             }
5872         }
5873         return ENCRYPTION_STATUS_UNSUPPORTED;
5874     }
5875 
5876     /**
5877      * Mark a CA certificate as approved by the device user. This means that they have been notified
5878      * of the installation, were made aware of the risks, viewed the certificate and still wanted to
5879      * keep the certificate on the device.
5880      *
5881      * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to
5882      * this certificate.
5883      *
5884      * @hide
5885      */
approveCaCert(String alias, int userHandle, boolean approval)5886     public boolean approveCaCert(String alias, int userHandle, boolean approval) {
5887         if (mService != null) {
5888             try {
5889                 return mService.approveCaCert(alias, userHandle, approval);
5890             } catch (RemoteException e) {
5891                 throw e.rethrowFromSystemServer();
5892             }
5893         }
5894         return false;
5895     }
5896 
5897     /**
5898      * Check whether a CA certificate has been approved by the device user.
5899      *
5900      * @hide
5901      */
isCaCertApproved(String alias, int userHandle)5902     public boolean isCaCertApproved(String alias, int userHandle) {
5903         if (mService != null) {
5904             try {
5905                 return mService.isCaCertApproved(alias, userHandle);
5906             } catch (RemoteException e) {
5907                 throw e.rethrowFromSystemServer();
5908             }
5909         }
5910         return false;
5911     }
5912 
5913     /**
5914      * Installs the given certificate as a user CA.
5915      * <p>
5916      * Inserted user CAs aren't automatically trusted by apps in Android 7.0 (API level 24) and
5917      * higher. App developers can change the default behavior for an app by adding a
5918      * <a href="{@docRoot}training/articles/security-config.html">Security Configuration
5919      * File</a> to the app manifest file.
5920      *
5921      * The caller must be a profile or device owner on that user, or a delegate package given the
5922      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
5923      * security exception will be thrown.
5924      *
5925      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5926      *              {@code null} if calling from a delegated certificate installer.
5927      * @param certBuffer encoded form of the certificate to install.
5928      *
5929      * @return false if the certBuffer cannot be parsed or installation is
5930      *         interrupted, true otherwise.
5931      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5932      *         owner.
5933      * @see #setDelegatedScopes
5934      * @see #DELEGATION_CERT_INSTALL
5935      */
installCaCert(@ullable ComponentName admin, byte[] certBuffer)5936     public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
5937         throwIfParentInstance("installCaCert");
5938         if (mService != null) {
5939             try {
5940                 return mService.installCaCert(admin, mContext.getPackageName(), certBuffer);
5941             } catch (RemoteException e) {
5942                 throw e.rethrowFromSystemServer();
5943             }
5944         }
5945         return false;
5946     }
5947 
5948     /**
5949      * Uninstalls the given certificate from trusted user CAs, if present.
5950      *
5951      * The caller must be a profile or device owner on that user, or a delegate package given the
5952      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
5953      * security exception will be thrown.
5954      *
5955      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5956      *              {@code null} if calling from a delegated certificate installer.
5957      * @param certBuffer encoded form of the certificate to remove.
5958      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5959      *         owner.
5960      * @see #setDelegatedScopes
5961      * @see #DELEGATION_CERT_INSTALL
5962      */
uninstallCaCert(@ullable ComponentName admin, byte[] certBuffer)5963     public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
5964         throwIfParentInstance("uninstallCaCert");
5965         if (mService != null) {
5966             try {
5967                 final String alias = getCaCertAlias(certBuffer);
5968                 mService.uninstallCaCerts(admin, mContext.getPackageName(), new String[] {alias});
5969             } catch (CertificateException e) {
5970                 Log.w(TAG, "Unable to parse certificate", e);
5971             } catch (RemoteException e) {
5972                 throw e.rethrowFromSystemServer();
5973             }
5974         }
5975     }
5976 
5977     /**
5978      * Returns all CA certificates that are currently trusted, excluding system CA certificates.
5979      * If a user has installed any certificates by other means than device policy these will be
5980      * included too.
5981      *
5982      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5983      *              {@code null} if calling from a delegated certificate installer.
5984      * @return a List of byte[] arrays, each encoding one user CA certificate.
5985      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5986      *         owner.
5987      */
getInstalledCaCerts(@ullable ComponentName admin)5988     public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
5989         final List<byte[]> certs = new ArrayList<byte[]>();
5990         throwIfParentInstance("getInstalledCaCerts");
5991         if (mService != null) {
5992             try {
5993                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
5994                 final TrustedCertificateStore certStore = new TrustedCertificateStore();
5995                 for (String alias : certStore.userAliases()) {
5996                     try {
5997                         certs.add(certStore.getCertificate(alias).getEncoded());
5998                     } catch (CertificateException ce) {
5999                         Log.w(TAG, "Could not encode certificate: " + alias, ce);
6000                     }
6001                 }
6002             } catch (RemoteException re) {
6003                 throw re.rethrowFromSystemServer();
6004             }
6005         }
6006         return certs;
6007     }
6008 
6009     /**
6010      * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
6011      * means other than device policy will also be removed, except for system CA certificates.
6012      *
6013      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6014      *              {@code null} if calling from a delegated certificate installer.
6015      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6016      *         owner.
6017      */
uninstallAllUserCaCerts(@ullable ComponentName admin)6018     public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
6019         throwIfParentInstance("uninstallAllUserCaCerts");
6020         if (mService != null) {
6021             try {
6022                 mService.uninstallCaCerts(admin, mContext.getPackageName(),
6023                         new TrustedCertificateStore().userAliases() .toArray(new String[0]));
6024             } catch (RemoteException re) {
6025                 throw re.rethrowFromSystemServer();
6026             }
6027         }
6028     }
6029 
6030     /**
6031      * Returns whether this certificate is installed as a trusted CA.
6032      *
6033      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6034      *              {@code null} if calling from a delegated certificate installer.
6035      * @param certBuffer encoded form of the certificate to look up.
6036      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6037      *         owner.
6038      */
hasCaCertInstalled(@ullable ComponentName admin, byte[] certBuffer)6039     public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
6040         throwIfParentInstance("hasCaCertInstalled");
6041         if (mService != null) {
6042             try {
6043                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
6044                 return getCaCertAlias(certBuffer) != null;
6045             } catch (RemoteException re) {
6046                 throw re.rethrowFromSystemServer();
6047             } catch (CertificateException ce) {
6048                 Log.w(TAG, "Could not parse certificate", ce);
6049             }
6050         }
6051         return false;
6052     }
6053 
6054     /**
6055      * This API can be called by the following to install a certificate and corresponding
6056      * private key:
6057      * <ul>
6058      *    <li>Device owner</li>
6059      *    <li>Profile owner</li>
6060      *    <li>Delegated certificate installer</li>
6061      *    <li>Credential management app</li>
6062      * </ul>
6063      * All apps within the profile will be able to access the certificate and use the private key,
6064      * given direct user approval.
6065      *
6066      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
6067      * can call this API. However, this API sets the key pair as user selectable by default,
6068      * which is not permitted when called by the credential management app. Instead,
6069      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)} should be
6070      * called with {@link #INSTALLKEY_SET_USER_SELECTABLE} not set as a flag.
6071      *
6072      * <p>Access to the installed credentials will not be granted to the caller of this API without
6073      * direct user approval. This is for security - should a certificate installer become
6074      * compromised, certificates it had already installed will be protected.
6075      *
6076      * <p>If the installer must have access to the credentials, call
6077      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead.
6078      *
6079      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
6080      * have been given to access the key and certificates associated with this alias will be
6081      * revoked.
6082      *
6083      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6084      *            {@code null} if calling from a delegated certificate installer.
6085      * @param privKey The private key to install.
6086      * @param cert The certificate to install.
6087      * @param alias The private key alias under which to install the certificate. If a certificate
6088      * with that alias already exists, it will be overwritten.
6089      * @return {@code true} if the keys were installed, {@code false} otherwise.
6090      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6091      *         owner.
6092      * @see #setDelegatedScopes
6093      * @see #DELEGATION_CERT_INSTALL
6094      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate cert, @NonNull String alias)6095     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
6096             @NonNull Certificate cert, @NonNull String alias) {
6097         return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false);
6098     }
6099 
6100     /**
6101      * This API can be called by the following to install a certificate chain and corresponding
6102      * private key for the leaf certificate:
6103      * <ul>
6104      *    <li>Device owner</li>
6105      *    <li>Profile owner</li>
6106      *    <li>Delegated certificate installer</li>
6107      *    <li>Credential management app</li>
6108      * </ul>
6109      * All apps within the profile will be able to access the certificate chain and use the private
6110      * key, given direct user approval.
6111      *
6112      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
6113      * can call this API. However, this API sets the key pair as user selectable by default,
6114      * which is not permitted when called by the credential management app. Instead,
6115      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)} should be
6116      * called with {@link #INSTALLKEY_SET_USER_SELECTABLE} not set as a flag.
6117      * Note, there can only be a credential management app on an unmanaged device.
6118      *
6119      * <p>The caller of this API may grant itself access to the certificate and private key
6120      * immediately, without user approval. It is a best practice not to request this unless strictly
6121      * necessary since it opens up additional security vulnerabilities.
6122      *
6123      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
6124      * have been given to access the key and certificates associated with this alias will be
6125      * revoked.
6126      *
6127      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6128      *        {@code null} if calling from a delegated certificate installer.
6129      * @param privKey The private key to install.
6130      * @param certs The certificate chain to install. The chain should start with the leaf
6131      *        certificate and include the chain of trust in order. This will be returned by
6132      *        {@link android.security.KeyChain#getCertificateChain}.
6133      * @param alias The private key alias under which to install the certificate. If a certificate
6134      *        with that alias already exists, it will be overwritten.
6135      * @param requestAccess {@code true} to request that the calling app be granted access to the
6136      *        credentials immediately. Otherwise, access to the credentials will be gated by user
6137      *        approval.
6138      * @return {@code true} if the keys were installed, {@code false} otherwise.
6139      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6140      *         owner.
6141      * @see android.security.KeyChain#getCertificateChain
6142      * @see #setDelegatedScopes
6143      * @see #DELEGATION_CERT_INSTALL
6144      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess)6145     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
6146             @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) {
6147         int flags = INSTALLKEY_SET_USER_SELECTABLE;
6148         if (requestAccess) {
6149             flags |= INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
6150         }
6151         return installKeyPair(admin, privKey, certs, alias, flags);
6152     }
6153 
6154     /**
6155      * This API can be called by the following to install a certificate chain and corresponding
6156      * private key for the leaf certificate:
6157      * <ul>
6158      *    <li>Device owner</li>
6159      *    <li>Profile owner</li>
6160      *    <li>Delegated certificate installer</li>
6161      *    <li>Credential management app</li>
6162      * </ul>
6163      * All apps within the profile will be able to access the certificate chain and use the
6164      * private key, given direct user approval (if the user is allowed to select the private key).
6165      *
6166      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
6167      * can call this API. If called by the credential management app:
6168      * <ul>
6169      *    <li>The componentName must be {@code null}r</li>
6170      *    <li>The alias must exist in the credential management app's
6171      *    {@link android.security.AppUriAuthenticationPolicy}</li>
6172      *    <li>The key pair must not be user selectable</li>
6173      * </ul>
6174      * Note, there can only be a credential management app on an unmanaged device.
6175      *
6176      * <p>The caller of this API may grant itself access to the certificate and private key
6177      * immediately, without user approval. It is a best practice not to request this unless strictly
6178      * necessary since it opens up additional security vulnerabilities.
6179      *
6180      * <p>Include {@link #INSTALLKEY_SET_USER_SELECTABLE} in the {@code flags} argument to allow
6181      * the user to select the key from a dialog.
6182      *
6183      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
6184      * have been given to access the key and certificates associated with this alias will be
6185      * revoked.
6186      *
6187      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6188      *        {@code null} if calling from a delegated certificate installer.
6189      * @param privKey The private key to install.
6190      * @param certs The certificate chain to install. The chain should start with the leaf
6191      *        certificate and include the chain of trust in order. This will be returned by
6192      *        {@link android.security.KeyChain#getCertificateChain}.
6193      * @param alias The private key alias under which to install the certificate. If a certificate
6194      *        with that alias already exists, it will be overwritten.
6195      * @param flags Flags to request that the calling app be granted access to the credentials
6196      *        and set the key to be user-selectable. See {@link #INSTALLKEY_SET_USER_SELECTABLE} and
6197      *        {@link #INSTALLKEY_REQUEST_CREDENTIALS_ACCESS}.
6198      * @return {@code true} if the keys were installed, {@code false} otherwise.
6199      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6200      *         owner, or {@code admin} is null but the calling application is not a delegated
6201      *         certificate installer or credential management app.
6202      * @see android.security.KeyChain#getCertificateChain
6203      * @see #setDelegatedScopes
6204      * @see #DELEGATION_CERT_INSTALL
6205      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, int flags)6206     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
6207             @NonNull Certificate[] certs, @NonNull String alias, int flags) {
6208         throwIfParentInstance("installKeyPair");
6209         boolean requestAccess = (flags & INSTALLKEY_REQUEST_CREDENTIALS_ACCESS)
6210                 == INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
6211         boolean isUserSelectable = (flags & INSTALLKEY_SET_USER_SELECTABLE)
6212                 == INSTALLKEY_SET_USER_SELECTABLE;
6213         try {
6214             final byte[] pemCert = Credentials.convertToPem(certs[0]);
6215             byte[] pemChain = null;
6216             if (certs.length > 1) {
6217                 pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length));
6218             }
6219             final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
6220                     .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
6221             return mService.installKeyPair(admin, mContext.getPackageName(), pkcs8Key, pemCert,
6222                     pemChain, alias, requestAccess, isUserSelectable);
6223         } catch (RemoteException e) {
6224             throw e.rethrowFromSystemServer();
6225         } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
6226             Log.w(TAG, "Failed to obtain private key material", e);
6227         } catch (CertificateException | IOException e) {
6228             Log.w(TAG, "Could not pem-encode certificate", e);
6229         }
6230         return false;
6231     }
6232 
6233     /**
6234      * This API can be called by the following to remove a certificate and private key pair
6235      * installed under a given alias:
6236      * <ul>
6237      *    <li>Device owner</li>
6238      *    <li>Profile owner</li>
6239      *    <li>Delegated certificate installer</li>
6240      *    <li>Credential management app</li>
6241      * </ul>
6242      *
6243      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
6244      * can call this API. If called by the credential management app, the componentName must be
6245      * {@code null}. Note, there can only be a credential management app on an unmanaged device.
6246      *
6247      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6248      *        {@code null} if calling from a delegated certificate installer.
6249      * @param alias The private key alias under which the certificate is installed.
6250      * @return {@code true} if the private key alias no longer exists, {@code false} otherwise.
6251      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6252      *         owner, or {@code admin} is null but the calling application is not a delegated
6253      *         certificate installer or credential management app.
6254      * @see #setDelegatedScopes
6255      * @see #DELEGATION_CERT_INSTALL
6256      */
removeKeyPair(@ullable ComponentName admin, @NonNull String alias)6257     public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
6258         throwIfParentInstance("removeKeyPair");
6259         try {
6260             return mService.removeKeyPair(admin, mContext.getPackageName(), alias);
6261         } catch (RemoteException e) {
6262             throw e.rethrowFromSystemServer();
6263         }
6264     }
6265 
6266     // STOPSHIP(b/174298501): clarify the expected return value following generateKeyPair call.
6267     /**
6268      * This API can be called by the following to query whether a certificate and private key are
6269      * installed under a given alias:
6270      * <ul>
6271      *    <li>Device owner</li>
6272      *    <li>Profile owner</li>
6273      *    <li>Delegated certificate installer</li>
6274      *    <li>Credential management app</li>
6275      * </ul>
6276      *
6277      * If called by the credential management app, the alias must exist in the credential
6278      * management app's {@link android.security.AppUriAuthenticationPolicy}.
6279      *
6280      * @param alias The alias under which the key pair is installed.
6281      * @return {@code true} if a key pair with this alias exists, {@code false} otherwise.
6282      * @throws SecurityException if the caller is not a device or profile owner, a delegated
6283      *         certificate installer or the credential management app.
6284      * @see #setDelegatedScopes
6285      * @see #DELEGATION_CERT_INSTALL
6286      */
hasKeyPair(@onNull String alias)6287     public boolean hasKeyPair(@NonNull String alias) {
6288         throwIfParentInstance("hasKeyPair");
6289         try {
6290             return mService.hasKeyPair(mContext.getPackageName(), alias);
6291         } catch (RemoteException e) {
6292             throw e.rethrowFromSystemServer();
6293         }
6294     }
6295 
6296     /**
6297      * This API can be called by the following to generate a new private/public key pair:
6298      * <ul>
6299      *    <li>Device owner</li>
6300      *    <li>Profile owner</li>
6301      *    <li>Delegated certificate installer</li>
6302      *    <li>Credential management app</li>
6303      * </ul>
6304      * If the device supports key generation via secure hardware, this method is useful for
6305      * creating a key in KeyChain that never left the secure hardware. Access to the key is
6306      * controlled the same way as in {@link #installKeyPair}.
6307      *
6308      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
6309      * can call this API. If called by the credential management app, the componentName must be
6310      * {@code null}. Note, there can only be a credential management app on an unmanaged device.
6311      *
6312      * <p>Because this method might take several seconds to complete, it should only be called from
6313      * a worker thread. This method returns {@code null} when called from the main thread.
6314      *
6315      * <p>This method is not thread-safe, calling it from multiple threads at the same time will
6316      * result in undefined behavior. If the calling thread is interrupted while the invocation is
6317      * in-flight, it will eventually terminate and return {@code null}.
6318      *
6319      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
6320      * have been given to access the key and certificates associated with this alias will be
6321      * revoked.
6322      *
6323      * <p>Attestation: to enable attestation, set an attestation challenge in {@code keySpec} via
6324      * {@link KeyGenParameterSpec.Builder#setAttestationChallenge}. By specifying flags to the
6325      * {@code idAttestationFlags} parameter, it is possible to request the device's unique
6326      * identity to be included in the attestation record.
6327      *
6328      * <p>Specific identifiers can be included in the attestation record, and an individual
6329      * attestation certificate can be used to sign the attestation record. To find out if the device
6330      * supports these features, refer to {@link #isDeviceIdAttestationSupported()} and
6331      * {@link #isUniqueDeviceAttestationSupported()}.
6332      *
6333      * <p>Device owner, profile owner, their delegated certificate installer and the credential
6334      * management app can use {@link #ID_TYPE_BASE_INFO} to request inclusion of the general device
6335      * information including manufacturer, model, brand, device and product in the attestation
6336      * record.
6337      * Only device owner, profile owner on an organization-owned device and their delegated
6338      * certificate installers can use {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and
6339      * {@link #ID_TYPE_MEID} to request unique device identifiers to be attested (the serial number,
6340      * IMEI and MEID correspondingly), if supported by the device
6341      * (see {@link #isDeviceIdAttestationSupported()}).
6342      * Additionally, device owner, profile owner on an organization-owned device and their delegated
6343      * certificate installers can also request the attestation record to be signed using an
6344      * individual attestation certificate by specifying the {@link #ID_TYPE_INDIVIDUAL_ATTESTATION}
6345      * flag (if supported by the device, see {@link #isUniqueDeviceAttestationSupported()}).
6346      * <p>
6347      * If any of {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID}
6348      * is set, it is implicitly assumed that {@link #ID_TYPE_BASE_INFO} is also set.
6349      * <p>
6350      * Attestation using {@link #ID_TYPE_INDIVIDUAL_ATTESTATION} can only be requested if
6351      * key generation is done in StrongBox.
6352      *
6353      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6354      *            {@code null} if calling from a delegated certificate installer.
6355      * @param algorithm The key generation algorithm, see {@link java.security.KeyPairGenerator}.
6356      * @param keySpec Specification of the key to generate, see
6357      * {@link java.security.KeyPairGenerator}.
6358      * @param idAttestationFlags A bitmask of the identifiers that should be included in the
6359      *        attestation record ({@code ID_TYPE_BASE_INFO}, {@code ID_TYPE_SERIAL},
6360      *        {@code ID_TYPE_IMEI} and {@code ID_TYPE_MEID}), and
6361      *        {@code ID_TYPE_INDIVIDUAL_ATTESTATION} if the attestation record should be signed
6362      *        using an individual attestation certificate.
6363      *        <p>
6364      *        {@code 0} should be passed in if no device identification is required in the
6365      *        attestation record and the batch attestation certificate should be used.
6366      *        <p>
6367      *        If any flag is specified, then an attestation challenge must be included in the
6368      *        {@code keySpec}.
6369      * @return A non-null {@code AttestedKeyPair} if the key generation succeeded, null otherwise.
6370      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6371      *         owner, or {@code admin} is null but the calling application is not a delegated
6372      *         certificate installer or credential management app. If Device ID attestation is
6373      *         requested (using {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} or
6374      *         {@link #ID_TYPE_MEID}), the caller must be the Device Owner or the Certificate
6375      *         Installer delegate.
6376      * @throws IllegalArgumentException in the following cases:
6377      *         <p>
6378      *         <ul>
6379      *         <li>The alias in {@code keySpec} is empty.</li>
6380      *         <li>The algorithm specification in {@code keySpec} is not
6381      *         {@code RSAKeyGenParameterSpec} or {@code ECGenParameterSpec}.</li>
6382      *         <li>Device ID attestation was requested but the {@code keySpec} does not contain an
6383      *         attestation challenge.</li>
6384      *         </ul>
6385      * @throws UnsupportedOperationException if Device ID attestation or individual attestation
6386      *         was requested but the underlying hardware does not support it.
6387      * @throws StrongBoxUnavailableException if the use of StrongBox for key generation was
6388      *         specified in {@code keySpec} but the device does not have one.
6389      * @see KeyGenParameterSpec.Builder#setAttestationChallenge(byte[])
6390      */
generateKeyPair(@ullable ComponentName admin, @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec, @AttestationIdType int idAttestationFlags)6391     public AttestedKeyPair generateKeyPair(@Nullable ComponentName admin,
6392             @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec,
6393             @AttestationIdType int idAttestationFlags) {
6394         throwIfParentInstance("generateKeyPair");
6395         try {
6396             final ParcelableKeyGenParameterSpec parcelableSpec =
6397                     new ParcelableKeyGenParameterSpec(keySpec);
6398             KeymasterCertificateChain attestationChain = new KeymasterCertificateChain();
6399 
6400             // Translate ID attestation flags to values used by AttestationUtils
6401             final boolean success = mService.generateKeyPair(
6402                     admin, mContext.getPackageName(), algorithm, parcelableSpec,
6403                     idAttestationFlags, attestationChain);
6404             if (!success) {
6405                 Log.e(TAG, "Error generating key via DevicePolicyManagerService.");
6406                 return null;
6407             }
6408 
6409             final String alias = keySpec.getKeystoreAlias();
6410             final KeyPair keyPair = KeyChain.getKeyPair(mContext, alias);
6411             Certificate[] outputChain = null;
6412             try {
6413                 if (AttestationUtils.isChainValid(attestationChain)) {
6414                     outputChain = AttestationUtils.parseCertificateChain(attestationChain);
6415                 }
6416             } catch (KeyAttestationException e) {
6417                 Log.e(TAG, "Error parsing attestation chain for alias " + alias, e);
6418                 mService.removeKeyPair(admin, mContext.getPackageName(), alias);
6419                 return null;
6420             }
6421             return new AttestedKeyPair(keyPair, outputChain);
6422         } catch (RemoteException e) {
6423             throw e.rethrowFromSystemServer();
6424         } catch (KeyChainException e) {
6425             Log.w(TAG, "Failed to generate key", e);
6426         } catch (InterruptedException e) {
6427             Log.w(TAG, "Interrupted while generating key", e);
6428             Thread.currentThread().interrupt();
6429         } catch (ServiceSpecificException e) {
6430             Log.w(TAG, String.format("Key Generation failure: %d", e.errorCode));
6431             switch (e.errorCode) {
6432                 case KEY_GEN_STRONGBOX_UNAVAILABLE:
6433                     throw new StrongBoxUnavailableException("No StrongBox for key generation.");
6434                 default:
6435                     throw new RuntimeException(
6436                             String.format("Unknown error while generating key: %d", e.errorCode));
6437             }
6438         }
6439         return null;
6440     }
6441 
6442     /**
6443      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
6444      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to grant an application access
6445      * to an already-installed (or generated) KeyChain key.
6446      * This is useful (in combination with {@link #installKeyPair} or {@link #generateKeyPair}) to
6447      * let an application call {@link android.security.KeyChain#getPrivateKey} without having to
6448      * call {@link android.security.KeyChain#choosePrivateKeyAlias} first.
6449      *
6450      * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED}
6451      * broadcast when access to a key is granted.
6452      *
6453      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6454      *        {@code null} if calling from a delegated certificate chooser.
6455      * @param alias The alias of the key to grant access to.
6456      * @param packageName The name of the (already installed) package to grant access to.
6457      * @return {@code true} if the grant was set successfully, {@code false} otherwise.
6458      *
6459      * @throws SecurityException if the caller is not a device owner, a profile owner or
6460      *         delegated certificate chooser.
6461      * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if
6462      *         {@code packageName} is not a name of an installed package.
6463      * @see #revokeKeyPairFromApp
6464      */
grantKeyPairToApp(@ullable ComponentName admin, @NonNull String alias, @NonNull String packageName)6465     public boolean grantKeyPairToApp(@Nullable ComponentName admin, @NonNull String alias,
6466             @NonNull String packageName) {
6467         throwIfParentInstance("grantKeyPairToApp");
6468         try {
6469             return mService.setKeyGrantForApp(
6470                     admin, mContext.getPackageName(), alias, packageName, true);
6471         } catch (RemoteException e) {
6472             e.rethrowFromSystemServer();
6473         }
6474         return false;
6475     }
6476 
6477     /**
6478      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
6479      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to query which apps have access
6480      * to a given KeyChain key.
6481      *
6482      * Key are granted on a per-UID basis, so if several apps share the same UID, granting access to
6483      * one of them automatically grants it to others. This method returns a map containing one entry
6484      * per grantee UID. Entries have UIDs as keys and sets of corresponding package names as values.
6485      * In particular, grantee packages that don't share UID with other packages are represented by
6486      * entries having singleton sets as values.
6487      *
6488      * @param alias The alias of the key to grant access to.
6489      * @return apps that have access to a given key, arranged in a map from UID to sets of
6490      *       package names.
6491      *
6492      * @throws SecurityException if the caller is not a device owner, a profile owner or
6493      *         delegated certificate chooser.
6494      * @throws IllegalArgumentException if {@code alias} doesn't correspond to an existing key.
6495      *
6496      * @see #grantKeyPairToApp(ComponentName, String, String)
6497      */
getKeyPairGrants(@onNull String alias)6498     public @NonNull Map<Integer, Set<String>> getKeyPairGrants(@NonNull String alias) {
6499         throwIfParentInstance("getKeyPairGrants");
6500         try {
6501             // The result is wrapped into intermediate parcelable representation.
6502             return mService.getKeyPairGrants(mContext.getPackageName(), alias).getPackagesByUid();
6503         } catch (RemoteException e) {
6504             e.rethrowFromSystemServer();
6505         }
6506         return null;
6507     }
6508 
6509     /**
6510      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
6511      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to revoke an application's
6512      * grant to a KeyChain key pair.
6513      * Calls by the application to {@link android.security.KeyChain#getPrivateKey}
6514      * will fail after the grant is revoked.
6515      *
6516      * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED}
6517      * broadcast when access to a key is revoked.
6518      *
6519      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6520      *        {@code null} if calling from a delegated certificate chooser.
6521      * @param alias The alias of the key to revoke access from.
6522      * @param packageName The name of the (already installed) package to revoke access from.
6523      * @return {@code true} if the grant was revoked successfully, {@code false} otherwise.
6524      *
6525      * @throws SecurityException if the caller is not a device owner, a profile owner or
6526      *         delegated certificate chooser.
6527      * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if
6528      *         {@code packageName} is not a name of an installed package.
6529      * @see #grantKeyPairToApp
6530      */
revokeKeyPairFromApp(@ullable ComponentName admin, @NonNull String alias, @NonNull String packageName)6531     public boolean revokeKeyPairFromApp(@Nullable ComponentName admin, @NonNull String alias,
6532             @NonNull String packageName) {
6533         throwIfParentInstance("revokeKeyPairFromApp");
6534         try {
6535             return mService.setKeyGrantForApp(
6536                     admin, mContext.getPackageName(), alias, packageName, false);
6537         } catch (RemoteException e) {
6538             e.rethrowFromSystemServer();
6539         }
6540         return false;
6541     }
6542 
6543     /**
6544      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
6545      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to allow using a KeyChain key
6546      * pair for authentication to Wifi networks. The key can then be used in configurations passed
6547      * to {@link android.net.wifi.WifiManager#addNetwork}.
6548      *
6549      * @param alias The alias of the key pair.
6550      * @return {@code true} if the operation was set successfully, {@code false} otherwise.
6551      *
6552      * @throws SecurityException if the caller is not a device owner, a profile owner or
6553      *         delegated certificate chooser.
6554      * @see #revokeKeyPairFromWifiAuth
6555      */
grantKeyPairToWifiAuth(@onNull String alias)6556     public boolean grantKeyPairToWifiAuth(@NonNull String alias) {
6557         throwIfParentInstance("grantKeyPairToWifiAuth");
6558         try {
6559             return mService.setKeyGrantToWifiAuth(mContext.getPackageName(), alias, true);
6560         } catch (RemoteException e) {
6561             e.rethrowFromSystemServer();
6562         }
6563         return false;
6564     }
6565 
6566     /**
6567      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
6568      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to deny using a KeyChain key
6569      * pair for authentication to Wifi networks. Configured networks using this key won't be able to
6570      * authenticate.
6571      *
6572      * @param alias The alias of the key pair.
6573      * @return {@code true} if the operation was set successfully, {@code false} otherwise.
6574      *
6575      * @throws SecurityException if the caller is not a device owner, a profile owner or
6576      *         delegated certificate chooser.
6577      * @see #grantKeyPairToWifiAuth
6578      */
revokeKeyPairFromWifiAuth(@onNull String alias)6579     public boolean revokeKeyPairFromWifiAuth(@NonNull String alias) {
6580         throwIfParentInstance("revokeKeyPairFromWifiAuth");
6581         try {
6582             return mService.setKeyGrantToWifiAuth(mContext.getPackageName(), alias, false);
6583         } catch (RemoteException e) {
6584             e.rethrowFromSystemServer();
6585         }
6586         return false;
6587     }
6588 
6589     /**
6590      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
6591      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to query whether a KeyChain key
6592      * pair can be used for authentication to Wifi networks.
6593      *
6594      * @param alias The alias of the key pair.
6595      * @return {@code true} if the key pair can be used, {@code false} otherwise.
6596      *
6597      * @throws SecurityException if the caller is not a device owner, a profile owner or
6598      *         delegated certificate chooser.
6599      * @see #grantKeyPairToWifiAuth
6600      */
isKeyPairGrantedToWifiAuth(@onNull String alias)6601     public boolean isKeyPairGrantedToWifiAuth(@NonNull String alias) {
6602         throwIfParentInstance("isKeyPairGrantedToWifiAuth");
6603         try {
6604             return mService.isKeyPairGrantedToWifiAuth(mContext.getPackageName(), alias);
6605         } catch (RemoteException e) {
6606             e.rethrowFromSystemServer();
6607         }
6608         return false;
6609     }
6610 
6611     /**
6612      * Returns {@code true} if the device supports attestation of device identifiers in addition
6613      * to key attestation. See
6614      * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}
6615      * @return {@code true} if Device ID attestation is supported.
6616      */
isDeviceIdAttestationSupported()6617     public boolean isDeviceIdAttestationSupported() {
6618         PackageManager pm = mContext.getPackageManager();
6619         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ID_ATTESTATION);
6620     }
6621 
6622     /**
6623      * Returns {@code true} if the StrongBox Keymaster implementation on the device was provisioned
6624      * with an individual attestation certificate and can sign attestation records using it (as
6625      * attestation using an individual attestation certificate is a feature only Keymaster
6626      * implementations with StrongBox security level can implement).
6627      * For use prior to calling
6628      * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}.
6629      * @return {@code true} if individual attestation is supported.
6630      */
isUniqueDeviceAttestationSupported()6631     public boolean isUniqueDeviceAttestationSupported() {
6632         PackageManager pm = mContext.getPackageManager();
6633         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_UNIQUE_ATTESTATION);
6634     }
6635 
6636     /**
6637      * This API can be called by the following to associate certificates with a key pair that was
6638      * generated using {@link #generateKeyPair}, and set whether the key is available for the user
6639      * to choose in the certificate selection prompt:
6640      * <ul>
6641      *    <li>Device owner</li>
6642      *    <li>Profile owner</li>
6643      *    <li>Delegated certificate installer</li>
6644      *    <li>Credential management app</li>
6645      * </ul>
6646      *
6647      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
6648      * can call this API. If called by the credential management app, the componentName must be
6649      * {@code null}. Note, there can only be a credential management app on an unmanaged device.
6650      *
6651      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6652      *            {@code null} if calling from a delegated certificate installer.
6653      * @param alias The private key alias under which to install the certificate. The {@code alias}
6654      *        should denote an existing private key. If a certificate with that alias already
6655      *        exists, it will be overwritten.
6656      * @param certs The certificate chain to install. The chain should start with the leaf
6657      *        certificate and include the chain of trust in order. This will be returned by
6658      *        {@link android.security.KeyChain#getCertificateChain}.
6659      * @param isUserSelectable {@code true} to indicate that a user can select this key via the
6660      *        certificate selection prompt, {@code false} to indicate that this key can only be
6661      *        granted access by implementing
6662      *        {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
6663      * @return {@code true} if the provided {@code alias} exists and the certificates has been
6664      *        successfully associated with it, {@code false} otherwise.
6665      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6666      *         owner, or {@code admin} is null but the calling application is not a delegated
6667      *         certificate installer or credential management app.
6668      */
setKeyPairCertificate(@ullable ComponentName admin, @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable)6669     public boolean setKeyPairCertificate(@Nullable ComponentName admin,
6670             @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable) {
6671         throwIfParentInstance("setKeyPairCertificate");
6672         try {
6673             final byte[] pemCert = Credentials.convertToPem(certs.get(0));
6674             byte[] pemChain = null;
6675             if (certs.size() > 1) {
6676                 pemChain = Credentials.convertToPem(
6677                         certs.subList(1, certs.size()).toArray(new Certificate[0]));
6678             }
6679             return mService.setKeyPairCertificate(admin, mContext.getPackageName(), alias, pemCert,
6680                     pemChain, isUserSelectable);
6681         } catch (RemoteException e) {
6682             throw e.rethrowFromSystemServer();
6683         } catch (CertificateException | IOException e) {
6684             Log.w(TAG, "Could not pem-encode certificate", e);
6685         }
6686         return false;
6687     }
6688 
6689 
6690     /**
6691      * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
6692      * doesn't exist.
6693      */
getCaCertAlias(byte[] certBuffer)6694     private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
6695         final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
6696         final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
6697                               new ByteArrayInputStream(certBuffer));
6698         return new TrustedCertificateStore().getCertificateAlias(cert);
6699     }
6700 
6701     /**
6702      * Called by a profile owner or device owner to grant access to privileged certificate
6703      * manipulation APIs to a third-party certificate installer app. Granted APIs include
6704      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
6705      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
6706      * <p>
6707      * Delegated certificate installer is a per-user state. The delegated access is persistent until
6708      * it is later cleared by calling this method with a null value or uninstallling the certificate
6709      * installer.
6710      * <p>
6711      * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
6712      * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
6713      * supplied certificate installer package must be installed when calling this API, otherwise an
6714      * {@link IllegalArgumentException} will be thrown.
6715      *
6716      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6717      * @param installerPackage The package name of the certificate installer which will be given
6718      *            access. If {@code null} is given the current package will be cleared.
6719      * @throws SecurityException if {@code admin} is not a device or a profile owner.
6720      *
6721      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
6722      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
6723      */
6724     @Deprecated
setCertInstallerPackage(@onNull ComponentName admin, @Nullable String installerPackage)6725     public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
6726             installerPackage) throws SecurityException {
6727         throwIfParentInstance("setCertInstallerPackage");
6728         if (mService != null) {
6729             try {
6730                 mService.setCertInstallerPackage(admin, installerPackage);
6731             } catch (RemoteException e) {
6732                 throw e.rethrowFromSystemServer();
6733             }
6734         }
6735     }
6736 
6737     /**
6738      * Called by a profile owner or device owner to retrieve the certificate installer for the user,
6739      * or {@code null} if none is set. If there are multiple delegates this function will return one
6740      * of them.
6741      *
6742      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6743      * @return The package name of the current delegated certificate installer, or {@code null} if
6744      *         none is set.
6745      * @throws SecurityException if {@code admin} is not a device or a profile owner.
6746      *
6747      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
6748      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
6749      */
6750     @Deprecated
getCertInstallerPackage(@onNull ComponentName admin)6751     public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
6752             throws SecurityException {
6753         throwIfParentInstance("getCertInstallerPackage");
6754         if (mService != null) {
6755             try {
6756                 return mService.getCertInstallerPackage(admin);
6757             } catch (RemoteException e) {
6758                 throw e.rethrowFromSystemServer();
6759             }
6760         }
6761         return null;
6762     }
6763 
6764     /**
6765      * Called by a profile owner or device owner to grant access to privileged APIs to another app.
6766      * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*}
6767      * constants.
6768      * <p>
6769      * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be
6770      * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra
6771      * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the
6772      * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag.
6773      * <p>
6774      * Delegated scopes are a per-user state. The delegated access is persistent until it is later
6775      * cleared by calling this method with an empty {@code scopes} list or uninstalling the
6776      * {@code delegatePackage}.
6777      *
6778      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6779      * @param delegatePackage The package name of the app which will be given access.
6780      * @param scopes The groups of privileged APIs whose access should be granted to
6781      *            {@code delegatedPackage}.
6782      * @throws SecurityException if {@code admin} is not a device or a profile owner.
6783      */
setDelegatedScopes(@onNull ComponentName admin, @NonNull String delegatePackage, @NonNull List<String> scopes)6784      public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage,
6785             @NonNull List<String> scopes) {
6786         throwIfParentInstance("setDelegatedScopes");
6787         if (mService != null) {
6788             try {
6789                 mService.setDelegatedScopes(admin, delegatePackage, scopes);
6790             } catch (RemoteException e) {
6791                 throw e.rethrowFromSystemServer();
6792             }
6793         }
6794     }
6795 
6796     /**
6797      * Called by a profile owner or device owner to retrieve a list of the scopes given to a
6798      * delegate package. Other apps can use this method to retrieve their own delegated scopes by
6799      * passing {@code null} for {@code admin} and their own package name as
6800      * {@code delegatedPackage}.
6801      *
6802      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6803      *            {@code null} if the caller is {@code delegatedPackage}.
6804      * @param delegatedPackage The package name of the app whose scopes should be retrieved.
6805      * @return A list containing the scopes given to {@code delegatedPackage}.
6806      * @throws SecurityException if {@code admin} is not a device or a profile owner.
6807      */
6808      @NonNull
getDelegatedScopes(@ullable ComponentName admin, @NonNull String delegatedPackage)6809      public List<String> getDelegatedScopes(@Nullable ComponentName admin,
6810              @NonNull String delegatedPackage) {
6811          throwIfParentInstance("getDelegatedScopes");
6812          if (mService != null) {
6813              try {
6814                  return mService.getDelegatedScopes(admin, delegatedPackage);
6815              } catch (RemoteException e) {
6816                  throw e.rethrowFromSystemServer();
6817              }
6818          }
6819          return null;
6820     }
6821 
6822     /**
6823      * Called by a profile owner or device owner to retrieve a list of delegate packages that were
6824      * granted a delegation scope.
6825      *
6826      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6827      * @param delegationScope The scope whose delegates should be retrieved.
6828      * @return A list of package names of the current delegated packages for
6829                {@code delegationScope}.
6830      * @throws SecurityException if {@code admin} is not a device or a profile owner.
6831      */
6832      @Nullable
getDelegatePackages(@onNull ComponentName admin, @NonNull String delegationScope)6833      public List<String> getDelegatePackages(@NonNull ComponentName admin,
6834              @NonNull String delegationScope) {
6835         throwIfParentInstance("getDelegatePackages");
6836         if (mService != null) {
6837             try {
6838                 return mService.getDelegatePackages(admin, delegationScope);
6839             } catch (RemoteException e) {
6840                 throw e.rethrowFromSystemServer();
6841             }
6842         }
6843         return null;
6844     }
6845 
6846     /**
6847      * Service-specific error code used in implementation of {@code setAlwaysOnVpnPackage} methods.
6848      * @hide
6849      */
6850     public static final int ERROR_VPN_PACKAGE_NOT_FOUND = 1;
6851 
6852     /**
6853      * Called by a device or profile owner to configure an always-on VPN connection through a
6854      * specific application for the current user. This connection is automatically granted and
6855      * persisted after a reboot.
6856      * <p> To support the always-on feature, an app must
6857      * <ul>
6858      *     <li>declare a {@link android.net.VpnService} in its manifest, guarded by
6859      *         {@link android.Manifest.permission#BIND_VPN_SERVICE};</li>
6860      *     <li>target {@link android.os.Build.VERSION_CODES#N API 24} or above; and</li>
6861      *     <li><i>not</i> explicitly opt out of the feature through
6862      *         {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}.</li>
6863      * </ul>
6864      * The call will fail if called with the package name of an unsupported VPN app.
6865      * <p> Enabling lockdown via {@code lockdownEnabled} argument carries the risk that any failure
6866      * of the VPN provider could break networking for all apps. This method clears any lockdown
6867      * allowlist set by {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)}.
6868      * <p> Starting from {@link android.os.Build.VERSION_CODES#S API 31} calling this method with
6869      * {@code vpnPackage} set to {@code null} only removes the existing configuration if it was
6870      * previously created by this admin. To remove VPN configuration created by the user use
6871      * {@link UserManager#DISALLOW_CONFIG_VPN}.
6872      *
6873      * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
6874      *        remove an existing always-on VPN configuration.
6875      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
6876      *        {@code false} otherwise. This has no effect when clearing.
6877      * @throws SecurityException if {@code admin} is not a device or a profile owner.
6878      * @throws NameNotFoundException if {@code vpnPackage} is not installed.
6879      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
6880      *         set as always-on, or if always-on VPN is not available.
6881      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
6882      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled)6883     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
6884             boolean lockdownEnabled) throws NameNotFoundException {
6885         setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled, Collections.emptySet());
6886     }
6887 
6888     /**
6889      * A version of {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} that allows the
6890      * admin to specify a set of apps that should be able to access the network directly when VPN
6891      * is not connected. When VPN connects these apps switch over to VPN if allowed to use that VPN.
6892      * System apps can always bypass VPN.
6893      * <p> Note that the system doesn't update the allowlist when packages are installed or
6894      * uninstalled, the admin app must call this method to keep the list up to date.
6895      * <p> When {@code lockdownEnabled} is false {@code lockdownAllowlist} is ignored . When
6896      * {@code lockdownEnabled} is {@code true} and {@code lockdownAllowlist} is {@code null} or
6897      * empty, only system apps can bypass VPN.
6898      * <p> Setting always-on VPN package to {@code null} or using
6899      * {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} clears lockdown allowlist.
6900      *
6901      * @param vpnPackage package name for an installed VPN app on the device, or {@code null}
6902      *         to remove an existing always-on VPN configuration
6903      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
6904      *         {@code false} otherwise. This has no effect when clearing.
6905      * @param lockdownAllowlist Packages that will be able to access the network directly when VPN
6906      *         is in lockdown mode but not connected. Has no effect when clearing.
6907      * @throws SecurityException if {@code admin} is not a device or a profile
6908      *         owner.
6909      * @throws NameNotFoundException if {@code vpnPackage} or one of
6910      *         {@code lockdownAllowlist} is not installed.
6911      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does
6912      *         not support being set as always-on, or if always-on VPN is not
6913      *         available.
6914      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled, @Nullable Set<String> lockdownAllowlist)6915     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
6916             boolean lockdownEnabled, @Nullable Set<String> lockdownAllowlist)
6917             throws NameNotFoundException {
6918         throwIfParentInstance("setAlwaysOnVpnPackage");
6919         if (mService != null) {
6920             try {
6921                 mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled,
6922                         lockdownAllowlist == null ? null : new ArrayList<>(lockdownAllowlist));
6923             } catch (ServiceSpecificException e) {
6924                 switch (e.errorCode) {
6925                     case ERROR_VPN_PACKAGE_NOT_FOUND:
6926                         throw new NameNotFoundException(e.getMessage());
6927                     default:
6928                         throw new RuntimeException(
6929                                 "Unknown error setting always-on VPN: " + e.errorCode, e);
6930                 }
6931             } catch (RemoteException e) {
6932                 throw e.rethrowFromSystemServer();
6933             }
6934         }
6935     }
6936 
6937     /**
6938      * Called by device or profile owner to query whether current always-on VPN is configured in
6939      * lockdown mode. Returns {@code false} when no always-on configuration is set.
6940      *
6941      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6942      *
6943      * @throws SecurityException if {@code admin} is not a device or a profile owner.
6944      *
6945      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean)
6946      */
isAlwaysOnVpnLockdownEnabled(@onNull ComponentName admin)6947     public boolean isAlwaysOnVpnLockdownEnabled(@NonNull ComponentName admin) {
6948         throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
6949         if (mService != null) {
6950             try {
6951                 // Starting from Android R, the caller can pass the permission check in
6952                 // DevicePolicyManagerService if it holds android.permission.MAINLINE_NETWORK_STACK.
6953                 // Note that the android.permission.MAINLINE_NETWORK_STACK is a signature permission
6954                 // which is used by the NetworkStack mainline module.
6955                 return mService.isAlwaysOnVpnLockdownEnabled(admin);
6956             } catch (RemoteException e) {
6957                 throw e.rethrowFromSystemServer();
6958             }
6959         }
6960         return false;
6961     }
6962 
6963     /**
6964      * Returns whether the admin has enabled always-on VPN lockdown for the current user.
6965      *
6966      * Only callable by the system.
6967     * @hide
6968     */
6969     @UserHandleAware
isAlwaysOnVpnLockdownEnabled()6970     public boolean isAlwaysOnVpnLockdownEnabled() {
6971         throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
6972         if (mService != null) {
6973             try {
6974                 return mService.isAlwaysOnVpnLockdownEnabledForUser(myUserId());
6975             } catch (RemoteException e) {
6976                 throw e.rethrowFromSystemServer();
6977             }
6978         }
6979         return false;
6980     }
6981 
6982     /**
6983      * Called by device or profile owner to query the set of packages that are allowed to access
6984      * the network directly when always-on VPN is in lockdown mode but not connected. Returns
6985      * {@code null} when always-on VPN is not active or not in lockdown mode.
6986      *
6987      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6988      *
6989      * @throws SecurityException if {@code admin} is not a device or a profile owner.
6990      *
6991      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
6992      */
getAlwaysOnVpnLockdownWhitelist(@onNull ComponentName admin)6993     public @Nullable Set<String> getAlwaysOnVpnLockdownWhitelist(@NonNull ComponentName admin) {
6994         throwIfParentInstance("getAlwaysOnVpnLockdownWhitelist");
6995         if (mService != null) {
6996             try {
6997                 final List<String> allowlist =
6998                         mService.getAlwaysOnVpnLockdownAllowlist(admin);
6999                 return allowlist == null ? null : new HashSet<>(allowlist);
7000             } catch (RemoteException e) {
7001                 throw e.rethrowFromSystemServer();
7002             }
7003         }
7004         return null;
7005     }
7006 
7007     /**
7008      * Called by a device or profile owner to read the name of the package administering an
7009      * always-on VPN connection for the current user. If there is no such package, or the always-on
7010      * VPN is provided by the system instead of by an application, {@code null} will be returned.
7011      *
7012      * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
7013      *         is set.
7014      * @throws SecurityException if {@code admin} is not a device or a profile owner.
7015      */
getAlwaysOnVpnPackage(@onNull ComponentName admin)7016     public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
7017         throwIfParentInstance("getAlwaysOnVpnPackage");
7018         if (mService != null) {
7019             try {
7020                 return mService.getAlwaysOnVpnPackage(admin);
7021             } catch (RemoteException e) {
7022                 throw e.rethrowFromSystemServer();
7023             }
7024         }
7025         return null;
7026     }
7027 
7028     /**
7029      * Returns the VPN package name if the admin has enabled always-on VPN on the current user,
7030      * or {@code null} if none is set.
7031      *
7032      * Only callable by the system.
7033      * @hide
7034      */
7035     @UserHandleAware
getAlwaysOnVpnPackage()7036     public @Nullable String getAlwaysOnVpnPackage() {
7037         throwIfParentInstance("getAlwaysOnVpnPackage");
7038         if (mService != null) {
7039             try {
7040                 return mService.getAlwaysOnVpnPackageForUser(myUserId());
7041             } catch (RemoteException e) {
7042                 throw e.rethrowFromSystemServer();
7043             }
7044         }
7045         return null;
7046     }
7047 
7048     /**
7049      * Called by an application that is administering the device to disable all cameras on the
7050      * device, for this user. After setting this, no applications running as this user will be able
7051      * to access any cameras on the device.
7052      * <p>
7053      * This method can be called on the {@link DevicePolicyManager} instance,
7054      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
7055      * the profile owner of an organization-owned managed profile.
7056      * <p>
7057      * If the caller is device owner, then the restriction will be applied to all users. If
7058      * called on the parent instance, then the restriction will be applied on the personal profile.
7059      * <p>
7060      * The calling device admin must have requested
7061      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
7062      * not, a security exception will be thrown.
7063      * <p>
7064      * <b>Note</b>, this policy type is deprecated for legacy device admins since
7065      * {@link android.os.Build.VERSION_CODES#Q}. On Android
7066      * {@link android.os.Build.VERSION_CODES#Q} devices, legacy device admins targeting SDK
7067      * version {@link android.os.Build.VERSION_CODES#P} or below can still call this API to
7068      * disable camera, while legacy device admins targeting SDK version
7069      * {@link android.os.Build.VERSION_CODES#Q} will receive a SecurityException. Starting
7070      * from Android {@link android.os.Build.VERSION_CODES#R}, requests to disable camera from
7071      * legacy device admins targeting SDK version {@link android.os.Build.VERSION_CODES#P} or
7072      * below will be silently ignored.
7073      *
7074      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7075      * @param disabled Whether or not the camera should be disabled.
7076      * @throws SecurityException if {@code admin} is not an active administrator or does not use
7077      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
7078      */
setCameraDisabled(@onNull ComponentName admin, boolean disabled)7079     public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
7080         if (mService != null) {
7081             try {
7082                 mService.setCameraDisabled(admin, disabled, mParentInstance);
7083             } catch (RemoteException e) {
7084                 throw e.rethrowFromSystemServer();
7085             }
7086         }
7087     }
7088 
7089     /**
7090      * Determine whether or not the device's cameras have been disabled for this user,
7091      * either by the calling admin, if specified, or all admins.
7092      * <p>
7093      * This method can be called on the {@link DevicePolicyManager} instance,
7094      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
7095      * the profile owner of an organization-owned managed profile.
7096      *
7097      * @param admin The name of the admin component to check, or {@code null} to check whether any admins
7098      * have disabled the camera
7099      */
getCameraDisabled(@ullable ComponentName admin)7100     public boolean getCameraDisabled(@Nullable ComponentName admin) {
7101         return getCameraDisabled(admin, myUserId());
7102     }
7103 
7104     /** @hide per-user version */
7105     @UnsupportedAppUsage
getCameraDisabled(@ullable ComponentName admin, int userHandle)7106     public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
7107         if (mService != null) {
7108             try {
7109                 return mService.getCameraDisabled(admin, userHandle, mParentInstance);
7110             } catch (RemoteException e) {
7111                 throw e.rethrowFromSystemServer();
7112             }
7113         }
7114         return false;
7115     }
7116 
7117     /**
7118      * Called by a device owner to request a bugreport.
7119      * <p>
7120      * If the device contains secondary users or profiles, they must be affiliated with the device.
7121      * Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
7122      *
7123      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7124      * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
7125      *         wasn't triggered because a previous bugreport operation is still active (either the
7126      *         bugreport is still running or waiting for the user to share or decline)
7127      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
7128      *         profile or secondary user that is not affiliated with the device.
7129      * @see #isAffiliatedUser
7130      */
requestBugreport(@onNull ComponentName admin)7131     public boolean requestBugreport(@NonNull ComponentName admin) {
7132         throwIfParentInstance("requestBugreport");
7133         if (mService != null) {
7134             try {
7135                 return mService.requestBugreport(admin);
7136             } catch (RemoteException e) {
7137                 throw e.rethrowFromSystemServer();
7138             }
7139         }
7140         return false;
7141     }
7142 
7143     /**
7144      * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
7145      * screen capture also prevents the content from being shown on display devices that do not have
7146      * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
7147      * secure surfaces and secure displays.
7148      * <p>
7149      * This method can be called on the {@link DevicePolicyManager} instance, returned by
7150      * {@link #getParentProfileInstance(ComponentName)}, where the calling device admin must be
7151      * the profile owner of an organization-owned managed profile. If it is not, a security
7152      * exception will be thrown.
7153      * <p>
7154      * If the caller is device owner or called on the parent instance by a profile owner of an
7155      * organization-owned managed profile, then the restriction will be applied to all users.
7156      * <p>
7157      * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
7158      * assist requests for all activities of the relevant user.
7159      *
7160      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7161      * @param disabled Whether screen capture is disabled or not.
7162      * @throws SecurityException if {@code admin} is not a device or profile owner or if
7163      *                           called on the parent profile and the {@code admin} is not a
7164      *                           profile owner of an organization-owned managed profile.
7165      */
setScreenCaptureDisabled(@onNull ComponentName admin, boolean disabled)7166     public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
7167         if (mService != null) {
7168             try {
7169                 mService.setScreenCaptureDisabled(admin, disabled, mParentInstance);
7170             } catch (RemoteException e) {
7171                 throw e.rethrowFromSystemServer();
7172             }
7173         }
7174     }
7175 
7176     /**
7177      * Determine whether or not screen capture has been disabled by the calling
7178      * admin, if specified, or all admins.
7179      * <p>
7180      * This method can be called on the {@link DevicePolicyManager} instance,
7181      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
7182      * the profile owner of an organization-owned managed profile (the calling admin must be
7183      * specified).
7184      *
7185      * @param admin The name of the admin component to check, or {@code null} to check whether any
7186      *              admins have disabled screen capture.
7187      */
getScreenCaptureDisabled(@ullable ComponentName admin)7188     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
7189         return getScreenCaptureDisabled(admin, myUserId());
7190     }
7191 
7192     /** @hide per-user version */
getScreenCaptureDisabled(@ullable ComponentName admin, int userHandle)7193     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
7194         if (mService != null) {
7195             try {
7196                 return mService.getScreenCaptureDisabled(admin, userHandle, mParentInstance);
7197             } catch (RemoteException e) {
7198                 throw e.rethrowFromSystemServer();
7199             }
7200         }
7201         return false;
7202     }
7203 
7204     /**
7205      * Called by a device/profile owner to set nearby notification streaming policy. Notification
7206      * streaming is sending notification data from pre-installed apps to nearby devices.
7207      *
7208      * @param policy One of the {@code NearbyStreamingPolicy} constants.
7209      * @throws SecurityException if caller is not a device or profile owner
7210      */
setNearbyNotificationStreamingPolicy(@earbyStreamingPolicy int policy)7211     public void setNearbyNotificationStreamingPolicy(@NearbyStreamingPolicy int policy) {
7212         throwIfParentInstance("setNearbyNotificationStreamingPolicy");
7213         if (mService == null) {
7214             return;
7215         }
7216         try {
7217             mService.setNearbyNotificationStreamingPolicy(policy);
7218         } catch (RemoteException e) {
7219             throw e.rethrowFromSystemServer();
7220         }
7221     }
7222 
7223     /**
7224      * Returns the current runtime nearby notification streaming policy set by the device or profile
7225      * owner.
7226      */
getNearbyNotificationStreamingPolicy()7227     public @NearbyStreamingPolicy int getNearbyNotificationStreamingPolicy() {
7228         return getNearbyNotificationStreamingPolicy(myUserId());
7229     }
7230 
7231     /** @hide per-user version */
getNearbyNotificationStreamingPolicy(int userId)7232     public @NearbyStreamingPolicy int getNearbyNotificationStreamingPolicy(int userId) {
7233         throwIfParentInstance("getNearbyNotificationStreamingPolicy");
7234         if (mService == null) {
7235             return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
7236         }
7237         try {
7238             return mService.getNearbyNotificationStreamingPolicy(userId);
7239         } catch (RemoteException re) {
7240             throw re.rethrowFromSystemServer();
7241         }
7242     }
7243 
7244     /**
7245      * Called by a device/profile owner to set nearby app streaming policy. App streaming is when
7246      * the device starts an app on a virtual display and sends a video stream of the app to nearby
7247      * devices.
7248      *
7249      * @param policy One of the {@code NearbyStreamingPolicy} constants.
7250      * @throws SecurityException if caller is not a device or profile owner.
7251      */
setNearbyAppStreamingPolicy(@earbyStreamingPolicy int policy)7252     public void setNearbyAppStreamingPolicy(@NearbyStreamingPolicy int policy) {
7253         throwIfParentInstance("setNearbyAppStreamingPolicy");
7254         if (mService == null) {
7255             return;
7256         }
7257         try {
7258             mService.setNearbyAppStreamingPolicy(policy);
7259         } catch (RemoteException e) {
7260             throw e.rethrowFromSystemServer();
7261         }
7262     }
7263 
7264     /**
7265      * Returns the current runtime nearby app streaming policy set by the device or profile owner.
7266      */
getNearbyAppStreamingPolicy()7267     public @NearbyStreamingPolicy int getNearbyAppStreamingPolicy() {
7268         return getNearbyAppStreamingPolicy(myUserId());
7269     }
7270 
7271     /** @hide per-user version */
getNearbyAppStreamingPolicy(int userId)7272     public @NearbyStreamingPolicy int getNearbyAppStreamingPolicy(int userId) {
7273         throwIfParentInstance("getNearbyAppStreamingPolicy");
7274         if (mService == null) {
7275             return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
7276         }
7277         try {
7278             return mService.getNearbyAppStreamingPolicy(userId);
7279         } catch (RemoteException re) {
7280             throw re.rethrowFromSystemServer();
7281         }
7282     }
7283 
7284     /**
7285      * Called by a device owner, or alternatively a profile owner from Android 8.0 (API level 26) or
7286      * higher, to set whether auto time is required. If auto time is required, no user will be able
7287      * set the date and time and network date and time will be used.
7288      * <p>
7289      * Note: if auto time is required the user can still manually set the time zone.
7290      * <p>
7291      * The calling device admin must be a device owner, or alternatively a profile owner from
7292      * Android 8.0 (API level 26) or higher. If it is not, a security exception will be thrown.
7293      * <p>
7294      * Staring from Android 11, this API switches to use
7295      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} to enforce the auto time settings. Calling
7296      * this API to enforce auto time will result in
7297      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being set, while calling this API to lift
7298      * the requirement will result in {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being cleared.
7299      * From Android 11, this API can also no longer be called on a managed profile.
7300      *
7301      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7302      * @param required Whether auto time is set required or not.
7303      * @throws SecurityException if {@code admin} is not a device owner, not a profile owner or
7304      * if this API is called on a managed profile.
7305      * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #setAutoTimeEnabled}
7306      * to turn auto time on or off and use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
7307      * to prevent the user from changing this setting.
7308      */
7309     @Deprecated
setAutoTimeRequired(@onNull ComponentName admin, boolean required)7310     public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
7311         throwIfParentInstance("setAutoTimeRequired");
7312         if (mService != null) {
7313             try {
7314                 mService.setAutoTimeRequired(admin, required);
7315             } catch (RemoteException e) {
7316                 throw e.rethrowFromSystemServer();
7317             }
7318         }
7319     }
7320 
7321     /**
7322      * @return true if auto time is required.
7323      * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #getAutoTimeEnabled}
7324      */
7325     @Deprecated
getAutoTimeRequired()7326     public boolean getAutoTimeRequired() {
7327         throwIfParentInstance("getAutoTimeRequired");
7328         if (mService != null) {
7329             try {
7330                 return mService.getAutoTimeRequired();
7331             } catch (RemoteException e) {
7332                 throw e.rethrowFromSystemServer();
7333             }
7334         }
7335         return false;
7336     }
7337 
7338     /**
7339      * Called by a device owner, a profile owner for the primary user or a profile
7340      * owner of an organization-owned managed profile to turn auto time on and off.
7341      * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
7342      * to prevent the user from changing this setting.
7343      * <p>
7344      * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
7345      * no user will be able set the date and time. Instead, the network date
7346      * and time will be used.
7347      *
7348      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7349      * @param enabled Whether time should be obtained automatically from the network or not.
7350      * @throws SecurityException if caller is not a device owner, a profile owner for the
7351      * primary user, or a profile owner of an organization-owned managed profile.
7352      */
setAutoTimeEnabled(@onNull ComponentName admin, boolean enabled)7353     public void setAutoTimeEnabled(@NonNull ComponentName admin, boolean enabled) {
7354         if (mService != null) {
7355             try {
7356                 mService.setAutoTimeEnabled(admin, enabled);
7357             } catch (RemoteException e) {
7358                 throw e.rethrowFromSystemServer();
7359             }
7360         }
7361     }
7362 
7363     /**
7364      * @return true if auto time is enabled on the device.
7365      * @throws SecurityException if caller is not a device owner, a profile owner for the
7366      * primary user, or a profile owner of an organization-owned managed profile.
7367      */
getAutoTimeEnabled(@onNull ComponentName admin)7368     public boolean getAutoTimeEnabled(@NonNull ComponentName admin) {
7369         if (mService != null) {
7370             try {
7371                 return mService.getAutoTimeEnabled(admin);
7372             } catch (RemoteException e) {
7373                 throw e.rethrowFromSystemServer();
7374             }
7375         }
7376         return false;
7377     }
7378 
7379     /**
7380      * Called by a device owner, a profile owner for the primary user or a profile
7381      * owner of an organization-owned managed profile to turn auto time zone on and off.
7382      * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
7383      * to prevent the user from changing this setting.
7384      * <p>
7385      * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
7386      * no user will be able set the date and time zone. Instead, the network date
7387      * and time zone will be used.
7388      *
7389      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7390      * @param enabled Whether time zone should be obtained automatically from the network or not.
7391      * @throws SecurityException if caller is not a device owner, a profile owner for the
7392      * primary user, or a profile owner of an organization-owned managed profile.
7393      */
setAutoTimeZoneEnabled(@onNull ComponentName admin, boolean enabled)7394     public void setAutoTimeZoneEnabled(@NonNull ComponentName admin, boolean enabled) {
7395         throwIfParentInstance("setAutoTimeZone");
7396         if (mService != null) {
7397             try {
7398                 mService.setAutoTimeZoneEnabled(admin, enabled);
7399             } catch (RemoteException e) {
7400                 throw e.rethrowFromSystemServer();
7401             }
7402         }
7403     }
7404 
7405     /**
7406      * @return true if auto time zone is enabled on the device.
7407      * @throws SecurityException if caller is not a device owner, a profile owner for the
7408      * primary user, or a profile owner of an organization-owned managed profile.
7409      */
getAutoTimeZoneEnabled(@onNull ComponentName admin)7410     public boolean getAutoTimeZoneEnabled(@NonNull ComponentName admin) {
7411         throwIfParentInstance("getAutoTimeZone");
7412         if (mService != null) {
7413             try {
7414                 return mService.getAutoTimeZoneEnabled(admin);
7415             } catch (RemoteException e) {
7416                 throw e.rethrowFromSystemServer();
7417             }
7418         }
7419         return false;
7420     }
7421 
7422     /**
7423      * TODO (b/137101239): remove this method in follow-up CL
7424      * since it's only used for split system user.
7425      * Called by a device owner to set whether all users created on the device should be ephemeral.
7426      * @hide
7427      */
setForceEphemeralUsers( @onNull ComponentName admin, boolean forceEphemeralUsers)7428     public void setForceEphemeralUsers(
7429             @NonNull ComponentName admin, boolean forceEphemeralUsers) {
7430         throwIfParentInstance("setForceEphemeralUsers");
7431         if (mService != null) {
7432             try {
7433                 mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
7434             } catch (RemoteException e) {
7435                 throw e.rethrowFromSystemServer();
7436             }
7437         }
7438     }
7439 
7440     /**
7441      * TODO (b/137101239): remove this method in follow-up CL
7442      * since it's only used for split system user.
7443      * @return true if all users are created ephemeral.
7444      * @throws SecurityException if {@code admin} is not a device owner.
7445      * @hide
7446      */
getForceEphemeralUsers(@onNull ComponentName admin)7447     public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
7448         throwIfParentInstance("getForceEphemeralUsers");
7449         if (mService != null) {
7450             try {
7451                 return mService.getForceEphemeralUsers(admin);
7452             } catch (RemoteException e) {
7453                 throw e.rethrowFromSystemServer();
7454             }
7455         }
7456         return false;
7457     }
7458 
7459     /**
7460      * Called by an application that is administering the device to disable keyguard customizations,
7461      * such as widgets. After setting this, keyguard features will be disabled according to the
7462      * provided feature list.
7463      * <p>
7464      * The calling device admin must have requested
7465      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
7466      * if it has not, a security exception will be thrown.
7467      * <p>
7468      * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
7469      * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
7470      * profile owner of a managed profile can set:
7471      * <ul>
7472      * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
7473      * is no separate challenge set on the managed profile.
7474      * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FACE} or
7475      * {@link #KEYGUARD_DISABLE_IRIS} which affects the managed profile challenge if
7476      * there is one, or the parent user otherwise.
7477      * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
7478      * by applications in the managed profile.
7479      * </ul>
7480      * <p>
7481      * From version {@link android.os.Build.VERSION_CODES#R} the profile owner of an
7482      * organization-owned managed profile can set:
7483      * <ul>
7484      * <li>{@link #KEYGUARD_DISABLE_SECURE_CAMERA} which affects the parent user when called on the
7485      * parent profile.
7486      * <li>{@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS} which affects the parent user when called
7487      * on the parent profile.
7488      * </ul>
7489      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, {@link #KEYGUARD_DISABLE_FINGERPRINT},
7490      * {@link #KEYGUARD_DISABLE_FACE}, {@link #KEYGUARD_DISABLE_IRIS},
7491      * {@link #KEYGUARD_DISABLE_SECURE_CAMERA} and {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS}
7492      * can also be set on the {@link DevicePolicyManager} instance returned by
7493      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
7494      * profile. {@link #KEYGUARD_DISABLE_SECURE_CAMERA} can only be set on the parent profile
7495      * instance if the calling device admin is the profile owner of an organization-owned
7496      * managed profile.
7497      * <p>
7498      * Requests to disable other features on a managed profile will be ignored.
7499      * <p>
7500      * The admin can check which features have been disabled by calling
7501      * {@link #getKeyguardDisabledFeatures(ComponentName)}
7502      *
7503      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7504      * @param which The disabled features flag which can be either
7505      *            {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
7506      *            {@link #KEYGUARD_DISABLE_FEATURES_ALL}, or a combination of
7507      *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
7508      *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
7509      *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
7510      *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
7511      *            {@link #KEYGUARD_DISABLE_FINGERPRINT},
7512      *            {@link #KEYGUARD_DISABLE_FACE},
7513      *            {@link #KEYGUARD_DISABLE_IRIS}.
7514      * @throws SecurityException if {@code admin} is not an active administrator or does not user
7515      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
7516      */
setKeyguardDisabledFeatures(@onNull ComponentName admin, int which)7517     public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
7518         if (mService != null) {
7519             try {
7520                 mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
7521             } catch (RemoteException e) {
7522                 throw e.rethrowFromSystemServer();
7523             }
7524         }
7525     }
7526 
7527     /**
7528      * Determine whether or not features have been disabled in keyguard either by the calling
7529      * admin, if specified, or all admins that set restrictions on this user and its participating
7530      * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
7531      *
7532      * <p>This method can be called on the {@link DevicePolicyManager} instance
7533      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
7534      * restrictions on the parent profile.
7535      *
7536      * @param admin The name of the admin component to check, or {@code null} to check whether any
7537      * admins have disabled features in keyguard.
7538      * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
7539      * for a list.
7540      */
getKeyguardDisabledFeatures(@ullable ComponentName admin)7541     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
7542         return getKeyguardDisabledFeatures(admin, myUserId());
7543     }
7544 
7545     /** @hide per-user version */
7546     @UnsupportedAppUsage
getKeyguardDisabledFeatures(@ullable ComponentName admin, int userHandle)7547     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
7548         if (mService != null) {
7549             try {
7550                 return mService.getKeyguardDisabledFeatures(admin, userHandle, mParentInstance);
7551             } catch (RemoteException e) {
7552                 throw e.rethrowFromSystemServer();
7553             }
7554         }
7555         return KEYGUARD_DISABLE_FEATURES_NONE;
7556     }
7557 
7558     /**
7559      * @hide
7560      */
7561     @TestApi
7562     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
7563     @RequiresPermission(allOf = {
7564             android.Manifest.permission.MANAGE_DEVICE_ADMINS,
7565             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL
7566     })
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing, int userHandle)7567     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
7568             int userHandle) {
7569         if (mService != null) {
7570             try {
7571                 mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
7572             } catch (RemoteException e) {
7573                 throw e.rethrowFromSystemServer();
7574             }
7575         }
7576     }
7577 
7578     /**
7579      * @hide
7580      */
7581     @UnsupportedAppUsage
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing)7582     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
7583         setActiveAdmin(policyReceiver, refreshing, myUserId());
7584     }
7585 
7586     /**
7587      * Called by a privileged caller holding {@code BIND_DEVICE_ADMIN} permission to retrieve
7588      * the remove warning for the given device admin.
7589      * @hide
7590      */
getRemoveWarning(@ullable ComponentName admin, RemoteCallback result)7591     public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
7592         if (mService != null) {
7593             try {
7594                 mService.getRemoveWarning(admin, result, myUserId());
7595             } catch (RemoteException e) {
7596                 throw e.rethrowFromSystemServer();
7597             }
7598         }
7599     }
7600 
7601     /**
7602      * @hide
7603      */
7604     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportPasswordChanged(@serIdInt int userId)7605     public void reportPasswordChanged(@UserIdInt int userId) {
7606         if (mService != null) {
7607             try {
7608                 mService.reportPasswordChanged(userId);
7609             } catch (RemoteException e) {
7610                 throw e.rethrowFromSystemServer();
7611             }
7612         }
7613     }
7614 
7615     /**
7616      * @hide
7617      */
7618     @UnsupportedAppUsage
7619     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedPasswordAttempt(int userHandle)7620     public void reportFailedPasswordAttempt(int userHandle) {
7621         if (mService != null) {
7622             try {
7623                 mService.reportFailedPasswordAttempt(userHandle);
7624             } catch (RemoteException e) {
7625                 throw e.rethrowFromSystemServer();
7626             }
7627         }
7628     }
7629 
7630     /**
7631      * @hide
7632      */
7633     @UnsupportedAppUsage
7634     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulPasswordAttempt(int userHandle)7635     public void reportSuccessfulPasswordAttempt(int userHandle) {
7636         if (mService != null) {
7637             try {
7638                 mService.reportSuccessfulPasswordAttempt(userHandle);
7639             } catch (RemoteException e) {
7640                 throw e.rethrowFromSystemServer();
7641             }
7642         }
7643     }
7644 
7645     /**
7646      * @hide
7647      */
7648     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedBiometricAttempt(int userHandle)7649     public void reportFailedBiometricAttempt(int userHandle) {
7650         if (mService != null) {
7651             try {
7652                 mService.reportFailedBiometricAttempt(userHandle);
7653             } catch (RemoteException e) {
7654                 throw e.rethrowFromSystemServer();
7655             }
7656         }
7657     }
7658 
7659     /**
7660      * @hide
7661      */
7662     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulBiometricAttempt(int userHandle)7663     public void reportSuccessfulBiometricAttempt(int userHandle) {
7664         if (mService != null) {
7665             try {
7666                 mService.reportSuccessfulBiometricAttempt(userHandle);
7667             } catch (RemoteException e) {
7668                 throw e.rethrowFromSystemServer();
7669             }
7670         }
7671     }
7672 
7673     /**
7674      * Should be called when keyguard has been dismissed.
7675      * @hide
7676      */
reportKeyguardDismissed(int userHandle)7677     public void reportKeyguardDismissed(int userHandle) {
7678         if (mService != null) {
7679             try {
7680                 mService.reportKeyguardDismissed(userHandle);
7681             } catch (RemoteException e) {
7682                 throw e.rethrowFromSystemServer();
7683             }
7684         }
7685     }
7686 
7687     /**
7688      * Should be called when keyguard view has been shown to the user.
7689      * @hide
7690      */
reportKeyguardSecured(int userHandle)7691     public void reportKeyguardSecured(int userHandle) {
7692         if (mService != null) {
7693             try {
7694                 mService.reportKeyguardSecured(userHandle);
7695             } catch (RemoteException e) {
7696                 throw e.rethrowFromSystemServer();
7697             }
7698         }
7699     }
7700 
7701     /**
7702      * @hide
7703      * Sets the given package as the device owner.
7704      * Same as {@link #setDeviceOwner(ComponentName, String)} but without setting a device owner name.
7705      * @param who the component name to be registered as device owner.
7706      * @return whether the package was successfully registered as the device owner.
7707      * @throws IllegalArgumentException if the package name is null or invalid
7708      * @throws IllegalStateException If the preconditions mentioned are not met.
7709      */
setDeviceOwner(ComponentName who)7710     public boolean setDeviceOwner(ComponentName who) {
7711         return setDeviceOwner(who, null);
7712     }
7713 
7714     /**
7715      * @hide
7716      */
setDeviceOwner(ComponentName who, int userId)7717     public boolean setDeviceOwner(ComponentName who, int userId)  {
7718         return setDeviceOwner(who, null, userId);
7719     }
7720 
7721     /**
7722      * @hide
7723      */
setDeviceOwner(ComponentName who, String ownerName)7724     public boolean setDeviceOwner(ComponentName who, String ownerName) {
7725         return setDeviceOwner(who, ownerName, UserHandle.USER_SYSTEM);
7726     }
7727 
7728     /**
7729      * @hide
7730      * Sets the given package as the device owner. The package must already be installed. There
7731      * must not already be a device owner.
7732      * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
7733      * this method.
7734      * Calling this after the setup phase of the primary user has completed is allowed only if
7735      * the caller is the shell uid, and there are no additional users and no accounts.
7736      * @param who the component name to be registered as device owner.
7737      * @param ownerName the human readable name of the institution that owns this device.
7738      * @param userId ID of the user on which the device owner runs.
7739      * @return whether the package was successfully registered as the device owner.
7740      * @throws IllegalArgumentException if the package name is null or invalid
7741      * @throws IllegalStateException If the preconditions mentioned are not met.
7742      */
7743     @TestApi
7744     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setDeviceOwner( @onNull ComponentName who, @Nullable String ownerName, @UserIdInt int userId)7745     public boolean setDeviceOwner(
7746             @NonNull ComponentName who, @Nullable String ownerName, @UserIdInt int userId) {
7747         if (mService != null) {
7748             try {
7749                 return mService.setDeviceOwner(who, ownerName, userId);
7750             } catch (RemoteException re) {
7751                 throw re.rethrowFromSystemServer();
7752             }
7753         }
7754         return false;
7755     }
7756 
7757     /**
7758      * Used to determine if a particular package has been registered as a Device Owner app.
7759      * A device owner app is a special device admin that cannot be deactivated by the user, once
7760      * activated as a device admin. It also cannot be uninstalled. To check whether a particular
7761      * package is currently registered as the device owner app, pass in the package name from
7762      * {@link Context#getPackageName()} to this method.<p/>This is useful for device
7763      * admin apps that want to check whether they are also registered as the device owner app. The
7764      * exact mechanism by which a device admin app is registered as a device owner app is defined by
7765      * the setup process.
7766      * @param packageName the package name of the app, to compare with the registered device owner
7767      * app, if any.
7768      * @return whether or not the package is registered as the device owner app.
7769      */
isDeviceOwnerApp(String packageName)7770     public boolean isDeviceOwnerApp(String packageName) {
7771         throwIfParentInstance("isDeviceOwnerApp");
7772         return isDeviceOwnerAppOnCallingUser(packageName);
7773     }
7774 
7775     /**
7776      * @return true if a package is registered as device owner, only when it's running on the
7777      * calling user.
7778      *
7779      * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
7780      * @hide
7781      */
isDeviceOwnerAppOnCallingUser(String packageName)7782     public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
7783         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
7784     }
7785 
7786     /**
7787      * @return true if a package is registered as device owner, even if it's running on a different
7788      * user.
7789      *
7790      * <p>Requires the MANAGE_USERS permission.
7791      *
7792      * @hide
7793      */
isDeviceOwnerAppOnAnyUser(String packageName)7794     public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
7795         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
7796     }
7797 
7798     /**
7799      * @return device owner component name, only when it's running on the calling user.
7800      *
7801      * @hide
7802      */
getDeviceOwnerComponentOnCallingUser()7803     public ComponentName getDeviceOwnerComponentOnCallingUser() {
7804         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
7805     }
7806 
7807     /**
7808      * @return device owner component name, even if it's running on a different user.
7809      *
7810      * @hide
7811      */
7812     @SystemApi
7813     @RequiresPermission(anyOf = {
7814             android.Manifest.permission.MANAGE_USERS,
7815             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
7816     })
getDeviceOwnerComponentOnAnyUser()7817     public ComponentName getDeviceOwnerComponentOnAnyUser() {
7818         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
7819     }
7820 
isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly)7821     private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
7822         if (packageName == null) {
7823             return false;
7824         }
7825         final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
7826         if (deviceOwner == null) {
7827             return false;
7828         }
7829         return packageName.equals(deviceOwner.getPackageName());
7830     }
7831 
getDeviceOwnerComponentInner(boolean callingUserOnly)7832     private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
7833         if (mService != null) {
7834             try {
7835                 return mService.getDeviceOwnerComponent(callingUserOnly);
7836             } catch (RemoteException re) {
7837                 throw re.rethrowFromSystemServer();
7838             }
7839         }
7840         return null;
7841     }
7842 
7843     /**
7844      * @return Handle of the user who runs device owner, or {@code null} if there's no device owner.
7845      *
7846      * @hide
7847      */
7848     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
7849     @SystemApi
getDeviceOwnerUser()7850     public @Nullable UserHandle getDeviceOwnerUser() {
7851         if (mService != null) {
7852             try {
7853                 int userId = mService.getDeviceOwnerUserId();
7854 
7855                 if (userId != UserHandle.USER_NULL) {
7856                     return UserHandle.of(userId);
7857                 }
7858             } catch (RemoteException re) {
7859                 throw re.rethrowFromSystemServer();
7860             }
7861         }
7862         return null;
7863     }
7864 
7865     /**
7866      * @hide
7867      */
getDeviceOwnerUserId()7868     public int getDeviceOwnerUserId() {
7869         if (mService != null) {
7870             try {
7871                 return mService.getDeviceOwnerUserId();
7872             } catch (RemoteException re) {
7873                 throw re.rethrowFromSystemServer();
7874             }
7875         }
7876         return UserHandle.USER_NULL;
7877     }
7878 
7879     /**
7880      * Clears the current device owner. The caller must be the device owner. This function should be
7881      * used cautiously as once it is called it cannot be undone. The device owner can only be set as
7882      * a part of device setup, before it completes.
7883      * <p>
7884      * While some policies previously set by the device owner will be cleared by this method, it is
7885      * a best-effort process and some other policies will still remain in place after the device
7886      * owner is cleared.
7887      *
7888      * @param packageName The package name of the device owner.
7889      * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
7890      *             does not own the current device owner component.
7891      *
7892      * @deprecated This method is expected to be used for testing purposes only. The device owner
7893      * will lose control of the device and its data after calling it. In order to protect any
7894      * sensitive data that remains on the device, it is advised that the device owner factory resets
7895      * the device instead of calling this method. See {@link #wipeData(int)}.
7896      */
7897     @Deprecated
clearDeviceOwnerApp(String packageName)7898     public void clearDeviceOwnerApp(String packageName) {
7899         throwIfParentInstance("clearDeviceOwnerApp");
7900         if (mService != null) {
7901             try {
7902                 mService.clearDeviceOwner(packageName);
7903             } catch (RemoteException re) {
7904                 throw re.rethrowFromSystemServer();
7905             }
7906         }
7907     }
7908 
7909     /**
7910      * Returns the device owner package name, only if it's running on the calling user.
7911      *
7912      * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
7913      *
7914      * @hide
7915      */
7916     @SystemApi
7917     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwner()7918     public @Nullable String getDeviceOwner() {
7919         throwIfParentInstance("getDeviceOwner");
7920         final ComponentName name = getDeviceOwnerComponentOnCallingUser();
7921         return name != null ? name.getPackageName() : null;
7922     }
7923 
7924     /**
7925      * Called by the system to find out whether the device is managed by a Device Owner.
7926      *
7927      * @return whether the device is managed by a Device Owner.
7928      * @throws SecurityException if the caller is not the device owner, does not hold the
7929      *         MANAGE_USERS permission and is not the system.
7930      *
7931      * @hide
7932      */
7933     @SystemApi
7934     @SuppressLint("RequiresPermission")
isDeviceManaged()7935     public boolean isDeviceManaged() {
7936         try {
7937             return mService.hasDeviceOwner();
7938         } catch (RemoteException re) {
7939             throw re.rethrowFromSystemServer();
7940         }
7941     }
7942 
7943     /**
7944      * Returns the device owner name.  Note this method *will* return the device owner
7945      * name when it's running on a different user.
7946      *
7947      * @hide
7948      */
7949     @SystemApi
7950     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwnerNameOnAnyUser()7951     public String getDeviceOwnerNameOnAnyUser() {
7952         throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
7953         if (mService != null) {
7954             try {
7955                 return mService.getDeviceOwnerName();
7956             } catch (RemoteException re) {
7957                 throw re.rethrowFromSystemServer();
7958             }
7959         }
7960         return null;
7961     }
7962 
7963     /**
7964      * @hide
7965      * @deprecated Use #ACTION_SET_PROFILE_OWNER
7966      * Sets the given component as an active admin and registers the package as the profile
7967      * owner for this user. The package must already be installed and there shouldn't be
7968      * an existing profile owner registered for this user. Also, this method must be called
7969      * before the user setup has been completed.
7970      * <p>
7971      * This method can only be called by system apps that hold MANAGE_USERS permission and
7972      * MANAGE_DEVICE_ADMINS permission.
7973      * @param admin The component to register as an active admin and profile owner.
7974      * @param ownerName The user-visible name of the entity that is managing this user.
7975      * @return whether the admin was successfully registered as the profile owner.
7976      * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
7977      *         the user has already been set up.
7978      */
7979     @Deprecated
7980     @SystemApi
7981     @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
setActiveProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName)7982     public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
7983             throws IllegalArgumentException {
7984         throwIfParentInstance("setActiveProfileOwner");
7985         if (mService != null) {
7986             try {
7987                 final int myUserId = myUserId();
7988                 mService.setActiveAdmin(admin, false, myUserId);
7989                 return mService.setProfileOwner(admin, ownerName, myUserId);
7990             } catch (RemoteException re) {
7991                 throw re.rethrowFromSystemServer();
7992             }
7993         }
7994         return false;
7995     }
7996 
7997     /**
7998      * Clears the active profile owner. The caller must be the profile owner of this user, otherwise
7999      * a SecurityException will be thrown. This method is not available to managed profile owners.
8000      * <p>
8001      * While some policies previously set by the profile owner will be cleared by this method, it is
8002      * a best-effort process and some other policies will still remain in place after the profile
8003      * owner is cleared.
8004      *
8005      * @param admin The component to remove as the profile owner.
8006      * @throws SecurityException if {@code admin} is not an active profile owner, or the method is
8007      * being called from a managed profile.
8008      *
8009      * @deprecated This method is expected to be used for testing purposes only. The profile owner
8010      * will lose control of the user and its data after calling it. In order to protect any
8011      * sensitive data that remains on this user, it is advised that the profile owner deletes it
8012      * instead of calling this method. See {@link #wipeData(int)}.
8013      */
8014     @Deprecated
clearProfileOwner(@onNull ComponentName admin)8015     public void clearProfileOwner(@NonNull ComponentName admin) {
8016         throwIfParentInstance("clearProfileOwner");
8017         if (mService != null) {
8018             try {
8019                 mService.clearProfileOwner(admin);
8020             } catch (RemoteException re) {
8021                 throw re.rethrowFromSystemServer();
8022             }
8023         }
8024     }
8025 
8026     /**
8027      * @hide
8028      * Checks whether the user was already setup.
8029      */
hasUserSetupCompleted()8030     public boolean hasUserSetupCompleted() {
8031         if (mService != null) {
8032             try {
8033                 return mService.hasUserSetupCompleted();
8034             } catch (RemoteException re) {
8035                 throw re.rethrowFromSystemServer();
8036             }
8037         }
8038         return true;
8039     }
8040 
8041     /**
8042      * @hide
8043      * Sets the given component as the profile owner of the given user profile. The package must
8044      * already be installed. There must not already be a profile owner for this user.
8045      * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
8046      * this method.
8047      * Calling this after the setup phase of the specified user has completed is allowed only if:
8048      * - the caller is SYSTEM_UID.
8049      * - or the caller is the shell uid, and there are no accounts on the specified user.
8050      * @param admin the component name to be registered as profile owner.
8051      * @param ownerName the human readable name of the organisation associated with this DPM.
8052      * @param userHandle the userId to set the profile owner for.
8053      * @return whether the component was successfully registered as the profile owner.
8054      * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
8055      * preconditions mentioned are not met.
8056      */
setProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName, int userHandle)8057     public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
8058             int userHandle) throws IllegalArgumentException {
8059         if (mService != null) {
8060             try {
8061                 if (ownerName == null) {
8062                     ownerName = "";
8063                 }
8064                 return mService.setProfileOwner(admin, ownerName, userHandle);
8065             } catch (RemoteException re) {
8066                 throw re.rethrowFromSystemServer();
8067             }
8068         }
8069         return false;
8070     }
8071 
8072     /**
8073      * Sets the device owner information to be shown on the lock screen.
8074      * <p>
8075      * Device owner information set using this method overrides any owner information manually set
8076      * by the user and prevents the user from further changing it.
8077      * <p>
8078      * If the device owner information is {@code null} or empty then the device owner info is
8079      * cleared and the user owner info is shown on the lock screen if it is set.
8080      * <p>
8081      * If the device owner information contains only whitespaces then the message on the lock screen
8082      * will be blank and the user will not be allowed to change it.
8083      * <p>
8084      * If the device owner information needs to be localized, it is the responsibility of the
8085      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
8086      * and set a new version of this string accordingly.
8087      * <p>
8088      * May be called by the device owner or the profile owner of an organization-owned device.
8089      *
8090      * @param admin The name of the admin component to check.
8091      * @param info Device owner information which will be displayed instead of the user owner info.
8092      * @throws SecurityException if {@code admin} is not a device owner.
8093      */
setDeviceOwnerLockScreenInfo(@onNull ComponentName admin, CharSequence info)8094     public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
8095         throwIfParentInstance("setDeviceOwnerLockScreenInfo");
8096         if (mService != null) {
8097             try {
8098                 mService.setDeviceOwnerLockScreenInfo(admin, info);
8099             } catch (RemoteException re) {
8100                 throw re.rethrowFromSystemServer();
8101             }
8102         }
8103     }
8104 
8105     /**
8106      * @return The device owner information. If it is not set returns {@code null}.
8107      */
getDeviceOwnerLockScreenInfo()8108     public CharSequence getDeviceOwnerLockScreenInfo() {
8109         throwIfParentInstance("getDeviceOwnerLockScreenInfo");
8110         if (mService != null) {
8111             try {
8112                 return mService.getDeviceOwnerLockScreenInfo();
8113             } catch (RemoteException re) {
8114                 throw re.rethrowFromSystemServer();
8115             }
8116         }
8117         return null;
8118     }
8119 
8120     /**
8121      * Called by device or profile owners to suspend packages for this user. This function can be
8122      * called by a device owner, profile owner, or by a delegate given the
8123      * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}.
8124      * <p>
8125      * A suspended package will not be able to start activities. Its notifications will be hidden,
8126      * it will not show up in recents, will not be able to show toasts or dialogs or ring the
8127      * device.
8128      * <p>
8129      * The package must already be installed. If the package is uninstalled while suspended the
8130      * package will no longer be suspended. The admin can block this by using
8131      * {@link #setUninstallBlocked}.
8132      *
8133      * <p>Some apps cannot be suspended, such as device admins, the active launcher, the required
8134      * package installer, the required package uninstaller, the required package verifier, the
8135      * default dialer, and the permission controller.
8136      *
8137      * @param admin The name of the admin component to check, or {@code null} if the caller is a
8138      *            package access delegate.
8139      * @param packageNames The package names to suspend or unsuspend.
8140      * @param suspended If set to {@code true} than the packages will be suspended, if set to
8141      *            {@code false} the packages will be unsuspended.
8142      * @return an array of package names for which the suspended status is not set as requested in
8143      *         this method.
8144      * @throws SecurityException if {@code admin} is not a device or profile owner.
8145      * @see #setDelegatedScopes
8146      * @see #DELEGATION_PACKAGE_ACCESS
8147      */
setPackagesSuspended(@onNull ComponentName admin, @NonNull String[] packageNames, boolean suspended)8148     public @NonNull String[] setPackagesSuspended(@NonNull ComponentName admin,
8149             @NonNull String[] packageNames, boolean suspended) {
8150         throwIfParentInstance("setPackagesSuspended");
8151         if (mService != null) {
8152             try {
8153                 return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames,
8154                         suspended);
8155             } catch (RemoteException re) {
8156                 throw re.rethrowFromSystemServer();
8157             }
8158         }
8159         return packageNames;
8160     }
8161 
8162     /**
8163      * Determine if a package is suspended. This function can be called by a device owner, profile
8164      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
8165      * {@link #setDelegatedScopes}.
8166      *
8167      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8168      *            {@code null} if the caller is a package access delegate.
8169      * @param packageName The name of the package to retrieve the suspended status of.
8170      * @return {@code true} if the package is suspended or {@code false} if the package is not
8171      *         suspended, could not be found or an error occurred.
8172      * @throws SecurityException if {@code admin} is not a device or profile owner.
8173      * @throws NameNotFoundException if the package could not be found.
8174      * @see #setDelegatedScopes
8175      * @see #DELEGATION_PACKAGE_ACCESS
8176      */
isPackageSuspended(@onNull ComponentName admin, String packageName)8177     public boolean isPackageSuspended(@NonNull ComponentName admin, String packageName)
8178             throws NameNotFoundException {
8179         throwIfParentInstance("isPackageSuspended");
8180         if (mService != null) {
8181             try {
8182                 return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName);
8183             } catch (RemoteException e) {
8184                 throw e.rethrowFromSystemServer();
8185             } catch (IllegalArgumentException ex) {
8186                 throw new NameNotFoundException(packageName);
8187             }
8188         }
8189         return false;
8190     }
8191 
8192     /**
8193      * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
8194      * be used. Only the profile owner can call this.
8195      *
8196      * @see #isProfileOwnerApp
8197      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8198      * @throws SecurityException if {@code admin} is not a profile owner.
8199      */
setProfileEnabled(@onNull ComponentName admin)8200     public void setProfileEnabled(@NonNull ComponentName admin) {
8201         throwIfParentInstance("setProfileEnabled");
8202         if (mService != null) {
8203             try {
8204                 mService.setProfileEnabled(admin);
8205             } catch (RemoteException e) {
8206                 throw e.rethrowFromSystemServer();
8207             }
8208         }
8209     }
8210 
8211     /**
8212      * Sets the name of the profile. In the device owner case it sets the name of the user which it
8213      * is called from. Only a profile owner or device owner can call this. If this is never called
8214      * by the profile or device owner, the name will be set to default values.
8215      *
8216      * @see #isProfileOwnerApp
8217      * @see #isDeviceOwnerApp
8218      * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
8219      * @param profileName The name of the profile.
8220      * @throws SecurityException if {@code admin} is not a device or profile owner.
8221      */
setProfileName(@onNull ComponentName admin, String profileName)8222     public void setProfileName(@NonNull ComponentName admin, String profileName) {
8223         throwIfParentInstance("setProfileName");
8224         if (mService != null) {
8225             try {
8226                 mService.setProfileName(admin, profileName);
8227             } catch (RemoteException e) {
8228                 throw e.rethrowFromSystemServer();
8229             }
8230         }
8231     }
8232 
8233     /**
8234      * Used to determine if a particular package is registered as the profile owner for the
8235      * user. A profile owner is a special device admin that has additional privileges
8236      * within the profile.
8237      *
8238      * @param packageName The package name of the app to compare with the registered profile owner.
8239      * @return Whether or not the package is registered as the profile owner.
8240      */
isProfileOwnerApp(String packageName)8241     public boolean isProfileOwnerApp(String packageName) {
8242         throwIfParentInstance("isProfileOwnerApp");
8243         if (mService != null) {
8244             try {
8245                 ComponentName profileOwner = mService.getProfileOwnerAsUser(myUserId());
8246                 return profileOwner != null
8247                         && profileOwner.getPackageName().equals(packageName);
8248             } catch (RemoteException re) {
8249                 throw re.rethrowFromSystemServer();
8250             }
8251         }
8252         return false;
8253     }
8254 
8255     /**
8256      * @hide
8257      * @return the packageName of the owner of the given user profile or {@code null} if no profile
8258      * owner has been set for that user.
8259      * @throws IllegalArgumentException if the userId is invalid.
8260      */
8261     @SystemApi
getProfileOwner()8262     public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
8263         throwIfParentInstance("getProfileOwner");
8264         return getProfileOwnerAsUser(mContext.getUserId());
8265     }
8266 
8267     /**
8268      * @see #getProfileOwner()
8269      * @hide
8270      */
8271     @RequiresPermission(value = android.Manifest.permission.INTERACT_ACROSS_USERS,
8272             conditional = true)
getProfileOwnerAsUser(@onNull UserHandle user)8273     public @Nullable ComponentName getProfileOwnerAsUser(@NonNull UserHandle user) {
8274         if (mService != null) {
8275             try {
8276                 return mService.getProfileOwnerAsUser(user.getIdentifier());
8277             } catch (RemoteException re) {
8278                 throw re.rethrowFromSystemServer();
8279             }
8280         }
8281         return null;
8282     }
8283 
8284     /**
8285      * @hide
8286      */
8287     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getProfileOwnerAsUser(final int userId)8288     public @Nullable ComponentName getProfileOwnerAsUser(final int userId) {
8289         if (mService != null) {
8290             try {
8291                 return mService.getProfileOwnerAsUser(userId);
8292             } catch (RemoteException re) {
8293                 throw re.rethrowFromSystemServer();
8294             }
8295         }
8296         return null;
8297     }
8298 
8299     /**
8300      * Returns the configured supervision app if it exists and is the device owner or policy owner.
8301      * @hide
8302      */
getProfileOwnerOrDeviceOwnerSupervisionComponent( @onNull UserHandle user)8303     public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent(
8304             @NonNull UserHandle user) {
8305         if (mService != null) {
8306             try {
8307                 return mService.getProfileOwnerOrDeviceOwnerSupervisionComponent(user);
8308             } catch (RemoteException re) {
8309                 throw re.rethrowFromSystemServer();
8310             }
8311         }
8312         return null;
8313     }
8314 
8315     /**
8316      * @hide
8317      * @return the human readable name of the organisation associated with this DPM or {@code null}
8318      *         if one is not set.
8319      * @throws IllegalArgumentException if the userId is invalid.
8320      */
getProfileOwnerName()8321     public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
8322         if (mService != null) {
8323             try {
8324                 return mService.getProfileOwnerName(mContext.getUserId());
8325             } catch (RemoteException re) {
8326                 throw re.rethrowFromSystemServer();
8327             }
8328         }
8329         return null;
8330     }
8331 
8332     /**
8333      * @hide
8334      * @param userId The user for whom to fetch the profile owner name, if any.
8335      * @return the human readable name of the organisation associated with this profile owner or
8336      *         null if one is not set.
8337      * @throws IllegalArgumentException if the userId is invalid.
8338      */
8339     @SystemApi
8340     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getProfileOwnerNameAsUser(int userId)8341     public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
8342         throwIfParentInstance("getProfileOwnerNameAsUser");
8343         if (mService != null) {
8344             try {
8345                 return mService.getProfileOwnerName(userId);
8346             } catch (RemoteException re) {
8347                 throw re.rethrowFromSystemServer();
8348             }
8349         }
8350         return null;
8351     }
8352 
8353     /**
8354      * Apps can use this method to find out if the device was provisioned as
8355      * organization-owend device with a managed profile.
8356      *
8357      * This, together with checking whether the device has a device owner (by calling
8358      * {@link #isDeviceOwnerApp}), could be used to learn whether the device is owned by an
8359      * organization or an individual:
8360      * If this method returns true OR {@link #isDeviceOwnerApp} returns true (for any package),
8361      * then the device is owned by an organization. Otherwise, it's owned by an individual.
8362      *
8363      * @return {@code true} if the device was provisioned as organization-owned device,
8364      * {@code false} otherwise.
8365      */
isOrganizationOwnedDeviceWithManagedProfile()8366     public boolean isOrganizationOwnedDeviceWithManagedProfile() {
8367         throwIfParentInstance("isOrganizationOwnedDeviceWithManagedProfile");
8368         if (mService != null) {
8369             try {
8370                 return mService.isOrganizationOwnedDeviceWithManagedProfile();
8371             } catch (RemoteException re) {
8372                 throw re.rethrowFromSystemServer();
8373             }
8374         }
8375         return false;
8376     }
8377 
8378     /**
8379      * Returns whether the specified package can read the device identifiers.
8380      *
8381      * @param packageName The package name of the app to check for device identifier access.
8382      * @param pid The process id of the package to be checked.
8383      * @param uid The uid of the package to be checked.
8384      * @return whether the package can read the device identifiers.
8385      *
8386      * @hide
8387      */
hasDeviceIdentifierAccess(@onNull String packageName, int pid, int uid)8388     public boolean hasDeviceIdentifierAccess(@NonNull String packageName, int pid, int uid) {
8389         throwIfParentInstance("hasDeviceIdentifierAccess");
8390         if (packageName == null) {
8391             return false;
8392         }
8393         if (mService != null) {
8394             try {
8395                 return mService.checkDeviceIdentifierAccess(packageName, pid, uid);
8396             } catch (RemoteException re) {
8397                 throw re.rethrowFromSystemServer();
8398             }
8399         }
8400         return false;
8401     }
8402 
8403     /**
8404      * Called by a profile owner or device owner to set a default activity that the system selects
8405      * to handle intents that match the given {@link IntentFilter}. This activity will remain the
8406      * default intent handler even if the set of potential event handlers for the intent filter
8407      * changes and if the intent preferences are reset.
8408      * <p>
8409      * Note that the caller should still declare the activity in the manifest, the API just sets
8410      * the activity to be the default one to handle the given intent filter.
8411      * <p>
8412      * The default disambiguation mechanism takes over if the activity is not installed (anymore).
8413      * When the activity is (re)installed, it is automatically reset as default intent handler for
8414      * the filter.
8415      * <p>
8416      * The calling device admin must be a profile owner or device owner. If it is not, a security
8417      * exception will be thrown.
8418      *
8419      * <p>NOTE: Performs disk I/O and shouldn't be called on the main thread.
8420      *
8421      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8422      * @param filter The IntentFilter for which a default handler is added.
8423      * @param activity The Activity that is added as default intent handler.
8424      * @throws SecurityException if {@code admin} is not a device or profile owner.
8425      */
addPersistentPreferredActivity(@onNull ComponentName admin, IntentFilter filter, @NonNull ComponentName activity)8426     public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
8427             @NonNull ComponentName activity) {
8428         throwIfParentInstance("addPersistentPreferredActivity");
8429         if (mService != null) {
8430             try {
8431                 mService.addPersistentPreferredActivity(admin, filter, activity);
8432             } catch (RemoteException e) {
8433                 throw e.rethrowFromSystemServer();
8434             }
8435         }
8436     }
8437 
8438     /**
8439      * Called by a profile owner or device owner to remove all persistent intent handler preferences
8440      * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
8441      * <p>
8442      * The calling device admin must be a profile owner. If it is not, a security exception will be
8443      * thrown.
8444      *
8445      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8446      * @param packageName The name of the package for which preferences are removed.
8447      * @throws SecurityException if {@code admin} is not a device or profile owner.
8448      */
clearPackagePersistentPreferredActivities(@onNull ComponentName admin, String packageName)8449     public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
8450             String packageName) {
8451         throwIfParentInstance("clearPackagePersistentPreferredActivities");
8452         if (mService != null) {
8453             try {
8454                 mService.clearPackagePersistentPreferredActivities(admin, packageName);
8455             } catch (RemoteException e) {
8456                 throw e.rethrowFromSystemServer();
8457             }
8458         }
8459     }
8460 
8461     /**
8462      * Must be called by a device owner or a profile owner of an organization-owned managed profile
8463      * to set the default SMS application.
8464      * <p>
8465      * This method can be called on the {@link DevicePolicyManager} instance, returned by
8466      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
8467      * of an organization-owned managed profile and the package must be a pre-installed system
8468      * package. If called on the parent instance, then the default SMS application is set on the
8469      * personal profile.
8470      *
8471      * @param admin       Which {@link DeviceAdminReceiver} this request is associated with.
8472      * @param packageName The name of the package to set as the default SMS application.
8473      * @throws SecurityException        if {@code admin} is not a device or profile owner or if
8474      *                                  called on the parent profile and the {@code admin} is not a
8475      *                                  profile owner of an organization-owned managed profile.
8476      * @throws IllegalArgumentException if called on the parent profile and the package
8477      *                                  provided is not a pre-installed system package.
8478      */
setDefaultSmsApplication(@onNull ComponentName admin, @NonNull String packageName)8479     public void setDefaultSmsApplication(@NonNull ComponentName admin,
8480             @NonNull String packageName) {
8481         if (mService != null) {
8482             try {
8483                 mService.setDefaultSmsApplication(admin, packageName, mParentInstance);
8484             } catch (RemoteException e) {
8485                 throw e.rethrowFromSystemServer();
8486             }
8487         }
8488     }
8489 
8490     /**
8491      * Called by a profile owner or device owner to grant permission to a package to manage
8492      * application restrictions for the calling user via {@link #setApplicationRestrictions} and
8493      * {@link #getApplicationRestrictions}.
8494      * <p>
8495      * This permission is persistent until it is later cleared by calling this method with a
8496      * {@code null} value or uninstalling the managing package.
8497      * <p>
8498      * The supplied application restriction managing package must be installed when calling this
8499      * API, otherwise an {@link NameNotFoundException} will be thrown.
8500      *
8501      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8502      * @param packageName The package name which will be given access to application restrictions
8503      *            APIs. If {@code null} is given the current package will be cleared.
8504      * @throws SecurityException if {@code admin} is not a device or profile owner.
8505      * @throws NameNotFoundException if {@code packageName} is not found
8506      *
8507      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
8508      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
8509      */
8510     @Deprecated
setApplicationRestrictionsManagingPackage(@onNull ComponentName admin, @Nullable String packageName)8511     public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
8512             @Nullable String packageName) throws NameNotFoundException {
8513         throwIfParentInstance("setApplicationRestrictionsManagingPackage");
8514         if (mService != null) {
8515             try {
8516                 if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
8517                     throw new NameNotFoundException(packageName);
8518                 }
8519             } catch (RemoteException e) {
8520                 throw e.rethrowFromSystemServer();
8521             }
8522         }
8523     }
8524 
8525     /**
8526      * Called by a profile owner or device owner to retrieve the application restrictions managing
8527      * package for the current user, or {@code null} if none is set. If there are multiple
8528      * delegates this function will return one of them.
8529      *
8530      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8531      * @return The package name allowed to manage application restrictions on the current user, or
8532      *         {@code null} if none is set.
8533      * @throws SecurityException if {@code admin} is not a device or profile owner.
8534      *
8535      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
8536      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
8537      */
8538     @Deprecated
8539     @Nullable
getApplicationRestrictionsManagingPackage( @onNull ComponentName admin)8540     public String getApplicationRestrictionsManagingPackage(
8541             @NonNull ComponentName admin) {
8542         throwIfParentInstance("getApplicationRestrictionsManagingPackage");
8543         if (mService != null) {
8544             try {
8545                 return mService.getApplicationRestrictionsManagingPackage(admin);
8546             } catch (RemoteException e) {
8547                 throw e.rethrowFromSystemServer();
8548             }
8549         }
8550         return null;
8551     }
8552 
8553     /**
8554      * Called by any application to find out whether it has been granted permission via
8555      * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
8556      * for the calling user.
8557      *
8558      * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
8559      * that method.
8560      *
8561      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes}
8562      * instead.
8563      */
8564     @Deprecated
isCallerApplicationRestrictionsManagingPackage()8565     public boolean isCallerApplicationRestrictionsManagingPackage() {
8566         throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
8567         if (mService != null) {
8568             try {
8569                 return mService.isCallerApplicationRestrictionsManagingPackage(
8570                         mContext.getPackageName());
8571             } catch (RemoteException e) {
8572                 throw e.rethrowFromSystemServer();
8573             }
8574         }
8575         return false;
8576     }
8577 
8578     /**
8579      * Sets the application restrictions for a given target application running in the calling user.
8580      * <p>
8581      * The caller must be a profile or device owner on that user, or the package allowed to manage
8582      * application restrictions via {@link #setDelegatedScopes} with the
8583      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
8584      * <p>
8585      * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
8586      * <ul>
8587      * <li>{@code boolean}
8588      * <li>{@code int}
8589      * <li>{@code String} or {@code String[]}
8590      * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
8591      * </ul>
8592      * <p>
8593      * If the restrictions are not available yet, but may be applied in the near future, the caller
8594      * can notify the target application of that by adding
8595      * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
8596      * <p>
8597      * The application restrictions are only made visible to the target application via
8598      * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
8599      * owner, and the application restrictions managing package via
8600      * {@link #getApplicationRestrictions}.
8601      *
8602      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
8603      *
8604      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8605      *            {@code null} if called by the application restrictions managing package.
8606      * @param packageName The name of the package to update restricted settings for.
8607      * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
8608      *            set of active restrictions.
8609      * @throws SecurityException if {@code admin} is not a device or profile owner.
8610      * @see #setDelegatedScopes
8611      * @see #DELEGATION_APP_RESTRICTIONS
8612      * @see UserManager#KEY_RESTRICTIONS_PENDING
8613      */
8614     @WorkerThread
setApplicationRestrictions(@ullable ComponentName admin, String packageName, Bundle settings)8615     public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
8616             Bundle settings) {
8617         throwIfParentInstance("setApplicationRestrictions");
8618         if (mService != null) {
8619             try {
8620                 mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName,
8621                         settings);
8622             } catch (RemoteException e) {
8623                 throw e.rethrowFromSystemServer();
8624             }
8625         }
8626     }
8627 
8628     /**
8629      * Sets a list of configuration features to enable for a trust agent component. This is meant to
8630      * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
8631      * agents but those enabled by this function call. If flag
8632      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
8633      * <p>
8634      * For any specific trust agent, whether it is disabled or not depends on the aggregated state
8635      * of each admin's {@link #KEYGUARD_DISABLE_TRUST_AGENTS} setting and its trust agent
8636      * configuration as set by this function call. In particular: if any admin sets
8637      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and does not additionally set any
8638      * trust agent configuration, the trust agent is disabled completely. Otherwise, the trust agent
8639      * will receive the list of configurations from all admins who set
8640      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and aggregate the configurations to determine its
8641      * behavior. The exact meaning of aggregation is trust-agent-specific.
8642      * <p>
8643      * The calling device admin must have requested
8644      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
8645      * if not, a security exception will be thrown.
8646      * <p>
8647      * This method can be called on the {@link DevicePolicyManager} instance returned by
8648      * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
8649      * the parent profile.
8650      * <p>
8651      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, calling
8652      * this method has no effect - no trust agent configuration will be set.
8653      *
8654      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8655      * @param target Component name of the agent to be configured.
8656      * @param configuration Trust-agent-specific feature configuration bundle. Please consult
8657      *        documentation of the specific trust agent to determine the interpretation of this
8658      *        bundle.
8659      * @throws SecurityException if {@code admin} is not an active administrator or does not use
8660      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
8661      */
8662     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setTrustAgentConfiguration(@onNull ComponentName admin, @NonNull ComponentName target, PersistableBundle configuration)8663     public void setTrustAgentConfiguration(@NonNull ComponentName admin,
8664             @NonNull ComponentName target, PersistableBundle configuration) {
8665         if (mService != null) {
8666             try {
8667                 mService.setTrustAgentConfiguration(admin, target, configuration, mParentInstance);
8668             } catch (RemoteException e) {
8669                 throw e.rethrowFromSystemServer();
8670             }
8671         }
8672     }
8673 
8674     /**
8675      * Gets configuration for the given trust agent based on aggregating all calls to
8676      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
8677      * all device admins.
8678      * <p>
8679      * This method can be called on the {@link DevicePolicyManager} instance returned by
8680      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
8681      * on the parent profile.
8682      * <p>
8683      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, null is
8684      * always returned.
8685      *
8686      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
8687      * this function returns a list of configurations for all admins that declare
8688      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
8689      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
8690      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
8691      * for this {@param agent} or calls it with a null configuration, null is returned.
8692      * @param agent Which component to get enabled features for.
8693      * @return configuration for the given trust agent.
8694      */
8695     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent)8696     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
8697             @Nullable ComponentName admin, @NonNull ComponentName agent) {
8698         return getTrustAgentConfiguration(admin, agent, myUserId());
8699     }
8700 
8701     /** @hide per-user version */
8702     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
8703     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent, int userHandle)8704     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
8705             @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
8706         if (mService != null) {
8707             try {
8708                 return mService.getTrustAgentConfiguration(admin, agent, userHandle,
8709                         mParentInstance);
8710             } catch (RemoteException e) {
8711                 throw e.rethrowFromSystemServer();
8712             }
8713         }
8714         return new ArrayList<PersistableBundle>(); // empty list
8715     }
8716 
8717     /**
8718      * Called by a profile owner of a managed profile to set whether caller-Id information from the
8719      * managed profile will be shown in the parent profile, for incoming calls.
8720      * <p>
8721      * The calling device admin must be a profile owner. If it is not, a security exception will be
8722      * thrown.
8723      *
8724      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8725      * @param disabled If true caller-Id information in the managed profile is not displayed.
8726      * @throws SecurityException if {@code admin} is not a profile owner.
8727      */
setCrossProfileCallerIdDisabled(@onNull ComponentName admin, boolean disabled)8728     public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
8729         throwIfParentInstance("setCrossProfileCallerIdDisabled");
8730         if (mService != null) {
8731             try {
8732                 mService.setCrossProfileCallerIdDisabled(admin, disabled);
8733             } catch (RemoteException e) {
8734                 throw e.rethrowFromSystemServer();
8735             }
8736         }
8737     }
8738 
8739     /**
8740      * Called by a profile owner of a managed profile to determine whether or not caller-Id
8741      * information has been disabled.
8742      * <p>
8743      * The calling device admin must be a profile owner. If it is not, a security exception will be
8744      * thrown.
8745      *
8746      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8747      * @throws SecurityException if {@code admin} is not a profile owner.
8748      */
getCrossProfileCallerIdDisabled(@onNull ComponentName admin)8749     public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
8750         throwIfParentInstance("getCrossProfileCallerIdDisabled");
8751         if (mService != null) {
8752             try {
8753                 return mService.getCrossProfileCallerIdDisabled(admin);
8754             } catch (RemoteException e) {
8755                 throw e.rethrowFromSystemServer();
8756             }
8757         }
8758         return false;
8759     }
8760 
8761     /**
8762      * Determine whether or not caller-Id information has been disabled.
8763      *
8764      * @param userHandle The user for whom to check the caller-id permission
8765      * @hide
8766      */
getCrossProfileCallerIdDisabled(UserHandle userHandle)8767     public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
8768         if (mService != null) {
8769             try {
8770                 return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
8771             } catch (RemoteException e) {
8772                 throw e.rethrowFromSystemServer();
8773             }
8774         }
8775         return false;
8776     }
8777 
8778     /**
8779      * Called by a profile owner of a managed profile to set whether contacts search from the
8780      * managed profile will be shown in the parent profile, for incoming calls.
8781      * <p>
8782      * The calling device admin must be a profile owner. If it is not, a security exception will be
8783      * thrown.
8784      *
8785      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8786      * @param disabled If true contacts search in the managed profile is not displayed.
8787      * @throws SecurityException if {@code admin} is not a profile owner.
8788      */
setCrossProfileContactsSearchDisabled(@onNull ComponentName admin, boolean disabled)8789     public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
8790             boolean disabled) {
8791         throwIfParentInstance("setCrossProfileContactsSearchDisabled");
8792         if (mService != null) {
8793             try {
8794                 mService.setCrossProfileContactsSearchDisabled(admin, disabled);
8795             } catch (RemoteException e) {
8796                 throw e.rethrowFromSystemServer();
8797             }
8798         }
8799     }
8800 
8801     /**
8802      * Called by a profile owner of a managed profile to determine whether or not contacts search
8803      * has been disabled.
8804      * <p>
8805      * The calling device admin must be a profile owner. If it is not, a security exception will be
8806      * thrown.
8807      *
8808      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8809      * @throws SecurityException if {@code admin} is not a profile owner.
8810      */
getCrossProfileContactsSearchDisabled(@onNull ComponentName admin)8811     public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
8812         throwIfParentInstance("getCrossProfileContactsSearchDisabled");
8813         if (mService != null) {
8814             try {
8815                 return mService.getCrossProfileContactsSearchDisabled(admin);
8816             } catch (RemoteException e) {
8817                 throw e.rethrowFromSystemServer();
8818             }
8819         }
8820         return false;
8821     }
8822 
8823 
8824     /**
8825      * Determine whether or not contacts search has been disabled.
8826      *
8827      * @param userHandle The user for whom to check the contacts search permission
8828      * @hide
8829      */
getCrossProfileContactsSearchDisabled(@onNull UserHandle userHandle)8830     public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
8831         if (mService != null) {
8832             try {
8833                 return mService
8834                         .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
8835             } catch (RemoteException e) {
8836                 throw e.rethrowFromSystemServer();
8837             }
8838         }
8839         return false;
8840     }
8841 
8842     /**
8843      * Start Quick Contact on the managed profile for the user, if the policy allows.
8844      *
8845      * @hide
8846      */
startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long directoryId, Intent originalIntent)8847     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
8848             boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
8849         if (mService != null) {
8850             try {
8851                 mService.startManagedQuickContact(actualLookupKey, actualContactId,
8852                         isContactIdIgnored, directoryId, originalIntent);
8853             } catch (RemoteException e) {
8854                 throw e.rethrowFromSystemServer();
8855             }
8856         }
8857     }
8858 
8859     /**
8860      * Start Quick Contact on the managed profile for the user, if the policy allows.
8861      * @hide
8862      */
startManagedQuickContact(String actualLookupKey, long actualContactId, Intent originalIntent)8863     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
8864             Intent originalIntent) {
8865         startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
8866                 originalIntent);
8867     }
8868 
8869     /**
8870      * Called by a profile owner of a managed profile to set whether bluetooth devices can access
8871      * enterprise contacts.
8872      * <p>
8873      * The calling device admin must be a profile owner. If it is not, a security exception will be
8874      * thrown.
8875      * <p>
8876      * This API works on managed profile only.
8877      *
8878      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8879      * @param disabled If true, bluetooth devices cannot access enterprise contacts.
8880      * @throws SecurityException if {@code admin} is not a profile owner.
8881      */
setBluetoothContactSharingDisabled(@onNull ComponentName admin, boolean disabled)8882     public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
8883         throwIfParentInstance("setBluetoothContactSharingDisabled");
8884         if (mService != null) {
8885             try {
8886                 mService.setBluetoothContactSharingDisabled(admin, disabled);
8887             } catch (RemoteException e) {
8888                 throw e.rethrowFromSystemServer();
8889             }
8890         }
8891     }
8892 
8893     /**
8894      * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
8895      * cannot access enterprise contacts.
8896      * <p>
8897      * The calling device admin must be a profile owner. If it is not, a security exception will be
8898      * thrown.
8899      * <p>
8900      * This API works on managed profile only.
8901      *
8902      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8903      * @throws SecurityException if {@code admin} is not a profile owner.
8904      */
getBluetoothContactSharingDisabled(@onNull ComponentName admin)8905     public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
8906         throwIfParentInstance("getBluetoothContactSharingDisabled");
8907         if (mService != null) {
8908             try {
8909                 return mService.getBluetoothContactSharingDisabled(admin);
8910             } catch (RemoteException e) {
8911                 throw e.rethrowFromSystemServer();
8912             }
8913         }
8914         return true;
8915     }
8916 
8917     /**
8918      * Determine whether or not Bluetooth devices cannot access contacts.
8919      * <p>
8920      * This API works on managed profile UserHandle only.
8921      *
8922      * @param userHandle The user for whom to check the caller-id permission
8923      * @hide
8924      */
8925     @SystemApi
8926     @RequiresPermission(permission.INTERACT_ACROSS_USERS)
getBluetoothContactSharingDisabled(@onNull UserHandle userHandle)8927     public boolean getBluetoothContactSharingDisabled(@NonNull UserHandle userHandle) {
8928         if (mService != null) {
8929             try {
8930                 return mService.getBluetoothContactSharingDisabledForUser(userHandle
8931                         .getIdentifier());
8932             } catch (RemoteException e) {
8933                 throw e.rethrowFromSystemServer();
8934             }
8935         }
8936         return true;
8937     }
8938 
8939     /**
8940      * Called by the profile owner of a managed profile so that some intents sent in the managed
8941      * profile can also be resolved in the parent, or vice versa. Only activity intents are
8942      * supported.
8943      *
8944      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8945      * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
8946      *            other profile
8947      * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
8948      *            {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
8949      * @throws SecurityException if {@code admin} is not a device or profile owner.
8950      */
addCrossProfileIntentFilter(@onNull ComponentName admin, IntentFilter filter, int flags)8951     public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
8952         throwIfParentInstance("addCrossProfileIntentFilter");
8953         if (mService != null) {
8954             try {
8955                 mService.addCrossProfileIntentFilter(admin, filter, flags);
8956             } catch (RemoteException e) {
8957                 throw e.rethrowFromSystemServer();
8958             }
8959         }
8960     }
8961 
8962     /**
8963      * Called by a profile owner of a managed profile to remove the cross-profile intent filters
8964      * that go from the managed profile to the parent, or from the parent to the managed profile.
8965      * Only removes those that have been set by the profile owner.
8966      * <p>
8967      * <em>Note</em>: A list of default cross profile intent filters are set up by the system when
8968      * the profile is created, some of them ensure the proper functioning of the profile, while
8969      * others enable sharing of data from the parent to the managed profile for user convenience.
8970      * These default intent filters are not cleared when this API is called. If the default cross
8971      * profile data sharing is not desired, they can be disabled with
8972      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE}.
8973      *
8974      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8975      * @throws SecurityException if {@code admin} is not a profile owner.
8976      */
clearCrossProfileIntentFilters(@onNull ComponentName admin)8977     public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
8978         throwIfParentInstance("clearCrossProfileIntentFilters");
8979         if (mService != null) {
8980             try {
8981                 mService.clearCrossProfileIntentFilters(admin);
8982             } catch (RemoteException e) {
8983                 throw e.rethrowFromSystemServer();
8984             }
8985         }
8986     }
8987 
8988     /**
8989      * Called by a profile or device owner to set the permitted
8990      * {@link android.accessibilityservice.AccessibilityService}. When set by
8991      * a device owner or profile owner the restriction applies to all profiles of the user the
8992      * device owner or profile owner is an admin for. By default, the user can use any accessibility
8993      * service. When zero or more packages have been added, accessibility services that are not in
8994      * the list and not part of the system can not be enabled by the user.
8995      * <p>
8996      * Calling with a null value for the list disables the restriction so that all services can be
8997      * used, calling with an empty list only allows the built-in system services. Any non-system
8998      * accessibility service that's currently enabled must be included in the list.
8999      * <p>
9000      * System accessibility services are always available to the user and this method can't
9001      * disable them.
9002      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9003      * @param packageNames List of accessibility service package names.
9004      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
9005      *         contain every enabled non-system accessibility service.
9006      * @throws SecurityException if {@code admin} is not a device or profile owner.
9007      */
setPermittedAccessibilityServices(@onNull ComponentName admin, List<String> packageNames)9008     public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
9009             List<String> packageNames) {
9010         throwIfParentInstance("setPermittedAccessibilityServices");
9011         if (mService != null) {
9012             try {
9013                 return mService.setPermittedAccessibilityServices(admin, packageNames);
9014             } catch (RemoteException e) {
9015                 throw e.rethrowFromSystemServer();
9016             }
9017         }
9018         return false;
9019     }
9020 
9021     /**
9022      * Returns the list of permitted accessibility services set by this device or profile owner.
9023      * <p>
9024      * An empty list means no accessibility services except system services are allowed. Null means
9025      * all accessibility services are allowed.
9026      *
9027      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9028      * @return List of accessiblity service package names.
9029      * @throws SecurityException if {@code admin} is not a device or profile owner.
9030      */
getPermittedAccessibilityServices(@onNull ComponentName admin)9031     public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
9032         throwIfParentInstance("getPermittedAccessibilityServices");
9033         if (mService != null) {
9034             try {
9035                 return mService.getPermittedAccessibilityServices(admin);
9036             } catch (RemoteException e) {
9037                 throw e.rethrowFromSystemServer();
9038             }
9039         }
9040         return null;
9041     }
9042 
9043     /**
9044      * Called by the system to check if a specific accessibility service is disabled by admin.
9045      *
9046      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9047      * @param packageName Accessibility service package name that needs to be checked.
9048      * @param userHandle user id the admin is running as.
9049      * @return true if the accessibility service is permitted, otherwise false.
9050      *
9051      * @hide
9052      */
isAccessibilityServicePermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)9053     public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
9054             @NonNull String packageName, int userHandle) {
9055         if (mService != null) {
9056             try {
9057                 return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
9058                         userHandle);
9059             } catch (RemoteException e) {
9060                 throw e.rethrowFromSystemServer();
9061             }
9062         }
9063         return false;
9064     }
9065 
9066     /**
9067      * Returns the list of accessibility services permitted by the device or profiles
9068      * owners of this user.
9069      *
9070      * <p>Null means all accessibility services are allowed, if a non-null list is returned
9071      * it will contain the intersection of the permitted lists for any device or profile
9072      * owners that apply to this user. It will also include any system accessibility services.
9073      *
9074      * @param userId which user to check for.
9075      * @return List of accessiblity service package names.
9076      * @hide
9077      */
9078      @SystemApi
9079      @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getPermittedAccessibilityServices(int userId)9080      public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
9081         throwIfParentInstance("getPermittedAccessibilityServices");
9082         if (mService != null) {
9083             try {
9084                 return mService.getPermittedAccessibilityServicesForUser(userId);
9085             } catch (RemoteException e) {
9086                 throw e.rethrowFromSystemServer();
9087             }
9088         }
9089         return null;
9090      }
9091 
9092     /**
9093      * Called by a profile or device owner to set the permitted input methods services for this
9094      * user. By default, the user can use any input method.
9095      * <p>
9096      * This method can be called on the {@link DevicePolicyManager} instance,
9097      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
9098      * a profile owner of an organization-owned device.
9099      * <p>
9100      * If called on the parent instance:
9101      * <ul>
9102      *    <li>The permitted input methods will be applied on the personal profile</li>
9103      *    <li>Can only permit all input methods (calling this method with a {@code null} package
9104      *    list) or only permit system input methods (calling this method with an empty package
9105      *    list). This is to prevent the caller from learning which packages are installed on
9106      *    the personal side</li>
9107      * </ul>
9108      * <p>
9109      * When zero or more packages have been added, input method that are not in the list and not
9110      * part of the system can not be enabled by the user. This method will fail if it is called for
9111      * a admin that is not for the foreground user or a profile of the foreground user. Any
9112      * non-system input method service that's currently enabled must be included in the list.
9113      * <p>
9114      * Calling with a null value for the list disables the restriction so that all input methods can
9115      * be used, calling with an empty list disables all but the system's own input methods.
9116      * <p>
9117      * System input methods are always available to the user - this method can't modify this.
9118      *
9119      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9120      * @param packageNames List of input method package names.
9121      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
9122      *        contain every enabled non-system input method service.
9123      * @throws SecurityException if {@code admin} is not a device, profile owner or if called on
9124      *                           the parent profile and the {@code admin} is not a profile owner
9125      *                           of an organization-owned managed profile.
9126      * @throws IllegalArgumentException if called on the parent profile, the {@code admin} is a
9127      *                           profile owner of an organization-owned managed profile and the
9128      *                           list of permitted input method package names is not null or empty.
9129      */
setPermittedInputMethods( @onNull ComponentName admin, List<String> packageNames)9130     public boolean setPermittedInputMethods(
9131             @NonNull ComponentName admin, List<String> packageNames) {
9132         if (mService != null) {
9133             try {
9134                 return mService.setPermittedInputMethods(admin, packageNames, mParentInstance);
9135             } catch (RemoteException e) {
9136                 throw e.rethrowFromSystemServer();
9137             }
9138         }
9139         return false;
9140     }
9141 
9142 
9143     /**
9144      * Returns the list of permitted input methods set by this device or profile owner.
9145      * <p>
9146      * This method can be called on the {@link DevicePolicyManager} instance,
9147      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
9148      * a profile owner of an organization-owned managed profile. If called on the parent instance,
9149      * then the returned list of permitted input methods are those which are applied on the
9150      * personal profile.
9151      * <p>
9152      * An empty list means no input methods except system input methods are allowed. Null means all
9153      * input methods are allowed.
9154      *
9155      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9156      * @return List of input method package names.
9157      * @throws SecurityException if {@code admin} is not a device, profile owner or if called on
9158      *                           the parent profile and the {@code admin} is not a profile owner
9159      *                           of an organization-owned managed profile.
9160      */
getPermittedInputMethods(@onNull ComponentName admin)9161     public @Nullable List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
9162         if (mService != null) {
9163             try {
9164                 return mService.getPermittedInputMethods(admin, mParentInstance);
9165             } catch (RemoteException e) {
9166                 throw e.rethrowFromSystemServer();
9167             }
9168         }
9169         return null;
9170     }
9171 
9172     /**
9173      * Called by the system to check if a specific input method is disabled by admin.
9174      * <p>
9175      * This method can be called on the {@link DevicePolicyManager} instance,
9176      * returned by {@link #getParentProfileInstance(ComponentName)}. If called on the parent
9177      * instance, this method will check whether the given input method is permitted on
9178      * the personal profile.
9179      *
9180      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9181      * @param packageName Input method package name that needs to be checked.
9182      * @param userHandle user id the admin is running as.
9183      * @return true if the input method is permitted, otherwise false.
9184      *
9185      * @hide
9186      */
isInputMethodPermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)9187     public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
9188             @NonNull String packageName, int userHandle) {
9189         if (mService != null) {
9190             try {
9191                 return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle,
9192                         mParentInstance);
9193             } catch (RemoteException e) {
9194                 throw e.rethrowFromSystemServer();
9195             }
9196         }
9197         return false;
9198     }
9199 
9200     /**
9201      * Returns the list of input methods permitted by the device or profiles owners.
9202      *
9203      * <p>On {@link android.os.Build.VERSION_CODES#Q} and later devices, this method returns the
9204      * result for the calling user.</p>
9205      *
9206      * <p>On Android P and prior devices, this method returns the result for the current user.</p>
9207      *
9208      * <p>Null means all input methods are allowed, if a non-null list is returned
9209      * it will contain the intersection of the permitted lists for any device or profile
9210      * owners that apply to this user. It will also include any system input methods.
9211      *
9212      * @return List of input method package names.
9213      * @hide
9214      */
9215     @SystemApi
9216     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getPermittedInputMethodsForCurrentUser()9217     public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
9218         throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
9219         if (mService != null) {
9220             try {
9221                 return mService.getPermittedInputMethodsForCurrentUser();
9222             } catch (RemoteException e) {
9223                 throw e.rethrowFromSystemServer();
9224             }
9225         }
9226         return null;
9227     }
9228 
9229     /**
9230      * Called by a profile owner of a managed profile to set the packages that are allowed to use
9231      * a {@link android.service.notification.NotificationListenerService} in the primary user to
9232      * see notifications from the managed profile. By default all packages are permitted by this
9233      * policy. When zero or more packages have been added, notification listeners installed on the
9234      * primary user that are not in the list and are not part of the system won't receive events
9235      * for managed profile notifications.
9236      * <p>
9237      * Calling with a {@code null} value for the list disables the restriction so that all
9238      * notification listener services be used. Calling with an empty list disables all but the
9239      * system's own notification listeners. System notification listener services are always
9240      * available to the user.
9241      * <p>
9242      * If a device or profile owner want to stop notification listeners in their user from seeing
9243      * that user's notifications they should prevent that service from running instead (e.g. via
9244      * {@link #setApplicationHidden(ComponentName, String, boolean)})
9245      *
9246      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9247      * @param packageList List of package names to allowlist
9248      * @return true if setting the restriction succeeded. It will fail if called outside a managed
9249      * profile
9250      * @throws SecurityException if {@code admin} is not a profile owner.
9251      *
9252      * @see android.service.notification.NotificationListenerService
9253      */
setPermittedCrossProfileNotificationListeners( @onNull ComponentName admin, @Nullable List<String> packageList)9254     public boolean setPermittedCrossProfileNotificationListeners(
9255             @NonNull ComponentName admin, @Nullable List<String> packageList) {
9256         throwIfParentInstance("setPermittedCrossProfileNotificationListeners");
9257         if (mService != null) {
9258             try {
9259                 return mService.setPermittedCrossProfileNotificationListeners(admin, packageList);
9260             } catch (RemoteException e) {
9261                 throw e.rethrowFromSystemServer();
9262             }
9263         }
9264         return false;
9265     }
9266 
9267     /**
9268      * Returns the list of packages installed on the primary user that allowed to use a
9269      * {@link android.service.notification.NotificationListenerService} to receive
9270      * notifications from this managed profile, as set by the profile owner.
9271      * <p>
9272      * An empty list means no notification listener services except system ones are allowed.
9273      * A {@code null} return value indicates that all notification listeners are allowed.
9274      */
getPermittedCrossProfileNotificationListeners( @onNull ComponentName admin)9275     public @Nullable List<String> getPermittedCrossProfileNotificationListeners(
9276             @NonNull ComponentName admin) {
9277         throwIfParentInstance("getPermittedCrossProfileNotificationListeners");
9278         if (mService != null) {
9279             try {
9280                 return mService.getPermittedCrossProfileNotificationListeners(admin);
9281             } catch (RemoteException e) {
9282                 throw e.rethrowFromSystemServer();
9283             }
9284         }
9285         return null;
9286     }
9287 
9288     /**
9289      * Returns true if {@code NotificationListenerServices} from the given package are allowed to
9290      * receive events for notifications from the given user id. Can only be called by the system uid
9291      *
9292      * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List)
9293      *
9294      * @hide
9295      */
isNotificationListenerServicePermitted( @onNull String packageName, @UserIdInt int userId)9296     public boolean isNotificationListenerServicePermitted(
9297             @NonNull String packageName, @UserIdInt int userId) {
9298         if (mService != null) {
9299             try {
9300                 return mService.isNotificationListenerServicePermitted(packageName, userId);
9301             } catch (RemoteException e) {
9302                 throw e.rethrowFromSystemServer();
9303             }
9304         }
9305         return true;
9306     }
9307 
9308     /**
9309      * Get the list of apps to keep around as APKs even if no user has currently installed it. This
9310      * function can be called by a device owner or by a delegate given the
9311      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
9312      * <p>
9313      * Please note that packages returned in this method are not automatically pre-cached.
9314      *
9315      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9316      *            {@code null} if the caller is a keep uninstalled packages delegate.
9317      * @return List of package names to keep cached.
9318      * @see #setDelegatedScopes
9319      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
9320      */
getKeepUninstalledPackages(@ullable ComponentName admin)9321     public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) {
9322         throwIfParentInstance("getKeepUninstalledPackages");
9323         if (mService != null) {
9324             try {
9325                 return mService.getKeepUninstalledPackages(admin, mContext.getPackageName());
9326             } catch (RemoteException e) {
9327                 throw e.rethrowFromSystemServer();
9328             }
9329         }
9330         return null;
9331     }
9332 
9333     /**
9334      * Set a list of apps to keep around as APKs even if no user has currently installed it. This
9335      * function can be called by a device owner or by a delegate given the
9336      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
9337      *
9338      * <p>Please note that setting this policy does not imply that specified apps will be
9339      * automatically pre-cached.</p>
9340      *
9341      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9342      *            {@code null} if the caller is a keep uninstalled packages delegate.
9343      * @param packageNames List of package names to keep cached.
9344      * @throws SecurityException if {@code admin} is not a device owner.
9345      * @see #setDelegatedScopes
9346      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
9347      */
setKeepUninstalledPackages(@ullable ComponentName admin, @NonNull List<String> packageNames)9348     public void setKeepUninstalledPackages(@Nullable ComponentName admin,
9349             @NonNull List<String> packageNames) {
9350         throwIfParentInstance("setKeepUninstalledPackages");
9351         if (mService != null) {
9352             try {
9353                 mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames);
9354             } catch (RemoteException e) {
9355                 throw e.rethrowFromSystemServer();
9356             }
9357         }
9358     }
9359 
9360     /**
9361       * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
9362       */
9363     public static final int SKIP_SETUP_WIZARD = 0x0001;
9364 
9365     /**
9366      * Flag used by {@link #createAndManageUser} to specify that the user should be created
9367      * ephemeral. Ephemeral users will be removed after switching to another user or rebooting the
9368      * device.
9369      */
9370     public static final int MAKE_USER_EPHEMERAL = 0x0002;
9371 
9372     /**
9373      * Flag used by {@link #createAndManageUser} to specify that the user should be created as a
9374      * demo user.
9375      * @hide
9376      */
9377     public static final int MAKE_USER_DEMO = 0x0004;
9378 
9379     /**
9380      * Flag used by {@link #createAndManageUser} to specify that the newly created user should skip
9381      * the disabling of system apps during provisioning.
9382      */
9383     public static final int LEAVE_ALL_SYSTEM_APPS_ENABLED = 0x0010;
9384 
9385     /**
9386      * @hide
9387      */
9388     @IntDef(flag = true, prefix = { "SKIP_", "MAKE_USER_", "START_", "LEAVE_" }, value = {
9389             SKIP_SETUP_WIZARD,
9390             MAKE_USER_EPHEMERAL,
9391             MAKE_USER_DEMO,
9392             LEAVE_ALL_SYSTEM_APPS_ENABLED
9393     })
9394     @Retention(RetentionPolicy.SOURCE)
9395     public @interface CreateAndManageUserFlags {}
9396 
9397     /**
9398      * Called by a device owner to create a user with the specified name and a given component of
9399      * the calling package as profile owner. The UserHandle returned by this method should not be
9400      * persisted as user handles are recycled as users are removed and created. If you need to
9401      * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
9402      * user will not be started in the background.
9403      * <p>
9404      * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
9405      * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
9406      * be registered as an active admin on the new user. The profile owner package will be installed
9407      * on the new user.
9408      * <p>
9409      * If the adminExtras are not null, they will be stored on the device until the user is started
9410      * for the first time. Then the extras will be passed to the admin when onEnable is called.
9411      * <p>From {@link android.os.Build.VERSION_CODES#P} onwards, if targeting
9412      * {@link android.os.Build.VERSION_CODES#P}, throws {@link UserOperationException} instead of
9413      * returning {@code null} on failure.
9414      *
9415      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9416      * @param name The user's name.
9417      * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
9418      *            same package as admin, otherwise no user is created and an
9419      *            IllegalArgumentException is thrown.
9420      * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
9421      *            user.
9422      * @param flags {@link #SKIP_SETUP_WIZARD}, {@link #MAKE_USER_EPHEMERAL} and
9423      *        {@link #LEAVE_ALL_SYSTEM_APPS_ENABLED} are supported.
9424      * @see UserHandle
9425      * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
9426      *         user could not be created.
9427      * @throws SecurityException if {@code admin} is not a device owner.
9428      * @throws UserOperationException if the user could not be created and the calling app is
9429      * targeting {@link android.os.Build.VERSION_CODES#P} and running on
9430      * {@link android.os.Build.VERSION_CODES#P}.
9431      */
createAndManageUser(@onNull ComponentName admin, @NonNull String name, @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras, @CreateAndManageUserFlags int flags)9432     public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
9433             @NonNull String name,
9434             @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
9435             @CreateAndManageUserFlags int flags) {
9436         throwIfParentInstance("createAndManageUser");
9437         try {
9438             return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
9439         } catch (ServiceSpecificException e) {
9440             throw new UserOperationException(e.getMessage(), e.errorCode);
9441         } catch (RemoteException re) {
9442             throw re.rethrowFromSystemServer();
9443         }
9444     }
9445 
9446     /**
9447      * Called by a device owner to remove a user/profile and all associated data. The primary user
9448      * can not be removed.
9449      *
9450      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9451      * @param userHandle the user to remove.
9452      * @return {@code true} if the user was removed, {@code false} otherwise.
9453      * @throws SecurityException if {@code admin} is not a device owner.
9454      */
removeUser(@onNull ComponentName admin, @NonNull UserHandle userHandle)9455     public boolean removeUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) {
9456         throwIfParentInstance("removeUser");
9457         try {
9458             return mService.removeUser(admin, userHandle);
9459         } catch (RemoteException re) {
9460             throw re.rethrowFromSystemServer();
9461         }
9462     }
9463 
9464     /**
9465      * Called by a device owner to switch the specified secondary user to the foreground.
9466      *
9467      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9468      * @param userHandle the user to switch to; null will switch to primary.
9469      * @return {@code true} if the switch was successful, {@code false} otherwise.
9470      * @throws SecurityException if {@code admin} is not a device owner.
9471      * @see Intent#ACTION_USER_FOREGROUND
9472      * @see #getSecondaryUsers(ComponentName)
9473      */
switchUser(@onNull ComponentName admin, @Nullable UserHandle userHandle)9474     public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
9475         throwIfParentInstance("switchUser");
9476         try {
9477             return mService.switchUser(admin, userHandle);
9478         } catch (RemoteException re) {
9479             throw re.rethrowFromSystemServer();
9480         }
9481     }
9482 
9483     /**
9484      * Called by a device owner to start the specified secondary user in background.
9485      *
9486      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9487      * @param userHandle the user to be started in background.
9488      * @return one of the following result codes:
9489      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
9490      * {@link UserManager#USER_OPERATION_SUCCESS},
9491      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
9492      * {@link UserManager#USER_OPERATION_ERROR_MAX_RUNNING_USERS},
9493      * @throws SecurityException if {@code admin} is not a device owner.
9494      * @see #getSecondaryUsers(ComponentName)
9495      */
startUserInBackground( @onNull ComponentName admin, @NonNull UserHandle userHandle)9496     public @UserOperationResult int startUserInBackground(
9497             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
9498         throwIfParentInstance("startUserInBackground");
9499         try {
9500             return mService.startUserInBackground(admin, userHandle);
9501         } catch (RemoteException re) {
9502             throw re.rethrowFromSystemServer();
9503         }
9504     }
9505 
9506     /**
9507      * Called by a device owner to stop the specified secondary user.
9508      *
9509      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9510      * @param userHandle the user to be stopped.
9511      * @return one of the following result codes:
9512      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
9513      * {@link UserManager#USER_OPERATION_SUCCESS},
9514      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
9515      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
9516      * @throws SecurityException if {@code admin} is not a device owner.
9517      * @see #getSecondaryUsers(ComponentName)
9518      */
stopUser( @onNull ComponentName admin, @NonNull UserHandle userHandle)9519     public @UserOperationResult int stopUser(
9520             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
9521         throwIfParentInstance("stopUser");
9522         try {
9523             return mService.stopUser(admin, userHandle);
9524         } catch (RemoteException re) {
9525             throw re.rethrowFromSystemServer();
9526         }
9527     }
9528 
9529     /**
9530      * Called by a profile owner of secondary user that is affiliated with the device to stop the
9531      * calling user and switch back to primary.
9532      *
9533      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9534      * @return one of the following result codes:
9535      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
9536      * {@link UserManager#USER_OPERATION_SUCCESS},
9537      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
9538      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
9539      * @throws SecurityException if {@code admin} is not a profile owner affiliated with the device.
9540      * @see #getSecondaryUsers(ComponentName)
9541      */
logoutUser(@onNull ComponentName admin)9542     public @UserOperationResult int logoutUser(@NonNull ComponentName admin) {
9543         throwIfParentInstance("logoutUser");
9544         try {
9545             return mService.logoutUser(admin);
9546         } catch (RemoteException re) {
9547             throw re.rethrowFromSystemServer();
9548         }
9549     }
9550 
9551     /**
9552      * Called by a device owner to list all secondary users on the device. Managed profiles are not
9553      * considered as secondary users.
9554      * <p> Used for various user management APIs, including {@link #switchUser}, {@link #removeUser}
9555      * and {@link #stopUser}.
9556      *
9557      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9558      * @return list of other {@link UserHandle}s on the device.
9559      * @throws SecurityException if {@code admin} is not a device owner.
9560      * @see #removeUser(ComponentName, UserHandle)
9561      * @see #switchUser(ComponentName, UserHandle)
9562      * @see #startUserInBackground(ComponentName, UserHandle)
9563      * @see #stopUser(ComponentName, UserHandle)
9564      */
getSecondaryUsers(@onNull ComponentName admin)9565     public List<UserHandle> getSecondaryUsers(@NonNull ComponentName admin) {
9566         throwIfParentInstance("getSecondaryUsers");
9567         try {
9568             return mService.getSecondaryUsers(admin);
9569         } catch (RemoteException re) {
9570             throw re.rethrowFromSystemServer();
9571         }
9572     }
9573 
9574     /**
9575      * Checks if the profile owner is running in an ephemeral user.
9576      *
9577      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9578      * @return whether the profile owner is running in an ephemeral user.
9579      */
isEphemeralUser(@onNull ComponentName admin)9580     public boolean isEphemeralUser(@NonNull ComponentName admin) {
9581         throwIfParentInstance("isEphemeralUser");
9582         try {
9583             return mService.isEphemeralUser(admin);
9584         } catch (RemoteException re) {
9585             throw re.rethrowFromSystemServer();
9586         }
9587     }
9588 
9589     /**
9590      * Retrieves the application restrictions for a given target application running in the calling
9591      * user.
9592      * <p>
9593      * The caller must be a profile or device owner on that user, or the package allowed to manage
9594      * application restrictions via {@link #setDelegatedScopes} with the
9595      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
9596      *
9597      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
9598      *
9599      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9600      *            {@code null} if called by the application restrictions managing package.
9601      * @param packageName The name of the package to fetch restricted settings of.
9602      * @return {@link Bundle} of settings corresponding to what was set last time
9603      *         {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
9604      *         {@link Bundle} if no restrictions have been set.
9605      * @throws SecurityException if {@code admin} is not a device or profile owner.
9606      * @see #setDelegatedScopes
9607      * @see #DELEGATION_APP_RESTRICTIONS
9608      */
9609     @WorkerThread
getApplicationRestrictions( @ullable ComponentName admin, String packageName)9610     public @NonNull Bundle getApplicationRestrictions(
9611             @Nullable ComponentName admin, String packageName) {
9612         throwIfParentInstance("getApplicationRestrictions");
9613         if (mService != null) {
9614             try {
9615                 return mService.getApplicationRestrictions(admin, mContext.getPackageName(),
9616                         packageName);
9617             } catch (RemoteException e) {
9618                 throw e.rethrowFromSystemServer();
9619             }
9620         }
9621         return null;
9622     }
9623 
9624     /**
9625      * Called by a profile or device owner to set a user restriction specified by the key.
9626      * <p>
9627      * The calling device admin must be a profile or device owner; if it is not, a security
9628      * exception will be thrown.
9629      * <p>
9630      * The profile owner of an organization-owned managed profile may invoke this method on
9631      * the {@link DevicePolicyManager} instance it obtained from
9632      * {@link #getParentProfileInstance(ComponentName)}, for enforcing device-wide restrictions.
9633      * <p>
9634      * See the constants in {@link android.os.UserManager} for the list of restrictions that can
9635      * be enforced device-wide.
9636      *
9637      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9638      * @param key   The key of the restriction.
9639      * @throws SecurityException if {@code admin} is not a device or profile owner.
9640      */
addUserRestriction(@onNull ComponentName admin, @UserManager.UserRestrictionKey String key)9641     public void addUserRestriction(@NonNull ComponentName admin,
9642             @UserManager.UserRestrictionKey String key) {
9643         if (mService != null) {
9644             try {
9645                 mService.setUserRestriction(admin, key, true, mParentInstance);
9646             } catch (RemoteException e) {
9647                 throw e.rethrowFromSystemServer();
9648             }
9649         }
9650     }
9651 
9652     /**
9653      * Called by a profile or device owner to clear a user restriction specified by the key.
9654      * <p>
9655      * The calling device admin must be a profile or device owner; if it is not, a security
9656      * exception will be thrown.
9657      * <p>
9658      * The profile owner of an organization-owned managed profile may invoke this method on
9659      * the {@link DevicePolicyManager} instance it obtained from
9660      * {@link #getParentProfileInstance(ComponentName)}, for clearing device-wide restrictions.
9661      * <p>
9662      * See the constants in {@link android.os.UserManager} for the list of restrictions.
9663      *
9664      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9665      * @param key   The key of the restriction.
9666      * @throws SecurityException if {@code admin} is not a device or profile owner.
9667      */
clearUserRestriction(@onNull ComponentName admin, @UserManager.UserRestrictionKey String key)9668     public void clearUserRestriction(@NonNull ComponentName admin,
9669             @UserManager.UserRestrictionKey String key) {
9670         if (mService != null) {
9671             try {
9672                 mService.setUserRestriction(admin, key, false, mParentInstance);
9673             } catch (RemoteException e) {
9674                 throw e.rethrowFromSystemServer();
9675             }
9676         }
9677     }
9678 
9679     /**
9680      * Called by a profile or device owner to get user restrictions set with
9681      * {@link #addUserRestriction(ComponentName, String)}.
9682      * <p>
9683      * The target user may have more restrictions set by the system or other device owner / profile
9684      * owner. To get all the user restrictions currently set, use
9685      * {@link UserManager#getUserRestrictions()}.
9686      * <p>
9687      * The profile owner of an organization-owned managed profile may invoke this method on
9688      * the {@link DevicePolicyManager} instance it obtained from
9689      * {@link #getParentProfileInstance(ComponentName)}, for retrieving device-wide restrictions
9690      * it previously set with {@link #addUserRestriction(ComponentName, String)}.
9691      *
9692      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9693      * @return a {@link Bundle} whose keys are the user restrictions, and the values a
9694      * {@code boolean} indicating whether the restriction is set.
9695      * @throws SecurityException if {@code admin} is not a device or profile owner.
9696      */
getUserRestrictions(@onNull ComponentName admin)9697     public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
9698         Bundle ret = null;
9699         if (mService != null) {
9700             try {
9701                 ret = mService.getUserRestrictions(admin, mParentInstance);
9702             } catch (RemoteException e) {
9703                 throw e.rethrowFromSystemServer();
9704             }
9705         }
9706         return ret == null ? new Bundle() : ret;
9707     }
9708 
9709     /**
9710      * Called by any app to display a support dialog when a feature was disabled by an admin.
9711      * This returns an intent that can be used with {@link Context#startActivity(Intent)} to
9712      * display the dialog. It will tell the user that the feature indicated by {@code restriction}
9713      * was disabled by an admin, and include a link for more information. The default content of
9714      * the dialog can be changed by the restricting admin via
9715      * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not
9716      * set (i.e. the feature is available), then the return value will be {@code null}.
9717      * @param restriction Indicates for which feature the dialog should be displayed. Can be a
9718      *            user restriction from {@link UserManager}, e.g.
9719      *            {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants
9720      *            {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
9721      * @return Intent An intent to be used to start the dialog-activity if the restriction is
9722      *            set by an admin, or null if the restriction does not exist or no admin set it.
9723      */
createAdminSupportIntent(@onNull String restriction)9724     public Intent createAdminSupportIntent(@NonNull String restriction) {
9725         throwIfParentInstance("createAdminSupportIntent");
9726         if (mService != null) {
9727             try {
9728                 return mService.createAdminSupportIntent(restriction);
9729             } catch (RemoteException e) {
9730                 throw e.rethrowFromSystemServer();
9731             }
9732         }
9733         return null;
9734     }
9735 
9736     /**
9737      * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and
9738      * actual package file remain. This function can be called by a device owner, profile owner, or
9739      * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
9740      * {@link #setDelegatedScopes}.
9741      * <p>
9742      * This method can be called on the {@link DevicePolicyManager} instance, returned by
9743      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
9744      * of an organization-owned managed profile and the package must be a system package. If called
9745      * on the parent instance, then the package is hidden or unhidden in the personal profile.
9746      *
9747      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9748      *            {@code null} if the caller is a package access delegate.
9749      * @param packageName The name of the package to hide or unhide.
9750      * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
9751      *            unhidden.
9752      * @return boolean Whether the hidden setting of the package was successfully updated.
9753      * @throws SecurityException if {@code admin} is not a device or profile owner or if called on
9754      *            the parent profile and the {@code admin} is not a profile owner of an
9755      *            organization-owned managed profile.
9756      * @throws IllegalArgumentException if called on the parent profile and the package provided
9757      *            is not a system package.
9758      * @see #setDelegatedScopes
9759      * @see #DELEGATION_PACKAGE_ACCESS
9760      */
setApplicationHidden(@onNull ComponentName admin, String packageName, boolean hidden)9761     public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
9762             boolean hidden) {
9763         if (mService != null) {
9764             try {
9765                 return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName,
9766                         hidden, mParentInstance);
9767             } catch (RemoteException e) {
9768                 throw e.rethrowFromSystemServer();
9769             }
9770         }
9771         return false;
9772     }
9773 
9774     /**
9775      * Determine if a package is hidden. This function can be called by a device owner, profile
9776      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
9777      * {@link #setDelegatedScopes}.
9778      * <p>
9779      * This method can be called on the {@link DevicePolicyManager} instance, returned by
9780      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
9781      * of an organization-owned managed profile and the package must be a system package. If called
9782      * on the parent instance, this will determine whether the package is hidden or unhidden in the
9783      * personal profile.
9784      *
9785      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9786      *            {@code null} if the caller is a package access delegate.
9787      * @param packageName The name of the package to retrieve the hidden status of.
9788      * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
9789      * @throws SecurityException if {@code admin} is not a device or profile owner or if called on
9790      *            the parent profile and the {@code admin} is not a profile owner of an
9791      *            organization-owned managed profile.
9792      * @throws IllegalArgumentException if called on the parent profile and the package provided
9793      *            is not a system package.
9794      * @see #setDelegatedScopes
9795      * @see #DELEGATION_PACKAGE_ACCESS
9796      */
isApplicationHidden(@onNull ComponentName admin, String packageName)9797     public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
9798         if (mService != null) {
9799             try {
9800                 return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName,
9801                         mParentInstance);
9802             } catch (RemoteException e) {
9803                 throw e.rethrowFromSystemServer();
9804             }
9805         }
9806         return false;
9807     }
9808 
9809     /**
9810      * Re-enable a system app that was disabled by default when the user was initialized. This
9811      * function can be called by a device owner, profile owner, or by a delegate given the
9812      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
9813      *
9814      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9815      *            {@code null} if the caller is an enable system app delegate.
9816      * @param packageName The package to be re-enabled in the calling profile.
9817      * @throws SecurityException if {@code admin} is not a device or profile owner.
9818      * @see #setDelegatedScopes
9819      * @see #DELEGATION_PACKAGE_ACCESS
9820      */
enableSystemApp(@onNull ComponentName admin, String packageName)9821     public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
9822         throwIfParentInstance("enableSystemApp");
9823         if (mService != null) {
9824             try {
9825                 mService.enableSystemApp(admin, mContext.getPackageName(), packageName);
9826             } catch (RemoteException e) {
9827                 throw e.rethrowFromSystemServer();
9828             }
9829         }
9830     }
9831 
9832     /**
9833      * Re-enable system apps by intent that were disabled by default when the user was initialized.
9834      * This function can be called by a device owner, profile owner, or by a delegate given the
9835      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
9836      *
9837      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9838      *            {@code null} if the caller is an enable system app delegate.
9839      * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
9840      *            intent will be re-enabled in the calling profile.
9841      * @return int The number of activities that matched the intent and were installed.
9842      * @throws SecurityException if {@code admin} is not a device or profile owner.
9843      * @see #setDelegatedScopes
9844      * @see #DELEGATION_PACKAGE_ACCESS
9845      */
enableSystemApp(@onNull ComponentName admin, Intent intent)9846     public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
9847         throwIfParentInstance("enableSystemApp");
9848         if (mService != null) {
9849             try {
9850                 return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent);
9851             } catch (RemoteException e) {
9852                 throw e.rethrowFromSystemServer();
9853             }
9854         }
9855         return 0;
9856     }
9857 
9858     /**
9859      * Install an existing package that has been installed in another user, or has been kept after
9860      * removal via {@link #setKeepUninstalledPackages}.
9861      * This function can be called by a device owner, profile owner or a delegate given
9862      * the {@link #DELEGATION_INSTALL_EXISTING_PACKAGE} scope via {@link #setDelegatedScopes}.
9863      * When called in a secondary user or managed profile, the user/profile must be affiliated with
9864      * the device. See {@link #isAffiliatedUser}.
9865      *
9866      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9867      * @param packageName The package to be installed in the calling profile.
9868      * @return {@code true} if the app is installed; {@code false} otherwise.
9869      * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
9870      * an affiliated user or profile.
9871      * @see #setKeepUninstalledPackages
9872      * @see #setDelegatedScopes
9873      * @see #isAffiliatedUser
9874      * @see #DELEGATION_PACKAGE_ACCESS
9875      */
installExistingPackage(@onNull ComponentName admin, String packageName)9876     public boolean installExistingPackage(@NonNull ComponentName admin, String packageName) {
9877         throwIfParentInstance("installExistingPackage");
9878         if (mService != null) {
9879             try {
9880                 return mService.installExistingPackage(admin, mContext.getPackageName(),
9881                         packageName);
9882             } catch (RemoteException e) {
9883                 throw e.rethrowFromSystemServer();
9884             }
9885         }
9886         return false;
9887     }
9888 
9889     /**
9890      * Called by a device owner or profile owner to disable account management for a specific type
9891      * of account.
9892      * <p>
9893      * The calling device admin must be a device owner or profile owner. If it is not, a security
9894      * exception will be thrown.
9895      * <p>
9896      * When account management is disabled for an account type, adding or removing an account of
9897      * that type will not be possible.
9898      * <p>
9899      * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
9900      * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
9901      * management for a specific type is disabled.
9902      * <p>
9903      * This method may be called on the {@code DevicePolicyManager} instance returned from
9904      * {@link #getParentProfileInstance(ComponentName)} by the profile owner on an
9905      * organization-owned device, to restrict accounts that may not be managed on the primary
9906      * profile.
9907      *
9908      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9909      * @param accountType For which account management is disabled or enabled.
9910      * @param disabled The boolean indicating that account management will be disabled (true) or
9911      *            enabled (false).
9912      * @throws SecurityException if {@code admin} is not a device or profile owner.
9913      */
setAccountManagementDisabled(@onNull ComponentName admin, String accountType, boolean disabled)9914     public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
9915             boolean disabled) {
9916         if (mService != null) {
9917             try {
9918                 mService.setAccountManagementDisabled(admin, accountType, disabled,
9919                         mParentInstance);
9920             } catch (RemoteException e) {
9921                 throw e.rethrowFromSystemServer();
9922             }
9923         }
9924     }
9925 
9926     /**
9927      * Gets the array of accounts for which account management is disabled by the profile owner
9928      * or device owner.
9929      *
9930      * <p> Account management can be disabled/enabled by calling
9931      * {@link #setAccountManagementDisabled}.
9932      * <p>
9933      * This method may be called on the {@code DevicePolicyManager} instance returned from
9934      * {@link #getParentProfileInstance(ComponentName)}. Note that only a profile owner on
9935      * an organization-owned device can affect account types on the parent profile instance.
9936      *
9937      * @return a list of account types for which account management has been disabled.
9938      *
9939      * @see #setAccountManagementDisabled
9940      */
getAccountTypesWithManagementDisabled()9941     public @Nullable String[] getAccountTypesWithManagementDisabled() {
9942         return getAccountTypesWithManagementDisabledAsUser(myUserId(), mParentInstance);
9943     }
9944 
9945     /**
9946      * @see #getAccountTypesWithManagementDisabled()
9947      * Note that calling this method on the parent profile instance will return the same
9948      * value as calling it on the main {@code DevicePolicyManager} instance.
9949      * @hide
9950      */
getAccountTypesWithManagementDisabledAsUser(int userId)9951     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
9952         return getAccountTypesWithManagementDisabledAsUser(userId, false);
9953     }
9954 
9955     /**
9956      * @see #getAccountTypesWithManagementDisabled()
9957      * @hide
9958      */
getAccountTypesWithManagementDisabledAsUser( int userId, boolean parentInstance)9959     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(
9960             int userId, boolean parentInstance) {
9961         if (mService != null) {
9962             try {
9963                 return mService.getAccountTypesWithManagementDisabledAsUser(userId, parentInstance);
9964             } catch (RemoteException e) {
9965                 throw e.rethrowFromSystemServer();
9966             }
9967         }
9968 
9969         return null;
9970     }
9971 
9972     /**
9973      * Called by device owner or profile owner to set whether a secondary lockscreen needs to be
9974      * shown.
9975      *
9976      * <p>The secondary lockscreen will by displayed after the primary keyguard security screen
9977      * requirements are met. To provide the lockscreen content the DO/PO will need to provide a
9978      * service handling the {@link #ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE} intent action,
9979      * extending the {@link DevicePolicyKeyguardService} class.
9980      *
9981      * <p>Relevant interactions on the secondary lockscreen should be communicated back to the
9982      * keyguard via {@link IKeyguardCallback}, such as when the screen is ready to be dismissed.
9983      *
9984      * <p>This API, and associated APIs, can only be called by the default supervision app when it
9985      * is set as the device owner or profile owner.
9986      *
9987      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9988      * @param enabled Whether or not the lockscreen needs to be shown.
9989      * @throws SecurityException if {@code admin} is not a device or profile owner.
9990      * @see #isSecondaryLockscreenEnabled
9991      * @hide
9992      **/
9993     @SystemApi
setSecondaryLockscreenEnabled(@onNull ComponentName admin, boolean enabled)9994     public void setSecondaryLockscreenEnabled(@NonNull ComponentName admin, boolean enabled) {
9995         throwIfParentInstance("setSecondaryLockscreenEnabled");
9996         if (mService != null) {
9997             try {
9998                 mService.setSecondaryLockscreenEnabled(admin, enabled);
9999             } catch (RemoteException e) {
10000                 throw e.rethrowFromSystemServer();
10001             }
10002         }
10003     }
10004 
10005     /**
10006      * Returns whether the secondary lock screen needs to be shown.
10007      * @see #setSecondaryLockscreenEnabled
10008      * @hide
10009      */
10010     @SystemApi
isSecondaryLockscreenEnabled(@onNull UserHandle userHandle)10011     public boolean isSecondaryLockscreenEnabled(@NonNull UserHandle userHandle) {
10012         throwIfParentInstance("isSecondaryLockscreenEnabled");
10013         if (mService != null) {
10014             try {
10015                 return mService.isSecondaryLockscreenEnabled(userHandle);
10016             } catch (RemoteException e) {
10017                 throw e.rethrowFromSystemServer();
10018             }
10019         }
10020         return false;
10021     }
10022 
10023     /**
10024      * Sets which packages may enter lock task mode.
10025      * <p>
10026      * Any packages that share uid with an allowed package will also be allowed to activate lock
10027      * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
10028      * package list results in locked tasks belonging to those packages to be finished.
10029      * <p>
10030      * This function can only be called by the device owner, a profile owner of an affiliated user
10031      * or profile, or the profile owner when no device owner is set. See {@link #isAffiliatedUser}.
10032      * Any package set via this method will be cleared if the user becomes unaffiliated.
10033      *
10034      * @param packages The list of packages allowed to enter lock task mode
10035      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10036      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
10037      * affiliated user or profile, or the profile owner when no device owner is set.
10038      * @see #isAffiliatedUser
10039      * @see Activity#startLockTask()
10040      * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
10041      * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
10042      * @see UserManager#DISALLOW_CREATE_WINDOWS
10043      */
setLockTaskPackages(@onNull ComponentName admin, @NonNull String[] packages)10044     public void setLockTaskPackages(@NonNull ComponentName admin, @NonNull String[] packages)
10045             throws SecurityException {
10046         throwIfParentInstance("setLockTaskPackages");
10047         if (mService != null) {
10048             try {
10049                 mService.setLockTaskPackages(admin, packages);
10050             } catch (RemoteException e) {
10051                 throw e.rethrowFromSystemServer();
10052             }
10053         }
10054     }
10055 
10056     /**
10057      * Returns the list of packages allowed to start the lock task mode.
10058      *
10059      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
10060      * affiliated user or profile, or the profile owner when no device owner is set.
10061      * @see #isAffiliatedUser
10062      * @see #setLockTaskPackages
10063      */
getLockTaskPackages(@onNull ComponentName admin)10064     public @NonNull String[] getLockTaskPackages(@NonNull ComponentName admin) {
10065         throwIfParentInstance("getLockTaskPackages");
10066         if (mService != null) {
10067             try {
10068                 return mService.getLockTaskPackages(admin);
10069             } catch (RemoteException e) {
10070                 throw e.rethrowFromSystemServer();
10071             }
10072         }
10073         return new String[0];
10074     }
10075 
10076     /**
10077      * This function lets the caller know whether the given component is allowed to start the
10078      * lock task mode.
10079      * @param pkg The package to check
10080      */
isLockTaskPermitted(String pkg)10081     public boolean isLockTaskPermitted(String pkg) {
10082         throwIfParentInstance("isLockTaskPermitted");
10083         if (mService != null) {
10084             try {
10085                 return mService.isLockTaskPermitted(pkg);
10086             } catch (RemoteException e) {
10087                 throw e.rethrowFromSystemServer();
10088             }
10089         }
10090         return false;
10091     }
10092 
10093     /**
10094      * Sets which system features are enabled when the device runs in lock task mode. This method
10095      * doesn't affect the features when lock task mode is inactive. Any system features not included
10096      * in {@code flags} are implicitly disabled when calling this method. By default, only
10097      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS} is enabled; all the other features are disabled. To
10098      * disable the global actions dialog, call this method omitting
10099      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}.
10100      *
10101      * <p>This method can only be called by the device owner, a profile owner of an affiliated
10102      * user or profile, or the profile owner when no device owner is set. See
10103      * {@link #isAffiliatedUser}.
10104      * Any features set using this method are cleared if the user becomes unaffiliated.
10105      *
10106      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10107      * @param flags The system features enabled during lock task mode.
10108      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
10109      * affiliated user or profile, or the profile owner when no device owner is set.
10110      * @see #isAffiliatedUser
10111      **/
setLockTaskFeatures(@onNull ComponentName admin, @LockTaskFeature int flags)10112     public void setLockTaskFeatures(@NonNull ComponentName admin, @LockTaskFeature int flags) {
10113         throwIfParentInstance("setLockTaskFeatures");
10114         if (mService != null) {
10115             try {
10116                 mService.setLockTaskFeatures(admin, flags);
10117             } catch (RemoteException e) {
10118                 throw e.rethrowFromSystemServer();
10119             }
10120         }
10121     }
10122 
10123     /**
10124      * Gets which system features are enabled for LockTask mode.
10125      *
10126      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10127      * @return bitfield of flags. See {@link #setLockTaskFeatures(ComponentName, int)} for a list.
10128      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
10129      * affiliated user or profile, or the profile owner when no device owner is set.
10130      * @see #isAffiliatedUser
10131      * @see #setLockTaskFeatures
10132      */
getLockTaskFeatures(@onNull ComponentName admin)10133     public @LockTaskFeature int getLockTaskFeatures(@NonNull ComponentName admin) {
10134         throwIfParentInstance("getLockTaskFeatures");
10135         if (mService != null) {
10136             try {
10137                 return mService.getLockTaskFeatures(admin);
10138             } catch (RemoteException e) {
10139                 throw e.rethrowFromSystemServer();
10140             }
10141         }
10142         return 0;
10143     }
10144 
10145     /**
10146      * Sets whether preferential network service is enabled on the work profile.
10147      * For example, an organization can have a deal/agreement with a carrier that all of
10148      * the work data from its employees’ devices will be sent via a network service dedicated
10149      * for enterprise use.
10150      *
10151      * An example of a supported preferential network service is the Enterprise
10152      * slice on 5G networks.
10153      *
10154      * By default, preferential network service is disabled on the work profile on supported
10155      * carriers and devices. Admins can explicitly enable it with this API.
10156      * On fully-managed devices this method is unsupported because all traffic is considered
10157      * work traffic.
10158      *
10159      * <p>This method can only be called by the profile owner of a managed profile.
10160      * @param enabled whether preferential network service should be enabled.
10161      * @throws SecurityException if the caller is not the profile owner.
10162      **/
setPreferentialNetworkServiceEnabled(boolean enabled)10163     public void setPreferentialNetworkServiceEnabled(boolean enabled) {
10164         throwIfParentInstance("setPreferentialNetworkServiceEnabled");
10165         if (mService == null) {
10166             return;
10167         }
10168 
10169         try {
10170             mService.setPreferentialNetworkServiceEnabled(enabled);
10171         } catch (RemoteException e) {
10172             throw e.rethrowFromSystemServer();
10173         }
10174     }
10175 
10176     /**
10177      * Indicates whether preferential network service is enabled.
10178      *
10179      * <p>This method can be called by the profile owner of a managed profile.
10180      *
10181      * @return whether preferential network service is enabled.
10182      * @throws SecurityException if the caller is not the profile owner.
10183      */
isPreferentialNetworkServiceEnabled()10184     public boolean isPreferentialNetworkServiceEnabled() {
10185         throwIfParentInstance("isPreferentialNetworkServiceEnabled");
10186         if (mService == null) {
10187             return false;
10188         }
10189         try {
10190             return mService.isPreferentialNetworkServiceEnabled(myUserId());
10191         } catch (RemoteException e) {
10192             throw e.rethrowFromSystemServer();
10193         }
10194     }
10195 
10196     /**
10197      * This method is mostly deprecated.
10198      * Most of the settings that still have an effect have dedicated setter methods or user
10199      * restrictions. See individual settings for details.
10200      * <p>
10201      * Called by device owner to update {@link android.provider.Settings.Global} settings.
10202      * Validation that the value of the setting is in the correct form for the setting type should
10203      * be performed by the caller.
10204      * <p>
10205      * The settings that can be updated with this method are:
10206      * <ul>
10207      * <li>{@link android.provider.Settings.Global#ADB_ENABLED} : use
10208      * {@link UserManager#DISALLOW_DEBUGGING_FEATURES} instead to restrict users from enabling
10209      * debugging features and this setting to turn adb on.</li>
10210      * <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
10211      * <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only
10212      * available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
10213      * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
10214      * <li>{@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This
10215      * setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
10216      * </ul>
10217      * <p>
10218      * The following settings used to be supported, but can be controlled in other ways:
10219      * <ul>
10220      * <li>{@link android.provider.Settings.Global#AUTO_TIME} : Use {@link #setAutoTimeEnabled} and
10221      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} instead.</li>
10222      * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE} : Use
10223      * {@link #setAutoTimeZoneEnabled} and {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
10224      * instead.</li>
10225      * <li>{@link android.provider.Settings.Global#DATA_ROAMING} : Use
10226      * {@link UserManager#DISALLOW_DATA_ROAMING} instead.</li>
10227      * </ul>
10228      * <p>
10229      * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
10230      * <ul>
10231      * <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use
10232      * {@link android.bluetooth.BluetoothAdapter#enable()} and
10233      * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
10234      * <li>{@link android.provider.Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
10235      * <li>{@link android.provider.Settings.Global#MODE_RINGER}. Use
10236      * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
10237      * <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li>
10238      * <li>{@link android.provider.Settings.Global#WIFI_ON}. Use
10239      * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
10240      * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}. No longer has effect.</li>
10241      * </ul>
10242      *
10243      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10244      * @param setting The name of the setting to update.
10245      * @param value The value to update the setting to.
10246      * @throws SecurityException if {@code admin} is not a device owner.
10247      */
setGlobalSetting(@onNull ComponentName admin, String setting, String value)10248     public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
10249         throwIfParentInstance("setGlobalSetting");
10250         if (mService != null) {
10251             try {
10252                 mService.setGlobalSetting(admin, setting, value);
10253             } catch (RemoteException e) {
10254                 throw e.rethrowFromSystemServer();
10255             }
10256         }
10257     }
10258 
10259     /** @hide */
10260     @StringDef({
10261             Settings.System.SCREEN_BRIGHTNESS_MODE,
10262             Settings.System.SCREEN_BRIGHTNESS,
10263             Settings.System.SCREEN_BRIGHTNESS_FLOAT,
10264             Settings.System.SCREEN_OFF_TIMEOUT
10265     })
10266     @Retention(RetentionPolicy.SOURCE)
10267     public @interface SystemSettingsWhitelist {}
10268 
10269     /**
10270      * Called by a device or profile owner to update {@link android.provider.Settings.System}
10271      * settings. Validation that the value of the setting is in the correct form for the setting
10272      * type should be performed by the caller.
10273      * <p>
10274      * The settings that can be updated by a device owner or profile owner of secondary user with
10275      * this method are:
10276      * <ul>
10277      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS}</li>
10278      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS_MODE}</li>
10279      * <li>{@link android.provider.Settings.System#SCREEN_OFF_TIMEOUT}</li>
10280      * </ul>
10281      * <p>
10282      *
10283      * @see android.provider.Settings.System#SCREEN_OFF_TIMEOUT
10284      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10285      * @param setting The name of the setting to update.
10286      * @param value The value to update the setting to.
10287      * @throws SecurityException if {@code admin} is not a device or profile owner.
10288      */
setSystemSetting(@onNull ComponentName admin, @NonNull @SystemSettingsWhitelist String setting, String value)10289     public void setSystemSetting(@NonNull ComponentName admin,
10290             @NonNull @SystemSettingsWhitelist String setting, String value) {
10291         throwIfParentInstance("setSystemSetting");
10292         if (mService != null) {
10293             try {
10294                 mService.setSystemSetting(admin, setting, value);
10295             } catch (RemoteException e) {
10296                 throw e.rethrowFromSystemServer();
10297             }
10298         }
10299     }
10300 
10301     /**
10302      * Called by a device owner or a profile owner of an organization-owned managed profile to
10303      * control whether the user can change networks configured by the admin.
10304      * <p>
10305      * WiFi network configuration lockdown is controlled by a global settings
10306      * {@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN} and calling
10307      * this API effectively modifies the global settings. Previously device owners can also
10308      * control this directly via {@link #setGlobalSetting} but they are recommended to switch
10309      * to this API.
10310      *
10311      * @param admin             admin Which {@link DeviceAdminReceiver} this request is associated
10312      *                          with.
10313      * @param lockdown Whether the admin configured networks should be unmodifiable by the
10314      *                          user.
10315      * @throws SecurityException if caller is not a device owner or a profile owner of an
10316      *                           organization-owned managed profile.
10317      */
setConfiguredNetworksLockdownState(@onNull ComponentName admin, boolean lockdown)10318     public void setConfiguredNetworksLockdownState(@NonNull ComponentName admin, boolean lockdown) {
10319         throwIfParentInstance("setConfiguredNetworksLockdownState");
10320         if (mService != null) {
10321             try {
10322                 mService.setConfiguredNetworksLockdownState(admin, lockdown);
10323             } catch (RemoteException e) {
10324                 throw e.rethrowFromSystemServer();
10325             }
10326         }
10327     }
10328 
10329     /**
10330      * Called by a device owner or a profile owner of an organization-owned managed profile to
10331      * determine whether the user is prevented from modifying networks configured by the admin.
10332      *
10333      * @param admin             admin Which {@link DeviceAdminReceiver} this request is associated
10334      *                          with.
10335      * @throws SecurityException if caller is not a device owner or a profile owner of an
10336      *                           organization-owned managed profile.
10337      */
hasLockdownAdminConfiguredNetworks(@onNull ComponentName admin)10338     public boolean hasLockdownAdminConfiguredNetworks(@NonNull ComponentName admin) {
10339         throwIfParentInstance("hasLockdownAdminConfiguredNetworks");
10340         if (mService != null) {
10341             try {
10342                 return mService.hasLockdownAdminConfiguredNetworks(admin);
10343             } catch (RemoteException e) {
10344                 throw e.rethrowFromSystemServer();
10345             }
10346         }
10347         return false;
10348     }
10349 
10350     /**
10351      * Called by a device owner or a profile owner of an organization-owned managed
10352      * profile to set the system wall clock time. This only takes effect if called when
10353      * {@link android.provider.Settings.Global#AUTO_TIME} is 0, otherwise {@code false}
10354      * will be returned.
10355      *
10356      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
10357      * @param millis time in milliseconds since the Epoch
10358      * @return {@code true} if set time succeeded, {@code false} otherwise.
10359      * @throws SecurityException if {@code admin} is not a device owner or a profile owner
10360      * of an organization-owned managed profile.
10361      */
setTime(@onNull ComponentName admin, long millis)10362     public boolean setTime(@NonNull ComponentName admin, long millis) {
10363         throwIfParentInstance("setTime");
10364         if (mService != null) {
10365             try {
10366                 return mService.setTime(admin, millis);
10367             } catch (RemoteException e) {
10368                 throw e.rethrowFromSystemServer();
10369             }
10370         }
10371         return false;
10372     }
10373 
10374     /**
10375      * Called by a device owner or a profile owner of an organization-owned managed
10376      * profile to set the system's persistent default time zone. This only takes
10377      * effect if called when {@link android.provider.Settings.Global#AUTO_TIME_ZONE}
10378      * is 0, otherwise {@code false} will be returned.
10379      *
10380      * @see android.app.AlarmManager#setTimeZone(String)
10381      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
10382      * @param timeZone one of the Olson ids from the list returned by
10383      *     {@link java.util.TimeZone#getAvailableIDs}
10384      * @return {@code true} if set timezone succeeded, {@code false} otherwise.
10385      * @throws SecurityException if {@code admin} is not a device owner or a profile owner
10386      * of an organization-owned managed profile.
10387      */
setTimeZone(@onNull ComponentName admin, String timeZone)10388     public boolean setTimeZone(@NonNull ComponentName admin, String timeZone) {
10389         throwIfParentInstance("setTimeZone");
10390         if (mService != null) {
10391             try {
10392                 return mService.setTimeZone(admin, timeZone);
10393             } catch (RemoteException e) {
10394                 throw e.rethrowFromSystemServer();
10395             }
10396         }
10397         return false;
10398     }
10399 
10400     /**
10401      * Called by device owners to set the user's global location setting.
10402      *
10403      *
10404      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
10405      * @param locationEnabled whether location should be enabled or disabled. <b>Note: </b> on
10406      * {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, calls to
10407      * disable will be ignored.
10408      * @throws SecurityException if {@code admin} is not a device owner.
10409      */
setLocationEnabled(@onNull ComponentName admin, boolean locationEnabled)10410     public void setLocationEnabled(@NonNull ComponentName admin, boolean locationEnabled) {
10411         throwIfParentInstance("setLocationEnabled");
10412         if (mService != null) {
10413             try {
10414                 mService.setLocationEnabled(admin, locationEnabled);
10415             } catch (RemoteException e) {
10416                 throw e.rethrowFromSystemServer();
10417             }
10418         }
10419     }
10420 
10421     /**
10422      * This method is mostly deprecated.
10423      * Most of the settings that still have an effect have dedicated setter methods
10424      * (e.g. {@link #setLocationEnabled}) or user restrictions.
10425      * <p>
10426      *
10427      * Called by profile or device owners to update {@link android.provider.Settings.Secure}
10428      * settings. Validation that the value of the setting is in the correct form for the setting
10429      * type should be performed by the caller.
10430      * <p>
10431      * The settings that can be updated by a profile or device owner with this method are:
10432      * <ul>
10433      * <li>{@link android.provider.Settings.Secure#DEFAULT_INPUT_METHOD}</li>
10434      * <li>{@link android.provider.Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
10435      * </ul>
10436      * <p>
10437      * A device owner can additionally update the following settings:
10438      * <ul>
10439      * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}, but see note below.</li>
10440      * </ul>
10441      *
10442      * <strong>Note: Starting from Android O, apps should no longer call this method with the
10443      * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is
10444      * deprecated. Instead, device owners or profile owners should use the restriction
10445      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}.
10446      * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method
10447      * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS},
10448      * an {@link UnsupportedOperationException} is thrown.
10449      *
10450      * Starting from Android Q, the device and profile owner can also call
10451      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY} to restrict unknown sources for
10452      * all users.
10453      * </strong>
10454      *
10455      * <strong>Note: Starting from Android R, apps should no longer call this method with the
10456      * setting {@link android.provider.Settings.Secure#LOCATION_MODE}, which is deprecated. Instead,
10457      * device owners should call {@link #setLocationEnabled(ComponentName, boolean)}. This will be
10458      * enforced for all apps targeting Android R or above.
10459      * </strong>
10460      *
10461      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10462      * @param setting The name of the setting to update.
10463      * @param value The value to update the setting to.
10464      * @throws SecurityException if {@code admin} is not a device or profile owner.
10465      */
setSecureSetting(@onNull ComponentName admin, String setting, String value)10466     public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
10467         throwIfParentInstance("setSecureSetting");
10468 
10469         if (mService != null) {
10470             try {
10471                 mService.setSecureSetting(admin, setting, value);
10472             } catch (RemoteException e) {
10473                 throw e.rethrowFromSystemServer();
10474             }
10475         }
10476     }
10477 
10478     /**
10479      * Designates a specific service component as the provider for making permission requests of a
10480      * local or remote administrator of the user.
10481      * <p/>
10482      * Only a device owner or profile owner can designate the restrictions provider.
10483      *
10484      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10485      * @param provider The component name of the service that implements
10486      *            {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
10487      *            provider previously assigned.
10488      * @throws SecurityException if {@code admin} is not a device or profile owner.
10489      */
setRestrictionsProvider(@onNull ComponentName admin, @Nullable ComponentName provider)10490     public void setRestrictionsProvider(@NonNull ComponentName admin,
10491             @Nullable ComponentName provider) {
10492         throwIfParentInstance("setRestrictionsProvider");
10493         if (mService != null) {
10494             try {
10495                 mService.setRestrictionsProvider(admin, provider);
10496             } catch (RemoteException re) {
10497                 throw re.rethrowFromSystemServer();
10498             }
10499         }
10500     }
10501 
10502     /**
10503      * Called by profile or device owners to set the global volume mute on or off.
10504      * This has no effect when set on a managed profile.
10505      *
10506      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10507      * @param on {@code true} to mute global volume, {@code false} to turn mute off.
10508      * @throws SecurityException if {@code admin} is not a device or profile owner.
10509      */
setMasterVolumeMuted(@onNull ComponentName admin, boolean on)10510     public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
10511         throwIfParentInstance("setMasterVolumeMuted");
10512         if (mService != null) {
10513             try {
10514                 mService.setMasterVolumeMuted(admin, on);
10515             } catch (RemoteException re) {
10516                 throw re.rethrowFromSystemServer();
10517             }
10518         }
10519     }
10520 
10521     /**
10522      * Called by profile or device owners to check whether the global volume mute is on or off.
10523      *
10524      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10525      * @return {@code true} if global volume is muted, {@code false} if it's not.
10526      * @throws SecurityException if {@code admin} is not a device or profile owner.
10527      */
isMasterVolumeMuted(@onNull ComponentName admin)10528     public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
10529         throwIfParentInstance("isMasterVolumeMuted");
10530         if (mService != null) {
10531             try {
10532                 return mService.isMasterVolumeMuted(admin);
10533             } catch (RemoteException re) {
10534                 throw re.rethrowFromSystemServer();
10535             }
10536         }
10537         return false;
10538     }
10539 
10540     /**
10541      * Change whether a user can uninstall a package. This function can be called by a device owner,
10542      * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via
10543      * {@link #setDelegatedScopes}.
10544      *
10545      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10546      *             {@code null} if the caller is a block uninstall delegate.
10547      * @param packageName package to change.
10548      * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
10549      * @throws SecurityException if {@code admin} is not a device or profile owner.
10550      * @see #setDelegatedScopes
10551      * @see #DELEGATION_BLOCK_UNINSTALL
10552      */
setUninstallBlocked(@ullable ComponentName admin, String packageName, boolean uninstallBlocked)10553     public void setUninstallBlocked(@Nullable ComponentName admin, String packageName,
10554             boolean uninstallBlocked) {
10555         throwIfParentInstance("setUninstallBlocked");
10556         if (mService != null) {
10557             try {
10558                 mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName,
10559                     uninstallBlocked);
10560             } catch (RemoteException re) {
10561                 throw re.rethrowFromSystemServer();
10562             }
10563         }
10564     }
10565 
10566     /**
10567      * Check whether the user has been blocked by device policy from uninstalling a package.
10568      * Requires the caller to be the profile owner if checking a specific admin's policy.
10569      * <p>
10570      * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
10571      * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
10572      * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
10573      * will cause a NullPointerException to be raised.
10574      *
10575      * @param admin The name of the admin component whose blocking policy will be checked, or
10576      *            {@code null} to check whether any admin has blocked the uninstallation.
10577      * @param packageName package to check.
10578      * @return true if uninstallation is blocked.
10579      * @throws SecurityException if {@code admin} is not a device or profile owner.
10580      */
isUninstallBlocked(@ullable ComponentName admin, String packageName)10581     public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
10582         throwIfParentInstance("isUninstallBlocked");
10583         if (mService != null) {
10584             try {
10585                 return mService.isUninstallBlocked(admin, packageName);
10586             } catch (RemoteException re) {
10587                 throw re.rethrowFromSystemServer();
10588             }
10589         }
10590         return false;
10591     }
10592 
10593     /**
10594      * Called by the profile owner of a managed profile to enable widget providers from a given
10595      * package to be available in the parent profile. As a result the user will be able to add
10596      * widgets from the allowlisted package running under the profile to a widget host which runs
10597      * under the parent profile, for example the home screen. Note that a package may have zero or
10598      * more provider components, where each component provides a different widget type.
10599      * <p>
10600      * <strong>Note:</strong> By default no widget provider package is allowlisted.
10601      *
10602      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10603      * @param packageName The package from which widget providers are allowlisted.
10604      * @return Whether the package was added.
10605      * @throws SecurityException if {@code admin} is not a profile owner.
10606      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
10607      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
10608      */
addCrossProfileWidgetProvider(@onNull ComponentName admin, String packageName)10609     public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
10610         throwIfParentInstance("addCrossProfileWidgetProvider");
10611         if (mService != null) {
10612             try {
10613                 return mService.addCrossProfileWidgetProvider(admin, packageName);
10614             } catch (RemoteException re) {
10615                 throw re.rethrowFromSystemServer();
10616             }
10617         }
10618         return false;
10619     }
10620 
10621     /**
10622      * Called by the profile owner of a managed profile to disable widget providers from a given
10623      * package to be available in the parent profile. For this method to take effect the package
10624      * should have been added via
10625      * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
10626      * <p>
10627      * <strong>Note:</strong> By default no widget provider package is allowlisted.
10628      *
10629      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10630      * @param packageName The package from which widget providers are no longer allowlisted.
10631      * @return Whether the package was removed.
10632      * @throws SecurityException if {@code admin} is not a profile owner.
10633      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
10634      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
10635      */
removeCrossProfileWidgetProvider( @onNull ComponentName admin, String packageName)10636     public boolean removeCrossProfileWidgetProvider(
10637             @NonNull ComponentName admin, String packageName) {
10638         throwIfParentInstance("removeCrossProfileWidgetProvider");
10639         if (mService != null) {
10640             try {
10641                 return mService.removeCrossProfileWidgetProvider(admin, packageName);
10642             } catch (RemoteException re) {
10643                 throw re.rethrowFromSystemServer();
10644             }
10645         }
10646         return false;
10647     }
10648 
10649     /**
10650      * Called by the profile owner of a managed profile to query providers from which packages are
10651      * available in the parent profile.
10652      *
10653      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10654      * @return The allowlisted package list.
10655      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
10656      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
10657      * @throws SecurityException if {@code admin} is not a profile owner.
10658      */
getCrossProfileWidgetProviders(@onNull ComponentName admin)10659     public @NonNull List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
10660         throwIfParentInstance("getCrossProfileWidgetProviders");
10661         if (mService != null) {
10662             try {
10663                 List<String> providers = mService.getCrossProfileWidgetProviders(admin);
10664                 if (providers != null) {
10665                     return providers;
10666                 }
10667             } catch (RemoteException re) {
10668                 throw re.rethrowFromSystemServer();
10669             }
10670         }
10671         return Collections.emptyList();
10672     }
10673 
10674     /**
10675      * Called by profile or device owners to set the user's photo.
10676      *
10677      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10678      * @param icon the bitmap to set as the photo.
10679      * @throws SecurityException if {@code admin} is not a device or profile owner.
10680      */
setUserIcon(@onNull ComponentName admin, Bitmap icon)10681     public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
10682         throwIfParentInstance("setUserIcon");
10683         try {
10684             mService.setUserIcon(admin, icon);
10685         } catch (RemoteException re) {
10686             throw re.rethrowFromSystemServer();
10687         }
10688     }
10689 
10690     /**
10691      * Called by device owners or profile owners of an organization-owned managed profile to to set
10692      * a local system update policy. When a new policy is set,
10693      * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
10694      * <p>
10695      * If the supplied system update policy has freeze periods set but the freeze periods do not
10696      * meet 90-day maximum length or 60-day minimum separation requirement set out in
10697      * {@link SystemUpdatePolicy#setFreezePeriods},
10698      * {@link SystemUpdatePolicy.ValidationFailedException} will the thrown. Note that the system
10699      * keeps a record of freeze periods the device experienced previously, and combines them with
10700      * the new freeze periods to be set when checking the maximum freeze length and minimum freeze
10701      * separation constraints. As a result, freeze periods that passed validation during
10702      * {@link SystemUpdatePolicy#setFreezePeriods} might fail the additional checks here due to
10703      * the freeze period history. If this is causing issues during development,
10704      * {@code adb shell dpm clear-freeze-period-record} can be used to clear the record.
10705      *
10706      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
10707      *            components in the device owner package can set system update policies and the most
10708      *            recent policy takes effect.
10709      * @param policy the new policy, or {@code null} to clear the current policy.
10710      * @throws SecurityException if {@code admin} is not a device owner or a profile owner of an
10711      *      organization-owned managed profile.
10712      * @throws IllegalArgumentException if the policy type or maintenance window is not valid.
10713      * @throws SystemUpdatePolicy.ValidationFailedException if the policy's freeze period does not
10714      *             meet the requirement.
10715      * @see SystemUpdatePolicy
10716      * @see SystemUpdatePolicy#setFreezePeriods(List)
10717      */
setSystemUpdatePolicy(@onNull ComponentName admin, SystemUpdatePolicy policy)10718     public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
10719         throwIfParentInstance("setSystemUpdatePolicy");
10720         if (mService != null) {
10721             try {
10722                 mService.setSystemUpdatePolicy(admin, policy);
10723             } catch (RemoteException re) {
10724                 throw re.rethrowFromSystemServer();
10725             }
10726         }
10727     }
10728 
10729     /**
10730      * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
10731      *
10732      * @return The current policy object, or {@code null} if no policy is set.
10733      */
getSystemUpdatePolicy()10734     public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
10735         throwIfParentInstance("getSystemUpdatePolicy");
10736         if (mService != null) {
10737             try {
10738                 return mService.getSystemUpdatePolicy();
10739             } catch (RemoteException re) {
10740                 throw re.rethrowFromSystemServer();
10741             }
10742         }
10743         return null;
10744     }
10745 
10746     /**
10747      * Reset record of previous system update freeze period the device went through.
10748      * @hide
10749      */
10750     @TestApi
10751     @RequiresPermission(android.Manifest.permission.CLEAR_FREEZE_PERIOD)
clearSystemUpdatePolicyFreezePeriodRecord()10752     public void clearSystemUpdatePolicyFreezePeriodRecord() {
10753         throwIfParentInstance("clearSystemUpdatePolicyFreezePeriodRecord");
10754         if (mService == null) {
10755             return;
10756         }
10757         try {
10758             mService.clearSystemUpdatePolicyFreezePeriodRecord();
10759         } catch (RemoteException re) {
10760             throw re.rethrowFromSystemServer();
10761         }
10762     }
10763 
10764     /**
10765      * Called by a device owner or profile owner of secondary users that is affiliated with the
10766      * device to disable the keyguard altogether.
10767      * <p>
10768      * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
10769      * type. However, this call has no effect if a password, pin or pattern is currently set. If a
10770      * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
10771      * disabled.
10772      *
10773      * <p>
10774      * As of {@link android.os.Build.VERSION_CODES#P}, this call also dismisses the
10775      * keyguard if it is currently shown.
10776      *
10777      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10778      * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
10779      * @return {@code false} if attempting to disable the keyguard while a lock password was in
10780      *         place. {@code true} otherwise.
10781      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
10782      * secondary user that is affiliated with the device.
10783      * @see #isAffiliatedUser
10784      * @see #getSecondaryUsers
10785      */
setKeyguardDisabled(@onNull ComponentName admin, boolean disabled)10786     public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
10787         throwIfParentInstance("setKeyguardDisabled");
10788         try {
10789             return mService.setKeyguardDisabled(admin, disabled);
10790         } catch (RemoteException re) {
10791             throw re.rethrowFromSystemServer();
10792         }
10793     }
10794 
10795     /**
10796      * Called by device owner or profile owner of secondary users that is affiliated with the
10797      * device to disable the status bar. Disabling the status bar blocks notifications and quick
10798      * settings.
10799      * <p>
10800      * <strong>Note:</strong> This method has no effect for LockTask mode. The behavior of the
10801      * status bar in LockTask mode can be configured with
10802      * {@link #setLockTaskFeatures(ComponentName, int)}. Calls to this method when the device is in
10803      * LockTask mode will be registered, but will only take effect when the device leaves LockTask
10804      * mode.
10805      *
10806      * <p>This policy does not have any effect while on the lock screen, where the status bar will
10807      * not be disabled. Using LockTask instead of this method is recommended.
10808      *
10809      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10810      * @param disabled {@code true} disables the status bar, {@code false} reenables it.
10811      * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
10812      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
10813      * secondary user that is affiliated with the device.
10814      * @see #isAffiliatedUser
10815      * @see #getSecondaryUsers
10816      */
setStatusBarDisabled(@onNull ComponentName admin, boolean disabled)10817     public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
10818         throwIfParentInstance("setStatusBarDisabled");
10819         try {
10820             return mService.setStatusBarDisabled(admin, disabled);
10821         } catch (RemoteException re) {
10822             throw re.rethrowFromSystemServer();
10823         }
10824     }
10825 
10826     /**
10827      * Called by the system update service to notify device and profile owners of pending system
10828      * updates.
10829      *
10830      * This method should only be used when it is unknown whether the pending system
10831      * update is a security patch. Otherwise, use
10832      * {@link #notifyPendingSystemUpdate(long, boolean)}.
10833      *
10834      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
10835      *         indicating when the current pending update was first available. {@code -1} if no
10836      *         update is available.
10837      * @see #notifyPendingSystemUpdate(long, boolean)
10838      * @hide
10839      */
10840     @SystemApi
10841     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime)10842     public void notifyPendingSystemUpdate(long updateReceivedTime) {
10843         throwIfParentInstance("notifyPendingSystemUpdate");
10844         if (mService != null) {
10845             try {
10846                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime));
10847             } catch (RemoteException re) {
10848                 throw re.rethrowFromSystemServer();
10849             }
10850         }
10851     }
10852 
10853     /**
10854      * Called by the system update service to notify device and profile owners of pending system
10855      * updates.
10856      *
10857      * This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
10858      * when it is known whether the pending system update is a security patch.
10859      *
10860      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
10861      *         indicating when the current pending update was first available. {@code -1} if no
10862      *         update is available.
10863      * @param isSecurityPatch {@code true} if this system update is purely a security patch;
10864      *         {@code false} if not.
10865      * @see #notifyPendingSystemUpdate(long)
10866      * @hide
10867      */
10868     @SystemApi
10869     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch)10870     public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) {
10871         throwIfParentInstance("notifyPendingSystemUpdate");
10872         if (mService != null) {
10873             try {
10874                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime,
10875                         isSecurityPatch));
10876             } catch (RemoteException re) {
10877                 throw re.rethrowFromSystemServer();
10878             }
10879         }
10880     }
10881 
10882     /**
10883      * Called by device or profile owners to get information about a pending system update.
10884      *
10885      * @param admin Which profile or device owner this request is associated with.
10886      * @return Information about a pending system update or {@code null} if no update pending.
10887      * @throws SecurityException if {@code admin} is not a device or profile owner.
10888      * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long)
10889      */
getPendingSystemUpdate(@onNull ComponentName admin)10890     public @Nullable SystemUpdateInfo getPendingSystemUpdate(@NonNull ComponentName admin) {
10891         throwIfParentInstance("getPendingSystemUpdate");
10892         try {
10893             return mService.getPendingSystemUpdate(admin);
10894         } catch (RemoteException re) {
10895             throw re.rethrowFromSystemServer();
10896         }
10897     }
10898 
10899     /**
10900      * Set the default response for future runtime permission requests by applications. This
10901      * function can be called by a device owner, profile owner, or by a delegate given the
10902      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
10903      * The policy can allow for normal operation which prompts the user to grant a permission, or
10904      * can allow automatic granting or denying of runtime permission requests by an application.
10905      * This also applies to new permissions declared by app updates. When a permission is denied or
10906      * granted this way, the effect is equivalent to setting the permission * grant state via
10907      * {@link #setPermissionGrantState}.
10908      * <p/>
10909      * As this policy only acts on runtime permission requests, it only applies to applications
10910      * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
10911      *
10912      * <p>
10913      * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, an auto-grant
10914      * policy will not apply to certain sensors-related permissions on some configurations.
10915      * See {@link #setPermissionGrantState(ComponentName, String, String, int)} for the list of
10916      * permissions affected, and the behavior change for managed profiles and fully-managed
10917      * devices.
10918      *
10919      * @param admin Which profile or device owner this request is associated with.
10920      * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
10921      *            {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
10922      * @throws SecurityException if {@code admin} is not a device or profile owner.
10923      * @see #setPermissionGrantState
10924      * @see #setDelegatedScopes
10925      * @see #DELEGATION_PERMISSION_GRANT
10926      */
setPermissionPolicy(@onNull ComponentName admin, int policy)10927     public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
10928         throwIfParentInstance("setPermissionPolicy");
10929         try {
10930             mService.setPermissionPolicy(admin, mContext.getPackageName(), policy);
10931         } catch (RemoteException re) {
10932             throw re.rethrowFromSystemServer();
10933         }
10934     }
10935 
10936     /**
10937      * Returns the current runtime permission policy set by the device or profile owner. The
10938      * default is {@link #PERMISSION_POLICY_PROMPT}.
10939      *
10940      * @param admin Which profile or device owner this request is associated with.
10941      * @return the current policy for future permission requests.
10942      */
getPermissionPolicy(ComponentName admin)10943     public int getPermissionPolicy(ComponentName admin) {
10944         throwIfParentInstance("getPermissionPolicy");
10945         try {
10946             return mService.getPermissionPolicy(admin);
10947         } catch (RemoteException re) {
10948             throw re.rethrowFromSystemServer();
10949         }
10950     }
10951 
10952     /**
10953      * Sets the grant state of a runtime permission for a specific application. The state can be
10954      * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
10955      * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
10956      * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
10957      * the permission is granted and the user cannot manage it through the UI. This method can only
10958      * be called by a profile owner, device owner, or a delegate given the
10959      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
10960      * <p/>
10961      * Note that user cannot manage other permissions in the affected group through the UI
10962      * either and their granted state will be kept as the current value. Thus, it's recommended that
10963      * you set the grant state of all the permissions in the affected group.
10964      * <p/>
10965      * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
10966      * the permission. It retains the previous grant, if any.
10967      * <p/>
10968      * Device admins with a {@code targetSdkVersion} &lt; {@link android.os.Build.VERSION_CODES#Q}
10969      * cannot grant and revoke permissions for applications built with a {@code targetSdkVersion}
10970      * &lt; {@link android.os.Build.VERSION_CODES#M}.
10971      * <p/>
10972      * Admins with a {@code targetSdkVersion} &ge; {@link android.os.Build.VERSION_CODES#Q} can
10973      * grant and revoke permissions of all apps. Similar to the user revoking a permission from a
10974      * application built with a {@code targetSdkVersion} &lt;
10975      * {@link android.os.Build.VERSION_CODES#M} the app-op matching the permission is set to
10976      * {@link android.app.AppOpsManager#MODE_IGNORED}, but the permission stays granted.
10977      * <p>
10978      * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, control over
10979      * the following, sensors-related, permissions is restricted:
10980      * <ul>
10981      *    <li>Manifest.permission.ACCESS_FINE_LOCATION</li>
10982      *    <li>Manifest.permission.ACCESS_BACKGROUND_LOCATION</li>
10983      *    <li>Manifest.permission.ACCESS_COARSE_LOCATION</li>
10984      *    <li>Manifest.permission.CAMERA</li>
10985      *    <li>Manifest.permission.RECORD_AUDIO</li>
10986      *    <li>Manifest.permission.RECORD_BACKGROUND_AUDIO</li>
10987      *    <li>Manifest.permission.ACTIVITY_RECOGNITION</li>
10988      *    <li>Manifest.permission.BODY_SENSORS</li>
10989      * </ul>
10990      * <p>
10991      * A profile owner may not grant these permissions (i.e. call this method with any of the
10992      * permissions listed above and {@code grantState} of {@code #PERMISSION_GRANT_STATE_GRANTED}),
10993      * but may deny them.
10994      * <p>
10995      * A device owner, by default, may continue granting these permissions. However, for increased
10996      * user control, the admin may opt out of controlling grants for these permissions by including
10997      * {@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT} in the provisioning parameters.
10998      * In that case the device owner's control will be limited do denying these permissions.
10999      * <p>
11000      * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, control over
11001      * the following permissions are restricted for managed profile owners:
11002      * <ul>
11003      *    <li>Manifest.permission.READ_SMS</li>
11004      * </ul>
11005      * <p>
11006      * A managed profile owner may not grant these permissions (i.e. call this method with any of
11007      * the permissions listed above and {@code grantState} of
11008      * {@code #PERMISSION_GRANT_STATE_GRANTED}), but may deny them.
11009      * <p>
11010      * Attempts by the admin to grant these permissions, when the admin is restricted from doing
11011      * so, will be silently ignored (no exception will be thrown).
11012      *
11013      * @param admin Which profile or device owner this request is associated with.
11014      * @param packageName The application to grant or revoke a permission to.
11015      * @param permission The permission to grant or revoke.
11016      * @param grantState The permission grant state which is one of
11017      *            {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
11018      *            {@link #PERMISSION_GRANT_STATE_GRANTED},
11019      * @return whether the permission was successfully granted or revoked.
11020      * @throws SecurityException if {@code admin} is not a device or profile owner.
11021      * @see #PERMISSION_GRANT_STATE_DENIED
11022      * @see #PERMISSION_GRANT_STATE_DEFAULT
11023      * @see #PERMISSION_GRANT_STATE_GRANTED
11024      * @see #setDelegatedScopes
11025      * @see #DELEGATION_PERMISSION_GRANT
11026      */
setPermissionGrantState(@onNull ComponentName admin, @NonNull String packageName, @NonNull String permission, @PermissionGrantState int grantState)11027     public boolean setPermissionGrantState(@NonNull ComponentName admin,
11028             @NonNull String packageName, @NonNull String permission,
11029             @PermissionGrantState int grantState) {
11030         throwIfParentInstance("setPermissionGrantState");
11031         try {
11032             CompletableFuture<Boolean> result = new CompletableFuture<>();
11033 
11034             mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName,
11035                     permission, grantState, new RemoteCallback((b) -> result.complete(b != null)));
11036 
11037             // Timeout
11038             BackgroundThread.getHandler().sendMessageDelayed(
11039                     obtainMessage(CompletableFuture::complete, result, false),
11040                     20_000);
11041 
11042             return result.get();
11043         } catch (RemoteException re) {
11044             throw re.rethrowFromSystemServer();
11045         } catch (InterruptedException | ExecutionException e) {
11046             throw new RuntimeException(e);
11047         }
11048     }
11049 
11050     /**
11051      * Returns the current grant state of a runtime permission for a specific application. This
11052      * function can be called by a device owner, profile owner, or by a delegate given the
11053      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
11054      *
11055      * @param admin Which profile or device owner this request is associated with, or {@code null}
11056      *            if the caller is a permission grant delegate.
11057      * @param packageName The application to check the grant state for.
11058      * @param permission The permission to check for.
11059      * @return the current grant state specified by device policy. If the profile or device owner
11060      *         has not set a grant state, the return value is
11061      *         {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
11062      *         permission is currently granted for the package.
11063      *         <p/>
11064      *         If a grant state was set by the profile or device owner, then the return value will
11065      *         be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
11066      *         {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
11067      *         currently denied or granted.
11068      * @throws SecurityException if {@code admin} is not a device or profile owner.
11069      * @see #setPermissionGrantState(ComponentName, String, String, int)
11070      * @see PackageManager#checkPermission(String, String)
11071      * @see #setDelegatedScopes
11072      * @see #DELEGATION_PERMISSION_GRANT
11073      */
getPermissionGrantState(@ullable ComponentName admin, @NonNull String packageName, @NonNull String permission)11074     public @PermissionGrantState int getPermissionGrantState(@Nullable ComponentName admin,
11075             @NonNull String packageName, @NonNull String permission) {
11076         throwIfParentInstance("getPermissionGrantState");
11077         try {
11078             return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName,
11079                     permission);
11080         } catch (RemoteException re) {
11081             throw re.rethrowFromSystemServer();
11082         }
11083     }
11084 
11085     /**
11086      * Returns whether it is possible for the caller to initiate provisioning of a managed profile
11087      * or device, setting itself as the device or profile owner.
11088      *
11089      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
11090      * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
11091      * @return whether provisioning a managed profile or device is possible.
11092      * @throws IllegalArgumentException if the supplied action is not valid.
11093      */
isProvisioningAllowed(@onNull String action)11094     public boolean isProvisioningAllowed(@NonNull String action) {
11095         throwIfParentInstance("isProvisioningAllowed");
11096         try {
11097             return mService.isProvisioningAllowed(action, mContext.getPackageName());
11098         } catch (RemoteException re) {
11099             throw re.rethrowFromSystemServer();
11100         }
11101     }
11102 
11103     /**
11104      * Checks whether it is possible to initiate provisioning a managed device,
11105      * profile or user, setting the given package as owner.
11106      *
11107      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
11108      *        {@link #ACTION_PROVISION_MANAGED_PROFILE}
11109      * @param packageName The package of the component that would be set as device, user, or profile
11110      *        owner.
11111      * @return A {@link ProvisioningPreCondition} value indicating whether provisioning is allowed.
11112      * @hide
11113      */
11114     @TestApi
checkProvisioningPreCondition( @ullable String action, @NonNull String packageName)11115     public @ProvisioningPreCondition int checkProvisioningPreCondition(
11116             @Nullable String action, @NonNull String packageName) {
11117         try {
11118             return mService.checkProvisioningPreCondition(action, packageName);
11119         } catch (RemoteException re) {
11120             throw re.rethrowFromSystemServer();
11121         }
11122     }
11123 
11124     /**
11125      * Return if this user is a managed profile of another user. An admin can become the profile
11126      * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
11127      * user with {@link #createAndManageUser}
11128      * @param admin Which profile owner this request is associated with.
11129      * @return if this user is a managed profile of another user.
11130      */
isManagedProfile(@onNull ComponentName admin)11131     public boolean isManagedProfile(@NonNull ComponentName admin) {
11132         throwIfParentInstance("isManagedProfile");
11133         try {
11134             return mService.isManagedProfile(admin);
11135         } catch (RemoteException re) {
11136             throw re.rethrowFromSystemServer();
11137         }
11138     }
11139 
11140     /**
11141      * Called by device owner, or profile owner on organization-owned device, to get the MAC
11142      * address of the Wi-Fi device.
11143      *
11144      * NOTE: The MAC address returned here should only be used for inventory management and is
11145      * not likely to be the MAC address used by the device to connect to Wi-Fi networks: MAC
11146      * addresses used for scanning and connecting to Wi-Fi networks are randomized by default.
11147      * To get the randomized MAC address used, call
11148      * {@link android.net.wifi.WifiConfiguration#getRandomizedMacAddress}.
11149      *
11150      * @param admin Which device owner this request is associated with.
11151      * @return the MAC address of the Wi-Fi device, or null when the information is not available.
11152      *         (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
11153      *         <p>
11154      *         The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
11155      * @throws SecurityException if {@code admin} is not a device owner.
11156      */
getWifiMacAddress(@onNull ComponentName admin)11157     public @Nullable String getWifiMacAddress(@NonNull ComponentName admin) {
11158         throwIfParentInstance("getWifiMacAddress");
11159         try {
11160             return mService.getWifiMacAddress(admin);
11161         } catch (RemoteException re) {
11162             throw re.rethrowFromSystemServer();
11163         }
11164     }
11165 
11166     /**
11167      * Called by device owner to reboot the device. If there is an ongoing call on the device,
11168      * throws an {@link IllegalStateException}.
11169      * @param admin Which device owner the request is associated with.
11170      * @throws IllegalStateException if device has an ongoing call.
11171      * @throws SecurityException if {@code admin} is not a device owner.
11172      * @see TelephonyManager#CALL_STATE_IDLE
11173      */
reboot(@onNull ComponentName admin)11174     public void reboot(@NonNull ComponentName admin) {
11175         throwIfParentInstance("reboot");
11176         try {
11177             mService.reboot(admin);
11178         } catch (RemoteException re) {
11179             throw re.rethrowFromSystemServer();
11180         }
11181     }
11182 
11183     /**
11184      * Called by a device admin to set the short support message. This will be displayed to the user
11185      * in settings screens where funtionality has been disabled by the admin. The message should be
11186      * limited to a short statement such as "This setting is disabled by your administrator. Contact
11187      * someone@example.com for support." If the message is longer than 200 characters it may be
11188      * truncated.
11189      * <p>
11190      * If the short support message needs to be localized, it is the responsibility of the
11191      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
11192      * and set a new version of this string accordingly.
11193      *
11194      * @see #setLongSupportMessage
11195      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11196      * @param message Short message to be displayed to the user in settings or null to clear the
11197      *            existing message.
11198      * @throws SecurityException if {@code admin} is not an active administrator.
11199      */
setShortSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)11200     public void setShortSupportMessage(@NonNull ComponentName admin,
11201             @Nullable CharSequence message) {
11202         throwIfParentInstance("setShortSupportMessage");
11203         if (mService != null) {
11204             try {
11205                 mService.setShortSupportMessage(admin, message);
11206             } catch (RemoteException e) {
11207                 throw e.rethrowFromSystemServer();
11208             }
11209         }
11210     }
11211 
11212     /**
11213      * Called by a device admin to get the short support message.
11214      *
11215      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11216      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
11217      *         null if no message has been set.
11218      * @throws SecurityException if {@code admin} is not an active administrator.
11219      */
getShortSupportMessage(@onNull ComponentName admin)11220     public CharSequence getShortSupportMessage(@NonNull ComponentName admin) {
11221         throwIfParentInstance("getShortSupportMessage");
11222         if (mService != null) {
11223             try {
11224                 return mService.getShortSupportMessage(admin);
11225             } catch (RemoteException e) {
11226                 throw e.rethrowFromSystemServer();
11227             }
11228         }
11229         return null;
11230     }
11231 
11232     /**
11233      * Called by a device admin to set the long support message. This will be displayed to the user
11234      * in the device administators settings screen.
11235      * <p>
11236      * If the long support message needs to be localized, it is the responsibility of the
11237      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
11238      * and set a new version of this string accordingly.
11239      *
11240      * @see #setShortSupportMessage
11241      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11242      * @param message Long message to be displayed to the user in settings or null to clear the
11243      *            existing message.
11244      * @throws SecurityException if {@code admin} is not an active administrator.
11245      */
setLongSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)11246     public void setLongSupportMessage(@NonNull ComponentName admin,
11247             @Nullable CharSequence message) {
11248         throwIfParentInstance("setLongSupportMessage");
11249         if (mService != null) {
11250             try {
11251                 mService.setLongSupportMessage(admin, message);
11252             } catch (RemoteException e) {
11253                 throw e.rethrowFromSystemServer();
11254             }
11255         }
11256     }
11257 
11258     /**
11259      * Called by a device admin to get the long support message.
11260      *
11261      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11262      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
11263      *         null if no message has been set.
11264      * @throws SecurityException if {@code admin} is not an active administrator.
11265      */
getLongSupportMessage(@onNull ComponentName admin)11266     public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
11267         throwIfParentInstance("getLongSupportMessage");
11268         if (mService != null) {
11269             try {
11270                 return mService.getLongSupportMessage(admin);
11271             } catch (RemoteException e) {
11272                 throw e.rethrowFromSystemServer();
11273             }
11274         }
11275         return null;
11276     }
11277 
11278     /**
11279      * Called by the system to get the short support message.
11280      *
11281      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11282      * @param userHandle user id the admin is running as.
11283      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
11284      *
11285      * @hide
11286      */
getShortSupportMessageForUser(@onNull ComponentName admin, int userHandle)11287     public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
11288             int userHandle) {
11289         if (mService != null) {
11290             try {
11291                 return mService.getShortSupportMessageForUser(admin, userHandle);
11292             } catch (RemoteException e) {
11293                 throw e.rethrowFromSystemServer();
11294             }
11295         }
11296         return null;
11297     }
11298 
11299 
11300     /**
11301      * Called by the system to get the long support message.
11302      *
11303      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11304      * @param userHandle user id the admin is running as.
11305      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
11306      *
11307      * @hide
11308      */
getLongSupportMessageForUser( @onNull ComponentName admin, int userHandle)11309     public @Nullable CharSequence getLongSupportMessageForUser(
11310             @NonNull ComponentName admin, int userHandle) {
11311         if (mService != null) {
11312             try {
11313                 return mService.getLongSupportMessageForUser(admin, userHandle);
11314             } catch (RemoteException e) {
11315                 throw e.rethrowFromSystemServer();
11316             }
11317         }
11318         return null;
11319     }
11320 
11321     /**
11322      * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
11323      * whose calls act on the parent profile.
11324      *
11325      * <p>The following methods are supported for the parent instance, all other methods will
11326      * throw a SecurityException when called on the parent instance:
11327      * <ul>
11328      * <li>{@link #getPasswordQuality}</li>
11329      * <li>{@link #setPasswordQuality}</li>
11330      * <li>{@link #getPasswordMinimumLength}</li>
11331      * <li>{@link #setPasswordMinimumLength}</li>
11332      * <li>{@link #getPasswordMinimumUpperCase}</li>
11333      * <li>{@link #setPasswordMinimumUpperCase}</li>
11334      * <li>{@link #getPasswordMinimumLowerCase}</li>
11335      * <li>{@link #setPasswordMinimumLowerCase}</li>
11336      * <li>{@link #getPasswordMinimumLetters}</li>
11337      * <li>{@link #setPasswordMinimumLetters}</li>
11338      * <li>{@link #getPasswordMinimumNumeric}</li>
11339      * <li>{@link #setPasswordMinimumNumeric}</li>
11340      * <li>{@link #getPasswordMinimumSymbols}</li>
11341      * <li>{@link #setPasswordMinimumSymbols}</li>
11342      * <li>{@link #getPasswordMinimumNonLetter}</li>
11343      * <li>{@link #setPasswordMinimumNonLetter}</li>
11344      * <li>{@link #getPasswordHistoryLength}</li>
11345      * <li>{@link #setPasswordHistoryLength}</li>
11346      * <li>{@link #getPasswordExpirationTimeout}</li>
11347      * <li>{@link #setPasswordExpirationTimeout}</li>
11348      * <li>{@link #getPasswordExpiration}</li>
11349      * <li>{@link #getPasswordMaximumLength}</li>
11350      * <li>{@link #isActivePasswordSufficient}</li>
11351      * <li>{@link #getCurrentFailedPasswordAttempts}</li>
11352      * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
11353      * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
11354      * <li>{@link #getMaximumTimeToLock}</li>
11355      * <li>{@link #setMaximumTimeToLock}</li>
11356      * <li>{@link #lockNow}</li>
11357      * <li>{@link #getKeyguardDisabledFeatures}</li>
11358      * <li>{@link #setKeyguardDisabledFeatures}</li>
11359      * <li>{@link #getTrustAgentConfiguration}</li>
11360      * <li>{@link #setTrustAgentConfiguration}</li>
11361      * <li>{@link #getRequiredStrongAuthTimeout}</li>
11362      * <li>{@link #setRequiredStrongAuthTimeout}</li>
11363      * <li>{@link #getAccountTypesWithManagementDisabled}</li>
11364      * <li>{@link #setRequiredPasswordComplexity(int)} </li>
11365      * <li>{@link #getRequiredPasswordComplexity()}</li>
11366      * </ul>
11367      * <p>
11368      * The following methods are supported for the parent instance but can only be called by the
11369      * profile owner of a managed profile that was created during the device provisioning flow:
11370      * <ul>
11371      * <li>{@link #getPasswordComplexity}</li>
11372      * <li>{@link #setCameraDisabled}</li>
11373      * <li>{@link #getCameraDisabled}</li>
11374      * <li>{@link #setAccountManagementDisabled(ComponentName, String, boolean)}</li>
11375      * <li>{@link #setPermittedInputMethods}</li>
11376      * <li>{@link #getPermittedInputMethods}</li>
11377      * </ul>
11378      *
11379      * <p>The following methods can be called by the profile owner of a managed profile
11380      * on an organization-owned device:
11381      * <ul>
11382      * <li>{@link #wipeData}</li>
11383      * </ul>
11384      *
11385      * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
11386      * @throws SecurityException if {@code admin} is not a profile owner.
11387      */
getParentProfileInstance(@onNull ComponentName admin)11388     public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
11389         throwIfParentInstance("getParentProfileInstance");
11390         try {
11391             if (!mService.isManagedProfile(admin)) {
11392                 throw new SecurityException("The current user does not have a parent profile.");
11393             }
11394             return new DevicePolicyManager(mContext, mService, true);
11395         } catch (RemoteException e) {
11396             throw e.rethrowFromSystemServer();
11397         }
11398     }
11399 
11400     /**
11401      * Called by device owner or a profile owner of an organization-owned managed profile to
11402      * control the security logging feature.
11403      *
11404      * <p> Security logs contain various information intended for security auditing purposes.
11405      * When security logging is enabled by a profile owner of
11406      * an organization-owned managed profile, certain security logs are not visible (for example
11407      * personal app launch events) or they will be redacted (for example, details of the physical
11408      * volume mount events). Please see {@link SecurityEvent} for details.
11409      *
11410      * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there
11411      * are unaffiliated secondary users or profiles on the device, regardless of whether the
11412      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
11413      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
11414      * new users as soon as possible after provisioning via {@link #setAffiliationIds}. Profile
11415      * owner of organization-owned managed profile is not subject to this restriction since all
11416      * privacy-sensitive events happening outside the managed profile would have been redacted
11417      * already.
11418      *
11419      * @param admin Which device admin this request is associated with.
11420      * @param enabled whether security logging should be enabled or not.
11421      * @throws SecurityException if {@code admin} is not allowed to control security logging.
11422      * @see #setAffiliationIds
11423      * @see #retrieveSecurityLogs
11424      */
setSecurityLoggingEnabled(@onNull ComponentName admin, boolean enabled)11425     public void setSecurityLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
11426         throwIfParentInstance("setSecurityLoggingEnabled");
11427         try {
11428             mService.setSecurityLoggingEnabled(admin, mContext.getPackageName(), enabled);
11429         } catch (RemoteException re) {
11430             throw re.rethrowFromSystemServer();
11431         }
11432     }
11433 
11434     /**
11435      * Return whether security logging is enabled or not by the admin.
11436      *
11437      * <p>Can only be called by the device owner or a profile owner of an organization-owned
11438      * managed profile, otherwise a {@link SecurityException} will be thrown.
11439      *
11440      * @param admin Which device admin this request is associated with.
11441      * @return {@code true} if security logging is enabled by device owner, {@code false} otherwise.
11442      * @throws SecurityException if {@code admin} is not allowed to control security logging.
11443      */
isSecurityLoggingEnabled(@ullable ComponentName admin)11444     public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) {
11445         throwIfParentInstance("isSecurityLoggingEnabled");
11446         try {
11447             return mService.isSecurityLoggingEnabled(admin, mContext.getPackageName());
11448         } catch (RemoteException re) {
11449             throw re.rethrowFromSystemServer();
11450         }
11451     }
11452 
11453     /**
11454      * Called by device owner or profile owner of an organization-owned managed profile to retrieve
11455      * all new security logging entries since the last call to this API after device boots.
11456      *
11457      * <p> Access to the logs is rate limited and it will only return new logs after the device
11458      * owner has been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
11459      *
11460      * <p> When called by a device owner, if there is any other user or profile on the device,
11461      * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown.
11462      * See {@link #isAffiliatedUser}.
11463      *
11464      * @param admin Which device admin this request is associated with.
11465      * @return the new batch of security logs which is a list of {@link SecurityEvent},
11466      * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
11467      * @throws SecurityException if {@code admin} is not allowed to access security logging,
11468      * or there is at least one profile or secondary user that is not affiliated with the device.
11469      * @see #isAffiliatedUser
11470      * @see DeviceAdminReceiver#onSecurityLogsAvailable
11471      */
11472     @SuppressLint("NullableCollection")
retrieveSecurityLogs(@onNull ComponentName admin)11473     public @Nullable List<SecurityEvent> retrieveSecurityLogs(@NonNull ComponentName admin) {
11474         throwIfParentInstance("retrieveSecurityLogs");
11475         try {
11476             ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(
11477                     admin, mContext.getPackageName());
11478             if (list != null) {
11479                 return list.getList();
11480             } else {
11481                 // Rate limit exceeded.
11482                 return null;
11483             }
11484         } catch (RemoteException re) {
11485             throw re.rethrowFromSystemServer();
11486         }
11487     }
11488 
11489     /**
11490      * Makes all accumulated network logs available to DPC in a new batch.
11491      * If throttled, returns time to wait in milliseconds, otherwise 0.
11492      * @hide
11493      */
11494     @TestApi
11495     @RequiresPermission(android.Manifest.permission.FORCE_DEVICE_POLICY_MANAGER_LOGS)
forceNetworkLogs()11496     public long forceNetworkLogs() {
11497         if (mService == null) {
11498             return -1;
11499         }
11500         try {
11501             return mService.forceNetworkLogs();
11502         } catch (RemoteException re) {
11503             throw re.rethrowFromSystemServer();
11504         }
11505     }
11506 
11507     /**
11508      * Forces a batch of security logs to be fetched from logd and makes it available for DPC.
11509      * If throttled, returns time to wait in milliseconds, otherwise 0.
11510      * @hide
11511      */
11512     @TestApi
11513     @RequiresPermission(android.Manifest.permission.FORCE_DEVICE_POLICY_MANAGER_LOGS)
forceSecurityLogs()11514     public long forceSecurityLogs() {
11515         if (mService == null) {
11516             return 0;
11517         }
11518         try {
11519             return mService.forceSecurityLogs();
11520         } catch (RemoteException re) {
11521             throw re.rethrowFromSystemServer();
11522         }
11523     }
11524 
11525     /**
11526      * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
11527      * profile.
11528      *
11529      * @hide
11530      */
getParentProfileInstance(UserInfo uInfo)11531     public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
11532         mContext.checkSelfPermission(
11533                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
11534         if (!uInfo.isManagedProfile()) {
11535             throw new SecurityException("The user " + uInfo.id
11536                     + " does not have a parent profile.");
11537         }
11538         return new DevicePolicyManager(mContext, mService, true);
11539     }
11540 
11541     /**
11542      * Called by a device or profile owner to restrict packages from using metered data.
11543      *
11544      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11545      * @param packageNames the list of package names to be restricted.
11546      * @return a list of package names which could not be restricted.
11547      * @throws SecurityException if {@code admin} is not a device or profile owner.
11548      */
setMeteredDataDisabledPackages(@onNull ComponentName admin, @NonNull List<String> packageNames)11549     public @NonNull List<String> setMeteredDataDisabledPackages(@NonNull ComponentName admin,
11550             @NonNull List<String> packageNames) {
11551         throwIfParentInstance("setMeteredDataDisabled");
11552         if (mService != null) {
11553             try {
11554                 return mService.setMeteredDataDisabledPackages(admin, packageNames);
11555             } catch (RemoteException re) {
11556                 throw re.rethrowFromSystemServer();
11557             }
11558         }
11559         return packageNames;
11560     }
11561 
11562     /**
11563      * Called by a device or profile owner to retrieve the list of packages which are restricted
11564      * by the admin from using metered data.
11565      *
11566      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11567      * @return the list of restricted package names.
11568      * @throws SecurityException if {@code admin} is not a device or profile owner.
11569      */
getMeteredDataDisabledPackages(@onNull ComponentName admin)11570     public @NonNull List<String> getMeteredDataDisabledPackages(@NonNull ComponentName admin) {
11571         throwIfParentInstance("getMeteredDataDisabled");
11572         if (mService != null) {
11573             try {
11574                 return mService.getMeteredDataDisabledPackages(admin);
11575             } catch (RemoteException re) {
11576                 throw re.rethrowFromSystemServer();
11577             }
11578         }
11579         return new ArrayList<>();
11580     }
11581 
11582     /**
11583      * Called by the system to check if a package is restricted from using metered data
11584      * by {@param admin}.
11585      *
11586      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11587      * @param packageName the package whose restricted status is needed.
11588      * @param userId the user to which {@param packageName} belongs.
11589      * @return {@code true} if the package is restricted by admin, otherwise {@code false}
11590      * @throws SecurityException if the caller doesn't run with {@link Process#SYSTEM_UID}
11591      * @hide
11592      */
isMeteredDataDisabledPackageForUser(@onNull ComponentName admin, String packageName, @UserIdInt int userId)11593     public boolean isMeteredDataDisabledPackageForUser(@NonNull ComponentName admin,
11594             String packageName, @UserIdInt int userId) {
11595         throwIfParentInstance("getMeteredDataDisabledForUser");
11596         if (mService != null) {
11597             try {
11598                 return mService.isMeteredDataDisabledPackageForUser(admin, packageName, userId);
11599             } catch (RemoteException re) {
11600                 throw re.rethrowFromSystemServer();
11601             }
11602         }
11603         return false;
11604     }
11605 
11606     /**
11607      * Called by device owner or profile owner of an organization-owned managed profile to retrieve
11608      * device logs from before the device's last reboot.
11609      * <p>
11610      * <strong> This API is not supported on all devices. Calling this API on unsupported devices
11611      * will result in {@code null} being returned. The device logs are retrieved from a RAM region
11612      * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
11613      * about data corruption when parsing. </strong>
11614      *
11615      * <p> When called by a device owner, if there is any other user or profile on the device,
11616      * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown.
11617      * See {@link #isAffiliatedUser}.
11618      *
11619      * @param admin Which device admin this request is associated with.
11620      * @return Device logs from before the latest reboot of the system, or {@code null} if this API
11621      *         is not supported on the device.
11622      * @throws SecurityException if {@code admin} is not allowed to access security logging, or
11623      * there is at least one profile or secondary user that is not affiliated with the device.
11624      * @see #isAffiliatedUser
11625      * @see #retrieveSecurityLogs
11626      */
11627     @SuppressLint("NullableCollection")
retrievePreRebootSecurityLogs( @onNull ComponentName admin)11628     public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
11629             @NonNull ComponentName admin) {
11630         throwIfParentInstance("retrievePreRebootSecurityLogs");
11631         try {
11632             ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(
11633                     admin, mContext.getPackageName());
11634             if (list != null) {
11635                 return list.getList();
11636             } else {
11637                 return null;
11638             }
11639         } catch (RemoteException re) {
11640             throw re.rethrowFromSystemServer();
11641         }
11642     }
11643 
11644     /**
11645      * Called by a profile owner of a managed profile to set the color used for customization. This
11646      * color is used as background color of the confirm credentials screen for that user. The
11647      * default color is teal (#00796B).
11648      * <p>
11649      * The confirm credentials screen can be created using
11650      * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
11651      * <p>
11652      * Starting from Android R, the organization color will no longer be used as the background
11653      * color of the confirm credentials screen.
11654      *
11655      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11656      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
11657      * @throws SecurityException if {@code admin} is not a profile owner.
11658      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
11659      * used as the background color of the confirm credentials screen.
11660      */
11661     @Deprecated
setOrganizationColor(@onNull ComponentName admin, int color)11662     public void setOrganizationColor(@NonNull ComponentName admin, int color) {
11663         throwIfParentInstance("setOrganizationColor");
11664         try {
11665             // always enforce alpha channel to have 100% opacity
11666             color |= 0xFF000000;
11667             mService.setOrganizationColor(admin, color);
11668         } catch (RemoteException re) {
11669             throw re.rethrowFromSystemServer();
11670         }
11671     }
11672 
11673     /**
11674      * @hide
11675      *
11676      * Sets the color used for customization.
11677      *
11678      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
11679      * @param userId which user to set the color to.
11680      * @RequiresPermission(allOf = {
11681      *       Manifest.permission.MANAGE_USERS,
11682      *       Manifest.permission.INTERACT_ACROSS_USERS_FULL})
11683      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
11684      * used as the background color of the confirm credentials screen.
11685      */
11686     @Deprecated
setOrganizationColorForUser(@olorInt int color, @UserIdInt int userId)11687     public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
11688         try {
11689             // always enforce alpha channel to have 100% opacity
11690             color |= 0xFF000000;
11691             mService.setOrganizationColorForUser(color, userId);
11692         } catch (RemoteException re) {
11693             throw re.rethrowFromSystemServer();
11694         }
11695     }
11696 
11697     /**
11698      * Called by a profile owner of a managed profile to retrieve the color used for customization.
11699      * This color is used as background color of the confirm credentials screen for that user.
11700      *
11701      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11702      * @return The 24bit (0xRRGGBB) representation of the color to be used.
11703      * @throws SecurityException if {@code admin} is not a profile owner.
11704      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
11705      * used as the background color of the confirm credentials screen.
11706      */
11707     @Deprecated
getOrganizationColor(@onNull ComponentName admin)11708     public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
11709         throwIfParentInstance("getOrganizationColor");
11710         try {
11711             return mService.getOrganizationColor(admin);
11712         } catch (RemoteException re) {
11713             throw re.rethrowFromSystemServer();
11714         }
11715     }
11716 
11717     /**
11718      * @hide
11719      * Retrieve the customization color for a given user.
11720      *
11721      * @param userHandle The user id of the user we're interested in.
11722      * @return The 24bit (0xRRGGBB) representation of the color to be used.
11723      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
11724      * used as the background color of the confirm credentials screen.
11725      */
11726     @Deprecated
getOrganizationColorForUser(int userHandle)11727     public @ColorInt int getOrganizationColorForUser(int userHandle) {
11728         try {
11729             return mService.getOrganizationColorForUser(userHandle);
11730         } catch (RemoteException re) {
11731             throw re.rethrowFromSystemServer();
11732         }
11733     }
11734 
11735     /**
11736      * Called by the device owner (since API 26) or profile owner (since API 24) to set the name of
11737      * the organization under management.
11738      *
11739      * <p>If the organization name needs to be localized, it is the responsibility of the {@link
11740      * DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast and set
11741      * a new version of this string accordingly.
11742      *
11743      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11744      * @param title The organization name or {@code null} to clear a previously set name.
11745      * @throws SecurityException if {@code admin} is not a device or profile owner.
11746      */
setOrganizationName(@onNull ComponentName admin, @Nullable CharSequence title)11747     public void setOrganizationName(@NonNull ComponentName admin, @Nullable CharSequence title) {
11748         throwIfParentInstance("setOrganizationName");
11749         try {
11750             mService.setOrganizationName(admin, title);
11751         } catch (RemoteException re) {
11752             throw re.rethrowFromSystemServer();
11753         }
11754     }
11755 
11756     /**
11757      * Called by a profile owner of a managed profile to retrieve the name of the organization under
11758      * management.
11759      *
11760      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11761      * @return The organization name or {@code null} if none is set.
11762      * @throws SecurityException if {@code admin} is not a profile owner.
11763      */
getOrganizationName(@onNull ComponentName admin)11764     public @Nullable CharSequence getOrganizationName(@NonNull ComponentName admin) {
11765         throwIfParentInstance("getOrganizationName");
11766         try {
11767             return mService.getOrganizationName(admin);
11768         } catch (RemoteException re) {
11769             throw re.rethrowFromSystemServer();
11770         }
11771     }
11772 
11773     /**
11774      * Called by the system to retrieve the name of the organization managing the device.
11775      *
11776      * @return The organization name or {@code null} if none is set.
11777      * @throws SecurityException if the caller is not the device owner, does not hold the
11778      *         MANAGE_USERS permission and is not the system.
11779      *
11780      * @hide
11781      */
11782     @SystemApi
11783     @SuppressLint("RequiresPermission")
getDeviceOwnerOrganizationName()11784     public @Nullable CharSequence getDeviceOwnerOrganizationName() {
11785         try {
11786             return mService.getDeviceOwnerOrganizationName();
11787         } catch (RemoteException re) {
11788             throw re.rethrowFromSystemServer();
11789         }
11790     }
11791 
11792     /**
11793      * Retrieve the default title message used in the confirm credentials screen for a given user.
11794      *
11795      * @param userHandle The user id of the user we're interested in.
11796      * @return The organization name or {@code null} if none is set.
11797      *
11798      * @hide
11799      */
getOrganizationNameForUser(int userHandle)11800     public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
11801         try {
11802             return mService.getOrganizationNameForUser(userHandle);
11803         } catch (RemoteException re) {
11804             throw re.rethrowFromSystemServer();
11805         }
11806     }
11807 
11808     /**
11809      * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
11810      *         return {@link #STATE_USER_UNMANAGED}
11811      * @hide
11812      */
11813     @SystemApi
11814     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
11815     @UserProvisioningState
getUserProvisioningState()11816     public int getUserProvisioningState() {
11817         throwIfParentInstance("getUserProvisioningState");
11818         if (mService != null) {
11819             try {
11820                 return mService.getUserProvisioningState();
11821             } catch (RemoteException e) {
11822                 throw e.rethrowFromSystemServer();
11823             }
11824         }
11825         return STATE_USER_UNMANAGED;
11826     }
11827 
11828     /**
11829      * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
11830      *
11831      * @param state to store
11832      * @param userHandle for user
11833      * @hide
11834      */
setUserProvisioningState(@serProvisioningState int state, int userHandle)11835     public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
11836         if (mService != null) {
11837             try {
11838                 mService.setUserProvisioningState(state, userHandle);
11839             } catch (RemoteException e) {
11840                 throw e.rethrowFromSystemServer();
11841             }
11842         }
11843     }
11844 
11845     /**
11846      * Indicates the entity that controls the device. Two users are
11847      * affiliated if the set of ids set by the device owner and the admin of the secondary user.
11848      *
11849      * <p>A user that is affiliated with the device owner user is considered to be
11850      * affiliated with the device.
11851      *
11852      * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
11853      * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user
11854      * is created, until it becomes affiliated. Therefore it is recommended that the appropriate
11855      * affiliation ids are set by its owner as soon as possible after the user is
11856      * created.
11857      * <p>
11858      * Note: This method used to be available for affiliating device owner and profile
11859      * owner. However, since Android 11, this combination is not possible. This method is now
11860      * only useful for affiliating the primary user with managed secondary users.
11861      *
11862      * @param admin Which device owner, or owner of secondary user, this request is associated with.
11863      * @param ids A set of opaque non-empty affiliation ids.
11864      *
11865      * @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
11866      * @see #isAffiliatedUser
11867      */
setAffiliationIds(@onNull ComponentName admin, @NonNull Set<String> ids)11868     public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) {
11869         throwIfParentInstance("setAffiliationIds");
11870         if (ids == null) {
11871             throw new IllegalArgumentException("ids must not be null");
11872         }
11873         try {
11874             mService.setAffiliationIds(admin, new ArrayList<>(ids));
11875         } catch (RemoteException e) {
11876             throw e.rethrowFromSystemServer();
11877         }
11878     }
11879 
11880     /**
11881      * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
11882      * empty set if none have been set.
11883      */
getAffiliationIds(@onNull ComponentName admin)11884     public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
11885         throwIfParentInstance("getAffiliationIds");
11886         try {
11887             return new ArraySet<>(mService.getAffiliationIds(admin));
11888         } catch (RemoteException e) {
11889             throw e.rethrowFromSystemServer();
11890         }
11891     }
11892 
11893     /**
11894      * Returns whether this user is affiliated with the device.
11895      * <p>
11896      * By definition, the user that the device owner runs on is always affiliated with the device.
11897      * Any other user is considered affiliated with the device if the set specified by its
11898      * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
11899      * @see #setAffiliationIds
11900      */
isAffiliatedUser()11901     public boolean isAffiliatedUser() {
11902         throwIfParentInstance("isAffiliatedUser");
11903         try {
11904             return mService.isCallingUserAffiliated();
11905         } catch (RemoteException e) {
11906             throw e.rethrowFromSystemServer();
11907         }
11908     }
11909 
11910     /**
11911      * @hide
11912      * Returns whether target user is affiliated with the device.
11913      */
isAffiliatedUser(@serIdInt int userId)11914     public boolean isAffiliatedUser(@UserIdInt int userId) {
11915         try {
11916             return mService.isAffiliatedUser(userId);
11917         } catch (RemoteException e) {
11918             throw e.rethrowFromSystemServer();
11919         }
11920     }
11921 
11922     /**
11923      * @hide
11924      * Returns whether the uninstall for {@code packageName} for the current user is in queue
11925      * to be started
11926      * @param packageName the package to check for
11927      * @return whether the uninstall intent for {@code packageName} is pending
11928      */
isUninstallInQueue(String packageName)11929     public boolean isUninstallInQueue(String packageName) {
11930         try {
11931             return mService.isUninstallInQueue(packageName);
11932         } catch (RemoteException re) {
11933             throw re.rethrowFromSystemServer();
11934         }
11935     }
11936 
11937     /**
11938      * @hide
11939      * @param packageName the package containing active DAs to be uninstalled
11940      */
uninstallPackageWithActiveAdmins(String packageName)11941     public void uninstallPackageWithActiveAdmins(String packageName) {
11942         try {
11943             mService.uninstallPackageWithActiveAdmins(packageName);
11944         } catch (RemoteException re) {
11945             throw re.rethrowFromSystemServer();
11946         }
11947     }
11948 
11949     /**
11950      * @hide
11951      * Remove a test admin synchronously without sending it a broadcast about being removed.
11952      * If the admin is a profile owner or device owner it will still be removed.
11953      *
11954      * @param userHandle user id to remove the admin for.
11955      * @param admin The administration compononent to remove.
11956      * @throws SecurityException if the caller is not shell / root or the admin package
11957      *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
11958      */
11959     @TestApi
11960     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
forceRemoveActiveAdmin( @onNull ComponentName adminReceiver, @UserIdInt int userHandle)11961     public void forceRemoveActiveAdmin(
11962             @NonNull ComponentName adminReceiver, @UserIdInt int userHandle) {
11963         try {
11964             mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
11965         } catch (RemoteException re) {
11966             throw re.rethrowFromSystemServer();
11967         }
11968     }
11969 
11970     /**
11971      * Returns whether the device has been provisioned.
11972      *
11973      * <p>Not for use by third-party applications.
11974      *
11975      * @hide
11976      */
11977     @SystemApi
11978     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioned()11979     public boolean isDeviceProvisioned() {
11980         try {
11981             return mService.isDeviceProvisioned();
11982         } catch (RemoteException re) {
11983             throw re.rethrowFromSystemServer();
11984         }
11985     }
11986 
11987     /**
11988       * Writes that the provisioning configuration has been applied.
11989       *
11990       * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
11991       * permission.
11992       *
11993       * <p>Not for use by third-party applications.
11994       *
11995       * @hide
11996       */
11997     @SystemApi
11998     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
setDeviceProvisioningConfigApplied()11999     public void setDeviceProvisioningConfigApplied() {
12000         try {
12001             mService.setDeviceProvisioningConfigApplied();
12002         } catch (RemoteException re) {
12003             throw re.rethrowFromSystemServer();
12004         }
12005     }
12006 
12007     /**
12008      * Returns whether the provisioning configuration has been applied.
12009      *
12010      * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
12011      *
12012      * <p>Not for use by third-party applications.
12013      *
12014      * @return whether the provisioning configuration has been applied.
12015      *
12016      * @hide
12017      */
12018     @SystemApi
12019     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioningConfigApplied()12020     public boolean isDeviceProvisioningConfigApplied() {
12021         try {
12022             return mService.isDeviceProvisioningConfigApplied();
12023         } catch (RemoteException re) {
12024             throw re.rethrowFromSystemServer();
12025         }
12026     }
12027 
12028     /**
12029      * @hide
12030      * Force update user setup completed status for the given {@code userId}.
12031      * @throws {@link SecurityException} if the caller has no
12032      *         {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS}.
12033      */
12034     @TestApi
forceUpdateUserSetupComplete(@serIdInt int userId)12035     public void forceUpdateUserSetupComplete(@UserIdInt int userId) {
12036         try {
12037             mService.forceUpdateUserSetupComplete(userId);
12038         } catch (RemoteException re) {
12039             throw re.rethrowFromSystemServer();
12040         }
12041     }
12042 
12043     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
throwIfParentInstance(String functionName)12044     private void throwIfParentInstance(String functionName) {
12045         if (mParentInstance) {
12046             throw new SecurityException(functionName + " cannot be called on the parent instance");
12047         }
12048     }
12049 
12050     /**
12051      * Allows the device owner or profile owner to enable or disable the backup service.
12052      *
12053      * <p> Each user has its own backup service which manages the backup and restore mechanisms in
12054      * that user. Disabling the backup service will prevent data from being backed up or restored.
12055      *
12056      * <p> Device owner calls this API to control backup services across all users on the device.
12057      * Profile owner can use this API to enable or disable the profile's backup service. However,
12058      * for a managed profile its backup functionality is only enabled if both the device owner
12059      * and the profile owner have enabled the backup service.
12060      *
12061      * <p> By default, backup service is disabled on a device with device owner, and within a
12062      * managed profile.
12063      *
12064      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12065      * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
12066      * @throws SecurityException if {@code admin} is not a device owner or a profile owner.
12067      */
setBackupServiceEnabled(@onNull ComponentName admin, boolean enabled)12068     public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
12069         throwIfParentInstance("setBackupServiceEnabled");
12070         try {
12071             mService.setBackupServiceEnabled(admin, enabled);
12072         } catch (RemoteException re) {
12073             throw re.rethrowFromSystemServer();
12074         }
12075     }
12076 
12077     /**
12078      * Return whether the backup service is enabled by the device owner or profile owner for the
12079      * current user, as previously set by {@link #setBackupServiceEnabled(ComponentName, boolean)}.
12080      *
12081      * <p> Whether the backup functionality is actually enabled or not depends on settings from both
12082      * the current user and the device owner, please see
12083      * {@link #setBackupServiceEnabled(ComponentName, boolean)} for details.
12084      *
12085      * <p> Backup service manages all backup and restore mechanisms on the device.
12086      *
12087      * @return {@code true} if backup service is enabled, {@code false} otherwise.
12088      * @see #setBackupServiceEnabled
12089      */
isBackupServiceEnabled(@onNull ComponentName admin)12090     public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
12091         throwIfParentInstance("isBackupServiceEnabled");
12092         try {
12093             return mService.isBackupServiceEnabled(admin);
12094         } catch (RemoteException re) {
12095             throw re.rethrowFromSystemServer();
12096         }
12097     }
12098 
12099     /**
12100      * Called by a device owner, profile owner of a managed profile or delegated app with
12101      * {@link #DELEGATION_NETWORK_LOGGING} to control the network logging feature.
12102      *
12103      * <p> When network logging is enabled by a profile owner, the network logs will only include
12104      * work profile network activity, not activity on the personal profile.
12105      *
12106      * <p> Network logs contain DNS lookup and connect() library call events. The following library
12107      *     functions are recorded while network logging is active:
12108      *     <ul>
12109      *       <li>{@code getaddrinfo()}</li>
12110      *       <li>{@code gethostbyname()}</li>
12111      *       <li>{@code connect()}</li>
12112      *     </ul>
12113      *
12114      * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
12115      *     full system call logging; event reporting is enabled by default for all processes but not
12116      *     strongly enforced.
12117      *     Events from applications using alternative implementations of libc, making direct kernel
12118      *     calls, or deliberately obfuscating traffic may not be recorded.
12119      *
12120      * <p> Some common network events may not be reported. For example:
12121      *     <ul>
12122      *       <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
12123      *           an alternative system for name resolution, and so avoid calling
12124      *           {@code getaddrinfo()} or {@code gethostbyname}.</li>
12125      *       <li>Applications may use datagram sockets for performance reasons, for example
12126      *           for a game client. Calling {@code connect()} is unnecessary for this kind of
12127      *           socket, so it will not trigger a network event.</li>
12128      *     </ul>
12129      *
12130      * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
12131      *     always-on VPN service.
12132      *     See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
12133      *     and {@link android.net.VpnService} for details.
12134      *
12135      * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
12136      * are unaffiliated secondary users or profiles on the device, regardless of whether the
12137      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
12138      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
12139      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
12140      *
12141      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
12142      *        {@code null} if called by a delegated app.
12143      * @param enabled whether network logging should be enabled or not.
12144      * @throws SecurityException if {@code admin} is not a device owner or profile owner.
12145      * @see #setAffiliationIds
12146      * @see #retrieveNetworkLogs
12147      */
setNetworkLoggingEnabled(@ullable ComponentName admin, boolean enabled)12148     public void setNetworkLoggingEnabled(@Nullable ComponentName admin, boolean enabled) {
12149         throwIfParentInstance("setNetworkLoggingEnabled");
12150         try {
12151             mService.setNetworkLoggingEnabled(admin, mContext.getPackageName(), enabled);
12152         } catch (RemoteException re) {
12153             throw re.rethrowFromSystemServer();
12154         }
12155     }
12156 
12157     /**
12158      * Return whether network logging is enabled by a device owner or profile owner of
12159      * a managed profile.
12160      *
12161      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
12162      * be {@code null} if the caller is a delegated app with {@link #DELEGATION_NETWORK_LOGGING}
12163      * or has MANAGE_USERS permission.
12164      * @return {@code true} if network logging is enabled by device owner or profile owner,
12165      * {@code false} otherwise.
12166      * @throws SecurityException if {@code admin} is not a device owner or profile owner and
12167      * caller has no MANAGE_USERS permission
12168      */
isNetworkLoggingEnabled(@ullable ComponentName admin)12169     public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
12170         throwIfParentInstance("isNetworkLoggingEnabled");
12171         try {
12172             return mService.isNetworkLoggingEnabled(admin, mContext.getPackageName());
12173         } catch (RemoteException re) {
12174             throw re.rethrowFromSystemServer();
12175         }
12176     }
12177 
12178     /**
12179      * Called by device owner, profile owner of a managed profile or delegated app with
12180      * {@link #DELEGATION_NETWORK_LOGGING} to retrieve the most recent batch of
12181      * network logging events.
12182      *
12183      * <p> When network logging is enabled by a profile owner, the network logs will only include
12184      * work profile network activity, not activity on the personal profile.
12185      *
12186      * A device owner or profile owner has to provide a batchToken provided as part of
12187      * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
12188      * token of the most recent available batch of logs, {@code null} will be returned.
12189      *
12190      * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
12191      *
12192      * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
12193      *
12194      * <p> Access to the logs is rate limited and this method will only return a new batch of logs
12195      * after the device device owner has been notified via
12196      * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
12197      *
12198      * <p>If the caller is not a profile owner and a secondary user or profile is created, calling
12199      * this method will throw a {@link SecurityException} until all users become affiliated again.
12200      * It will also no longer be possible to retrieve the network logs batch with the most recent
12201      * batchToken provided by {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
12202      * See {@link DevicePolicyManager#setAffiliationIds}.
12203      *
12204      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
12205      *        {@code null} if called by a delegated app.
12206      * @param batchToken A token of the batch to retrieve
12207      * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
12208      *        {@code null} if the batch represented by batchToken is no longer available or if
12209      *        logging is disabled.
12210      * @throws SecurityException if {@code admin} is not a device owner, profile owner or if the
12211      * {@code admin} is not a profile owner and there is at least one profile or secondary user
12212      * that is not affiliated with the device.
12213      * @see #setAffiliationIds
12214      * @see DeviceAdminReceiver#onNetworkLogsAvailable
12215      */
retrieveNetworkLogs(@ullable ComponentName admin, long batchToken)12216     public @Nullable List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin,
12217             long batchToken) {
12218         throwIfParentInstance("retrieveNetworkLogs");
12219         try {
12220             return mService.retrieveNetworkLogs(admin, mContext.getPackageName(), batchToken);
12221         } catch (RemoteException re) {
12222             throw re.rethrowFromSystemServer();
12223         }
12224     }
12225 
12226     /**
12227      * Called by a device owner to bind to a service from a secondary managed user or vice versa.
12228      * See {@link #getBindDeviceAdminTargetUsers} for the pre-requirements of a
12229      * device owner to bind to services of another managed user.
12230      * <p>
12231      * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
12232      * Note that the {@link Context} used to obtain this
12233      * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
12234      * to bind to the {@link android.app.Service}.
12235      * <p>
12236      * Note: This method used to be available for communication between device owner and profile
12237      * owner. However, since Android 11, this combination is not possible. This method is now
12238      * only useful for communication between device owner and managed secondary users.
12239      *
12240      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12241      * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
12242      *        explicit component name or a package name to match an
12243      *        {@link IntentFilter} published by a service.
12244      * @param conn Receives information as the service is started and stopped in main thread. This
12245      *        must be a valid {@link ServiceConnection} object; it must not be {@code null}.
12246      * @param flags Operation options for the binding operation. See
12247      *        {@link Context#bindService(Intent, ServiceConnection, int)}.
12248      * @param targetUser Which user to bind to. Must be one of the users returned by
12249      *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
12250      *        be thrown.
12251      * @return If you have successfully bound to the service, {@code true} is returned;
12252      *         {@code false} is returned if the connection is not made and you will not
12253      *         receive the service object.
12254      *
12255      * @see Context#bindService(Intent, ServiceConnection, int)
12256      * @see #getBindDeviceAdminTargetUsers(ComponentName)
12257      */
bindDeviceAdminServiceAsUser( @onNull ComponentName admin, Intent serviceIntent, @NonNull ServiceConnection conn, @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser)12258     public boolean bindDeviceAdminServiceAsUser(
12259             @NonNull ComponentName admin,  Intent serviceIntent, @NonNull ServiceConnection conn,
12260             @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser) {
12261         throwIfParentInstance("bindDeviceAdminServiceAsUser");
12262         // Keep this in sync with ContextImpl.bindServiceCommon.
12263         try {
12264             final IServiceConnection sd = mContext.getServiceDispatcher(
12265                     conn, mContext.getMainThreadHandler(), flags);
12266             serviceIntent.prepareToLeaveProcess(mContext);
12267             return mService.bindDeviceAdminServiceAsUser(admin,
12268                     mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
12269                     sd, flags, targetUser.getIdentifier());
12270         } catch (RemoteException re) {
12271             throw re.rethrowFromSystemServer();
12272         }
12273     }
12274 
12275     /**
12276      * Returns the list of target users that the calling device owner or owner of secondary user
12277      * can use when calling {@link #bindDeviceAdminServiceAsUser}.
12278      * <p>
12279      * A device owner can bind to a service from a secondary managed user and vice versa, provided
12280      * that both users are affiliated. See {@link #setAffiliationIds}.
12281      */
getBindDeviceAdminTargetUsers(@onNull ComponentName admin)12282     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
12283         throwIfParentInstance("getBindDeviceAdminTargetUsers");
12284         try {
12285             return mService.getBindDeviceAdminTargetUsers(admin);
12286         } catch (RemoteException re) {
12287             throw re.rethrowFromSystemServer();
12288         }
12289     }
12290 
12291     /**
12292      * Called by the system to get the time at which the device owner last retrieved security
12293      * logging entries.
12294      *
12295      * @return the time at which the device owner most recently retrieved security logging entries,
12296      *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
12297      * @throws SecurityException if the caller is not the device owner, does not hold the
12298      *         MANAGE_USERS permission and is not the system.
12299      *
12300      * @hide
12301      */
12302     @TestApi
getLastSecurityLogRetrievalTime()12303     public long getLastSecurityLogRetrievalTime() {
12304         try {
12305             return mService.getLastSecurityLogRetrievalTime();
12306         } catch (RemoteException re) {
12307             throw re.rethrowFromSystemServer();
12308         }
12309     }
12310 
12311     /**
12312      * Called by the system to get the time at which the device owner last requested a bug report.
12313      *
12314      * @return the time at which the device owner most recently requested a bug report, in
12315      *         milliseconds since epoch; -1 if a bug report was never requested.
12316      * @throws SecurityException if the caller is not the device owner, does not hold the
12317      *         MANAGE_USERS permission and is not the system.
12318      *
12319      * @hide
12320      */
12321     @TestApi
getLastBugReportRequestTime()12322     public long getLastBugReportRequestTime() {
12323         try {
12324             return mService.getLastBugReportRequestTime();
12325         } catch (RemoteException re) {
12326             throw re.rethrowFromSystemServer();
12327         }
12328     }
12329 
12330     /**
12331      * Called by the system to get the time at which the device owner or profile owner of a
12332      * managed profile last retrieved network logging events.
12333      *
12334      * @return the time at which the device owner or profile owner most recently retrieved network
12335      *         logging events, in milliseconds since epoch; -1 if network logging events were
12336      *         never retrieved.
12337      * @throws SecurityException if the caller is not the device owner, does not hold the
12338      *         MANAGE_USERS permission and is not the system.
12339      *
12340      * @hide
12341      */
12342     @TestApi
getLastNetworkLogRetrievalTime()12343     public long getLastNetworkLogRetrievalTime() {
12344         try {
12345             return mService.getLastNetworkLogRetrievalTime();
12346         } catch (RemoteException re) {
12347             throw re.rethrowFromSystemServer();
12348         }
12349     }
12350 
12351     /**
12352      * Called by the system to find out whether the current user's IME was set by the device/profile
12353      * owner or the user.
12354      *
12355      * @return {@code true} if the user's IME was set by the device or profile owner, {@code false}
12356      *         otherwise.
12357      * @throws SecurityException if the caller is not the device owner/profile owner.
12358      *
12359      * @hide
12360      */
12361     @TestApi
isCurrentInputMethodSetByOwner()12362     public boolean isCurrentInputMethodSetByOwner() {
12363         try {
12364             return mService.isCurrentInputMethodSetByOwner();
12365         } catch (RemoteException re) {
12366             throw re.rethrowFromSystemServer();
12367         }
12368     }
12369 
12370     /**
12371      * Called by the system to get a list of CA certificates that were installed by the device or
12372      * profile owner.
12373      *
12374      * <p> The caller must be the target user's device owner/profile Owner or hold the
12375      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
12376      *
12377      * @param user The user for whom to retrieve information.
12378      * @return list of aliases identifying CA certificates installed by the device or profile owner
12379      * @throws SecurityException if the caller does not have permission to retrieve information
12380      *         about the given user's CA certificates.
12381      *
12382      * @hide
12383      */
12384     @TestApi
getOwnerInstalledCaCerts(@onNull UserHandle user)12385     public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
12386         try {
12387             return mService.getOwnerInstalledCaCerts(user).getList();
12388         } catch (RemoteException re) {
12389             throw re.rethrowFromSystemServer();
12390         }
12391     }
12392 
12393     /**
12394      * Returns whether factory reset protection policy is supported on the device.
12395      *
12396      * @return {@code true} if the device support factory reset protection policy.
12397      *
12398      * @hide
12399      */
12400     @TestApi
isFactoryResetProtectionPolicySupported()12401     public boolean isFactoryResetProtectionPolicySupported() {
12402         try {
12403             return mService.isFactoryResetProtectionPolicySupported();
12404         } catch (RemoteException re) {
12405             throw re.rethrowFromSystemServer();
12406         }
12407     }
12408 
12409     /**
12410      * Called by the device owner or profile owner to clear application user data of a given
12411      * package. The behaviour of this is equivalent to the target application calling
12412      * {@link android.app.ActivityManager#clearApplicationUserData()}.
12413      *
12414      * <p><strong>Note:</strong> an application can store data outside of its application data, e.g.
12415      * external storage or user dictionary. This data will not be wiped by calling this API.
12416      *
12417      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12418      * @param packageName The name of the package which will have its user data wiped.
12419      * @param executor The executor through which the listener should be invoked.
12420      * @param listener A callback object that will inform the caller when the clearing is done.
12421      * @throws SecurityException if the caller is not the device owner/profile owner.
12422      */
clearApplicationUserData(@onNull ComponentName admin, @NonNull String packageName, @NonNull @CallbackExecutor Executor executor, @NonNull OnClearApplicationUserDataListener listener)12423     public void clearApplicationUserData(@NonNull ComponentName admin,
12424             @NonNull String packageName, @NonNull @CallbackExecutor Executor executor,
12425             @NonNull OnClearApplicationUserDataListener listener) {
12426         throwIfParentInstance("clearAppData");
12427         Objects.requireNonNull(executor);
12428         Objects.requireNonNull(listener);
12429         try {
12430             mService.clearApplicationUserData(admin, packageName,
12431                     new IPackageDataObserver.Stub() {
12432                         public void onRemoveCompleted(String pkg, boolean succeeded) {
12433                             executor.execute(() ->
12434                                     listener.onApplicationUserDataCleared(pkg, succeeded));
12435                         }
12436                     });
12437         } catch (RemoteException re) {
12438             throw re.rethrowFromSystemServer();
12439         }
12440     }
12441 
12442     /**
12443      * Called by a device owner to specify whether logout is enabled for all secondary users. The
12444      * system may show a logout button that stops the user and switches back to the primary user.
12445      *
12446      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12447      * @param enabled whether logout should be enabled or not.
12448      * @throws SecurityException if {@code admin} is not a device owner.
12449      */
setLogoutEnabled(@onNull ComponentName admin, boolean enabled)12450     public void setLogoutEnabled(@NonNull ComponentName admin, boolean enabled) {
12451         throwIfParentInstance("setLogoutEnabled");
12452         try {
12453             mService.setLogoutEnabled(admin, enabled);
12454         } catch (RemoteException re) {
12455             throw re.rethrowFromSystemServer();
12456         }
12457     }
12458 
12459     /**
12460      * Returns whether logout is enabled by a device owner.
12461      *
12462      * @return {@code true} if logout is enabled by device owner, {@code false} otherwise.
12463      */
isLogoutEnabled()12464     public boolean isLogoutEnabled() {
12465         throwIfParentInstance("isLogoutEnabled");
12466         try {
12467             return mService.isLogoutEnabled();
12468         } catch (RemoteException re) {
12469             throw re.rethrowFromSystemServer();
12470         }
12471     }
12472 
12473     /**
12474      * Callback used in {@link #clearApplicationUserData}
12475      * to indicate that the clearing of an application's user data is done.
12476      */
12477     public interface OnClearApplicationUserDataListener {
12478         /**
12479          * Method invoked when clearing the application user data has completed.
12480          *
12481          * @param packageName The name of the package which had its user data cleared.
12482          * @param succeeded Whether the clearing succeeded. Clearing fails for device administrator
12483          *                  apps and protected system packages.
12484          */
onApplicationUserDataCleared(String packageName, boolean succeeded)12485         void onApplicationUserDataCleared(String packageName, boolean succeeded);
12486     }
12487 
12488     /**
12489      * Returns set of system apps that should be removed during provisioning.
12490      *
12491      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12492      * @param userId ID of the user to be provisioned.
12493      * @param provisioningAction action indicating type of provisioning, should be one of
12494      * {@link #ACTION_PROVISION_MANAGED_DEVICE}, {@link #ACTION_PROVISION_MANAGED_PROFILE} or
12495      * {@link #ACTION_PROVISION_MANAGED_USER}.
12496      *
12497      * @hide
12498      */
12499     @TestApi
getDisallowedSystemApps(@onNull ComponentName admin, @UserIdInt int userId, @NonNull String provisioningAction)12500     public @NonNull Set<String> getDisallowedSystemApps(@NonNull ComponentName admin,
12501             @UserIdInt int userId, @NonNull String provisioningAction) {
12502         try {
12503             return new ArraySet<>(
12504                     mService.getDisallowedSystemApps(admin, userId, provisioningAction));
12505         } catch (RemoteException re) {
12506             throw re.rethrowFromSystemServer();
12507         }
12508     }
12509 
12510     /**
12511      * Changes the current administrator to another one. All policies from the current
12512      * administrator are migrated to the new administrator. The whole operation is atomic -
12513      * the transfer is either complete or not done at all.
12514      *
12515      * <p>Depending on the current administrator (device owner, profile owner), you have the
12516      * following expected behaviour:
12517      * <ul>
12518      *     <li>A device owner can only be transferred to a new device owner</li>
12519      *     <li>A profile owner can only be transferred to a new profile owner</li>
12520      * </ul>
12521      *
12522      * <p>Use the {@code bundle} parameter to pass data to the new administrator. The data
12523      * will be received in the
12524      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}
12525      * callback of the new administrator.
12526      *
12527      * <p>The transfer has failed if the original administrator is still the corresponding owner
12528      * after calling this method.
12529      *
12530      * <p>The incoming target administrator must have the
12531      * <code>&lt;support-transfer-ownership /&gt;</code> tag inside the
12532      * <code>&lt;device-admin&gt;&lt;/device-admin&gt;</code> tags in the xml file referenced by
12533      * {@link DeviceAdminReceiver#DEVICE_ADMIN_META_DATA}. Otherwise an
12534      * {@link IllegalArgumentException} will be thrown.
12535      *
12536      * @param admin which {@link DeviceAdminReceiver} this request is associated with
12537      * @param target which {@link DeviceAdminReceiver} we want the new administrator to be
12538      * @param bundle data to be sent to the new administrator
12539      * @throws SecurityException if {@code admin} is not a device owner nor a profile owner
12540      * @throws IllegalArgumentException if {@code admin} or {@code target} is {@code null}, they
12541      * are components in the same package or {@code target} is not an active admin
12542      */
transferOwnership(@onNull ComponentName admin, @NonNull ComponentName target, @Nullable PersistableBundle bundle)12543     public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
12544             @Nullable PersistableBundle bundle) {
12545         throwIfParentInstance("transferOwnership");
12546         try {
12547             mService.transferOwnership(admin, target, bundle);
12548         } catch (RemoteException re) {
12549             throw re.rethrowFromSystemServer();
12550         }
12551     }
12552 
12553     /**
12554      * Called by a device owner to specify the user session start message. This may be displayed
12555      * during a user switch.
12556      * <p>
12557      * The message should be limited to a short statement or it may be truncated.
12558      * <p>
12559      * If the message needs to be localized, it is the responsibility of the
12560      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
12561      * and set a new version of this message accordingly.
12562      *
12563      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12564      * @param startUserSessionMessage message for starting user session, or {@code null} to use
12565      * system default message.
12566      * @throws SecurityException if {@code admin} is not a device owner.
12567      */
setStartUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence startUserSessionMessage)12568     public void setStartUserSessionMessage(
12569             @NonNull ComponentName admin, @Nullable CharSequence startUserSessionMessage) {
12570         throwIfParentInstance("setStartUserSessionMessage");
12571         try {
12572             mService.setStartUserSessionMessage(admin, startUserSessionMessage);
12573         } catch (RemoteException re) {
12574             throw re.rethrowFromSystemServer();
12575         }
12576     }
12577 
12578     /**
12579      * Called by a device owner to specify the user session end message. This may be displayed
12580      * during a user switch.
12581      * <p>
12582      * The message should be limited to a short statement or it may be truncated.
12583      * <p>
12584      * If the message needs to be localized, it is the responsibility of the
12585      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
12586      * and set a new version of this message accordingly.
12587      *
12588      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12589      * @param endUserSessionMessage message for ending user session, or {@code null} to use system
12590      * default message.
12591      * @throws SecurityException if {@code admin} is not a device owner.
12592      */
setEndUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence endUserSessionMessage)12593     public void setEndUserSessionMessage(
12594             @NonNull ComponentName admin, @Nullable CharSequence endUserSessionMessage) {
12595         throwIfParentInstance("setEndUserSessionMessage");
12596         try {
12597             mService.setEndUserSessionMessage(admin, endUserSessionMessage);
12598         } catch (RemoteException re) {
12599             throw re.rethrowFromSystemServer();
12600         }
12601     }
12602 
12603     /**
12604      * Returns the user session start message.
12605      *
12606      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12607      * @throws SecurityException if {@code admin} is not a device owner.
12608      */
getStartUserSessionMessage(@onNull ComponentName admin)12609     public CharSequence getStartUserSessionMessage(@NonNull ComponentName admin) {
12610         throwIfParentInstance("getStartUserSessionMessage");
12611         try {
12612             return mService.getStartUserSessionMessage(admin);
12613         } catch (RemoteException re) {
12614             throw re.rethrowFromSystemServer();
12615         }
12616     }
12617 
12618     /**
12619      * Returns the user session end message.
12620      *
12621      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12622      * @throws SecurityException if {@code admin} is not a device owner.
12623      */
getEndUserSessionMessage(@onNull ComponentName admin)12624     public CharSequence getEndUserSessionMessage(@NonNull ComponentName admin) {
12625         throwIfParentInstance("getEndUserSessionMessage");
12626         try {
12627             return mService.getEndUserSessionMessage(admin);
12628         } catch (RemoteException re) {
12629             throw re.rethrowFromSystemServer();
12630         }
12631     }
12632 
12633     /**
12634      * Called by device owner to add an override APN.
12635      *
12636      * <p>This method may returns {@code -1} if {@code apnSetting} conflicts with an existing
12637      * override APN. Update the existing conflicted APN with
12638      * {@link #updateOverrideApn(ComponentName, int, ApnSetting)} instead of adding a new entry.
12639      * <p>Two override APNs are considered to conflict when all the following APIs return
12640      * the same values on both override APNs:
12641      * <ul>
12642      *   <li>{@link ApnSetting#getOperatorNumeric()}</li>
12643      *   <li>{@link ApnSetting#getApnName()}</li>
12644      *   <li>{@link ApnSetting#getProxyAddressAsString()}</li>
12645      *   <li>{@link ApnSetting#getProxyPort()}</li>
12646      *   <li>{@link ApnSetting#getMmsProxyAddressAsString()}</li>
12647      *   <li>{@link ApnSetting#getMmsProxyPort()}</li>
12648      *   <li>{@link ApnSetting#getMmsc()}</li>
12649      *   <li>{@link ApnSetting#isEnabled()}</li>
12650      *   <li>{@link ApnSetting#getMvnoType()}</li>
12651      *   <li>{@link ApnSetting#getProtocol()}</li>
12652      *   <li>{@link ApnSetting#getRoamingProtocol()}</li>
12653      * </ul>
12654      *
12655      * @param admin which {@link DeviceAdminReceiver} this request is associated with
12656      * @param apnSetting the override APN to insert
12657      * @return The {@code id} of inserted override APN. Or {@code -1} when failed to insert into
12658      *         the database.
12659      * @throws SecurityException if {@code admin} is not a device owner.
12660      *
12661      * @see #setOverrideApnsEnabled(ComponentName, boolean)
12662      */
addOverrideApn(@onNull ComponentName admin, @NonNull ApnSetting apnSetting)12663     public int addOverrideApn(@NonNull ComponentName admin, @NonNull ApnSetting apnSetting) {
12664         throwIfParentInstance("addOverrideApn");
12665         if (mService != null) {
12666             try {
12667                 return mService.addOverrideApn(admin, apnSetting);
12668             } catch (RemoteException e) {
12669                 throw e.rethrowFromSystemServer();
12670             }
12671         }
12672         return -1;
12673     }
12674 
12675     /**
12676      * Called by device owner to update an override APN.
12677      *
12678      * <p>This method may returns {@code false} if there is no override APN with the given
12679      * {@code apnId}.
12680      * <p>This method may also returns {@code false} if {@code apnSetting} conflicts with an
12681      * existing override APN. Update the existing conflicted APN instead.
12682      * <p>See {@link #addOverrideApn} for the definition of conflict.
12683      *
12684      * @param admin which {@link DeviceAdminReceiver} this request is associated with
12685      * @param apnId the {@code id} of the override APN to update
12686      * @param apnSetting the override APN to update
12687      * @return {@code true} if the required override APN is successfully updated,
12688      *         {@code false} otherwise.
12689      * @throws SecurityException if {@code admin} is not a device owner.
12690      *
12691      * @see #setOverrideApnsEnabled(ComponentName, boolean)
12692      */
updateOverrideApn(@onNull ComponentName admin, int apnId, @NonNull ApnSetting apnSetting)12693     public boolean updateOverrideApn(@NonNull ComponentName admin, int apnId,
12694             @NonNull ApnSetting apnSetting) {
12695         throwIfParentInstance("updateOverrideApn");
12696         if (mService != null) {
12697             try {
12698                 return mService.updateOverrideApn(admin, apnId, apnSetting);
12699             } catch (RemoteException e) {
12700                 throw e.rethrowFromSystemServer();
12701             }
12702         }
12703         return false;
12704     }
12705 
12706     /**
12707      * Called by device owner to remove an override APN.
12708      *
12709      * <p>This method may returns {@code false} if there is no override APN with the given
12710      * {@code apnId}.
12711      *
12712      * @param admin which {@link DeviceAdminReceiver} this request is associated with
12713      * @param apnId the {@code id} of the override APN to remove
12714      * @return {@code true} if the required override APN is successfully removed, {@code false}
12715      *         otherwise.
12716      * @throws SecurityException if {@code admin} is not a device owner.
12717      *
12718      * @see #setOverrideApnsEnabled(ComponentName, boolean)
12719      */
removeOverrideApn(@onNull ComponentName admin, int apnId)12720     public boolean removeOverrideApn(@NonNull ComponentName admin, int apnId) {
12721         throwIfParentInstance("removeOverrideApn");
12722         if (mService != null) {
12723             try {
12724                 return mService.removeOverrideApn(admin, apnId);
12725             } catch (RemoteException e) {
12726                 throw e.rethrowFromSystemServer();
12727             }
12728         }
12729         return false;
12730     }
12731 
12732     /**
12733      * Called by device owner to get all override APNs inserted by device owner.
12734      *
12735      * @param admin which {@link DeviceAdminReceiver} this request is associated with
12736      * @return A list of override APNs inserted by device owner.
12737      * @throws SecurityException if {@code admin} is not a device owner.
12738      *
12739      * @see #setOverrideApnsEnabled(ComponentName, boolean)
12740      */
getOverrideApns(@onNull ComponentName admin)12741     public List<ApnSetting> getOverrideApns(@NonNull ComponentName admin) {
12742         throwIfParentInstance("getOverrideApns");
12743         if (mService != null) {
12744             try {
12745                 return mService.getOverrideApns(admin);
12746             } catch (RemoteException e) {
12747                 throw e.rethrowFromSystemServer();
12748             }
12749         }
12750         return Collections.emptyList();
12751     }
12752 
12753     /**
12754      * Called by device owner to set if override APNs should be enabled.
12755      * <p> Override APNs are separated from other APNs on the device, and can only be inserted or
12756      * modified by the device owner. When enabled, only override APNs are in use, any other APNs
12757      * are ignored.
12758      *
12759      * @param admin which {@link DeviceAdminReceiver} this request is associated with
12760      * @param enabled {@code true} if override APNs should be enabled, {@code false} otherwise
12761      * @throws SecurityException if {@code admin} is not a device owner.
12762      */
setOverrideApnsEnabled(@onNull ComponentName admin, boolean enabled)12763     public void setOverrideApnsEnabled(@NonNull ComponentName admin, boolean enabled) {
12764         throwIfParentInstance("setOverrideApnEnabled");
12765         if (mService != null) {
12766             try {
12767                 mService.setOverrideApnsEnabled(admin, enabled);
12768             } catch (RemoteException e) {
12769                 throw e.rethrowFromSystemServer();
12770             }
12771         }
12772     }
12773 
12774     /**
12775      * Called by device owner to check if override APNs are currently enabled.
12776      *
12777      * @param admin which {@link DeviceAdminReceiver} this request is associated with
12778      * @return {@code true} if override APNs are currently enabled, {@code false} otherwise.
12779      * @throws SecurityException if {@code admin} is not a device owner.
12780      *
12781      * @see #setOverrideApnsEnabled(ComponentName, boolean)
12782      */
isOverrideApnEnabled(@onNull ComponentName admin)12783     public boolean isOverrideApnEnabled(@NonNull ComponentName admin) {
12784         throwIfParentInstance("isOverrideApnEnabled");
12785         if (mService != null) {
12786             try {
12787                 return mService.isOverrideApnEnabled(admin);
12788             } catch (RemoteException e) {
12789                 throw e.rethrowFromSystemServer();
12790             }
12791         }
12792         return false;
12793     }
12794 
12795     /**
12796      * Returns the data passed from the current administrator to the new administrator during an
12797      * ownership transfer. This is the same {@code bundle} passed in
12798      * {@link #transferOwnership(ComponentName, ComponentName, PersistableBundle)}. The bundle is
12799      * persisted until the profile owner or device owner is removed.
12800      *
12801      * <p>This is the same <code>bundle</code> received in the
12802      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}.
12803      * Use this method to retrieve it after the transfer as long as the new administrator is the
12804      * active device or profile owner.
12805      *
12806      * <p>Returns <code>null</code> if no ownership transfer was started for the calling user.
12807      *
12808      * @see #transferOwnership
12809      * @see DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)
12810      * @throws SecurityException if the caller is not a device or profile owner.
12811      */
12812     @Nullable
getTransferOwnershipBundle()12813     public PersistableBundle getTransferOwnershipBundle() {
12814         throwIfParentInstance("getTransferOwnershipBundle");
12815         try {
12816             return mService.getTransferOwnershipBundle();
12817         } catch (RemoteException re) {
12818             throw re.rethrowFromSystemServer();
12819         }
12820     }
12821 
12822     /**
12823      * Sets the global Private DNS mode to opportunistic.
12824      * May only be called by the device owner.
12825      *
12826      * <p>In this mode, the DNS subsystem will attempt a TLS handshake to the network-supplied
12827      * resolver prior to attempting name resolution in cleartext.
12828      *
12829      * <p>Note: The device owner won't be able to set the global private DNS mode if there are
12830      * unaffiliated secondary users or profiles on the device. It's recommended that affiliation
12831      * ids are set for new users as soon as possible after provisioning via
12832      * {@link #setAffiliationIds}.
12833      *
12834      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12835      *
12836      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully, or
12837      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set.
12838      *
12839      * @throws SecurityException if the caller is not the device owner.
12840      */
setGlobalPrivateDnsModeOpportunistic( @onNull ComponentName admin)12841     public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeOpportunistic(
12842             @NonNull ComponentName admin) {
12843         throwIfParentInstance("setGlobalPrivateDnsModeOpportunistic");
12844 
12845         if (mService == null) {
12846             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
12847         }
12848 
12849         try {
12850             return mService.setGlobalPrivateDns(admin, PRIVATE_DNS_MODE_OPPORTUNISTIC, null);
12851         } catch (RemoteException re) {
12852             throw re.rethrowFromSystemServer();
12853         }
12854     }
12855 
12856     /**
12857      * Sets the global Private DNS host to be used.
12858      * May only be called by the device owner.
12859      *
12860      * <p>Note that the method is blocking as it will perform a connectivity check to the resolver,
12861      * to ensure it is valid. Because of that, the method should not be called on any thread that
12862      * relates to user interaction, such as the UI thread.
12863      *
12864      * <p>In case a VPN is used in conjunction with Private DNS resolver, the Private DNS resolver
12865      * must be reachable both from within and outside the VPN. Otherwise, the device may lose
12866      * the ability to resolve hostnames as system traffic to the resolver may not go through the
12867      * VPN.
12868      *
12869      * <p>Note: The device owner won't be able to set the global private DNS mode if there are
12870      * unaffiliated secondary users or profiles on the device. It's recommended that affiliation
12871      * ids are set for new users as soon as possible after provisioning via
12872      * {@link #setAffiliationIds}.
12873      *
12874      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12875      * @param privateDnsHost The hostname of a server that implements DNS over TLS (RFC7858).
12876      *
12877      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully,
12878      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set or
12879      *         {@code PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING} if the specified host does not
12880      *         implement RFC7858.
12881      *
12882      * @throws IllegalArgumentException if the {@code privateDnsHost} is not a valid hostname.
12883      *
12884      * @throws SecurityException if the caller is not the device owner.
12885      */
setGlobalPrivateDnsModeSpecifiedHost( @onNull ComponentName admin, @NonNull String privateDnsHost)12886     @WorkerThread public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeSpecifiedHost(
12887             @NonNull ComponentName admin, @NonNull String privateDnsHost) {
12888         throwIfParentInstance("setGlobalPrivateDnsModeSpecifiedHost");
12889         Objects.requireNonNull(privateDnsHost, "dns resolver is null");
12890 
12891         if (mService == null) {
12892             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
12893         }
12894 
12895         if (NetworkUtilsInternal.isWeaklyValidatedHostname(privateDnsHost)) {
12896             if (!PrivateDnsConnectivityChecker.canConnectToPrivateDnsServer(privateDnsHost)) {
12897                 return PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING;
12898             }
12899         }
12900 
12901         try {
12902             return mService.setGlobalPrivateDns(
12903                     admin, PRIVATE_DNS_MODE_PROVIDER_HOSTNAME, privateDnsHost);
12904         } catch (RemoteException re) {
12905             throw re.rethrowFromSystemServer();
12906         }
12907     }
12908 
12909     /**
12910      * Called by device owner or profile owner of an organization-owned managed profile to install
12911      * a system update from the given file. The device will be
12912      * rebooted in order to finish installing the update. Note that if the device is rebooted, this
12913      * doesn't necessarily mean that the update has been applied successfully. The caller should
12914      * additionally check the system version with {@link android.os.Build#FINGERPRINT} or {@link
12915      * android.os.Build.VERSION}. If an error occurs during processing the OTA before the reboot,
12916      * the caller will be notified by {@link InstallSystemUpdateCallback}. If device does not have
12917      * sufficient battery level, the installation will fail with error {@link
12918      * InstallSystemUpdateCallback#UPDATE_ERROR_BATTERY_LOW}.
12919      *
12920      * @param admin The {@link DeviceAdminReceiver} that this request is associated with.
12921      * @param updateFilePath An Uri of the file that contains the update. The file should be
12922      * readable by the calling app.
12923      * @param executor The executor through which the callback should be invoked.
12924      * @param callback A callback object that will inform the caller when installing an update
12925      * fails.
12926      */
installSystemUpdate( @onNull ComponentName admin, @NonNull Uri updateFilePath, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)12927     public void installSystemUpdate(
12928             @NonNull ComponentName admin, @NonNull Uri updateFilePath,
12929             @NonNull @CallbackExecutor Executor executor,
12930             @NonNull InstallSystemUpdateCallback callback) {
12931         throwIfParentInstance("installUpdate");
12932         if (mService == null) {
12933             return;
12934         }
12935         try (ParcelFileDescriptor fileDescriptor = mContext.getContentResolver()
12936                     .openFileDescriptor(updateFilePath, "r")) {
12937             mService.installUpdateFromFile(
12938                     admin, fileDescriptor, new StartInstallingUpdateCallback.Stub() {
12939                         @Override
12940                         public void onStartInstallingUpdateError(
12941                                 int errorCode, String errorMessage) {
12942                             executeCallback(errorCode, errorMessage, executor, callback);
12943                         }
12944                     });
12945         } catch (RemoteException e) {
12946             throw e.rethrowFromSystemServer();
12947         } catch (FileNotFoundException e) {
12948             Log.w(TAG, e);
12949             executeCallback(
12950                     InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
12951                     Log.getStackTraceString(e),
12952                     executor, callback);
12953         } catch (IOException e) {
12954             Log.w(TAG, e);
12955             executeCallback(
12956                     InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN, Log.getStackTraceString(e),
12957                     executor, callback);
12958         }
12959     }
12960 
executeCallback(int errorCode, String errorMessage, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)12961     private void executeCallback(int errorCode, String errorMessage,
12962             @NonNull @CallbackExecutor Executor executor,
12963             @NonNull InstallSystemUpdateCallback callback) {
12964         executor.execute(() -> callback.onInstallUpdateError(errorCode, errorMessage));
12965     }
12966 
12967     /**
12968      * Returns the system-wide Private DNS mode.
12969      *
12970      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12971      * @return one of {@code PRIVATE_DNS_MODE_OFF}, {@code PRIVATE_DNS_MODE_OPPORTUNISTIC},
12972      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} or {@code PRIVATE_DNS_MODE_UNKNOWN}.
12973      * @throws SecurityException if the caller is not the device owner.
12974      */
getGlobalPrivateDnsMode(@onNull ComponentName admin)12975     public int getGlobalPrivateDnsMode(@NonNull ComponentName admin) {
12976         throwIfParentInstance("setGlobalPrivateDns");
12977         if (mService == null) {
12978             return PRIVATE_DNS_MODE_UNKNOWN;
12979         }
12980 
12981         try {
12982             return mService.getGlobalPrivateDnsMode(admin);
12983         } catch (RemoteException re) {
12984             throw re.rethrowFromSystemServer();
12985         }
12986     }
12987 
12988     /**
12989      * Returns the system-wide Private DNS host.
12990      *
12991      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12992      * @return The hostname used for Private DNS queries, null if none is set.
12993      * @throws SecurityException if the caller is not the device owner.
12994      */
getGlobalPrivateDnsHost(@onNull ComponentName admin)12995     public @Nullable String getGlobalPrivateDnsHost(@NonNull ComponentName admin) {
12996         throwIfParentInstance("setGlobalPrivateDns");
12997         if (mService == null) {
12998             return null;
12999         }
13000 
13001         try {
13002             return mService.getGlobalPrivateDnsHost(admin);
13003         } catch (RemoteException re) {
13004             throw re.rethrowFromSystemServer();
13005         }
13006     }
13007 
13008     /**
13009      * Deprecated. Use {@code markProfileOwnerOnOrganizationOwnedDevice} instead.
13010      * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#Q} or
13011      * below, will behave the same as {@link #markProfileOwnerOnOrganizationOwnedDevice}.
13012      *
13013      * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#R}
13014      * or above, will throw an UnsupportedOperationException when called.
13015      *
13016      * @deprecated Use {@link #markProfileOwnerOnOrganizationOwnedDevice} instead.
13017      *
13018      * @hide
13019      */
13020     @Deprecated
13021     @SystemApi
13022     @RequiresPermission(value = android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS,
13023             conditional = true)
setProfileOwnerCanAccessDeviceIds(@onNull ComponentName who)13024     public void setProfileOwnerCanAccessDeviceIds(@NonNull ComponentName who) {
13025         ApplicationInfo ai = mContext.getApplicationInfo();
13026         if (ai.targetSdkVersion > Build.VERSION_CODES.Q) {
13027             throw new UnsupportedOperationException(
13028                     "This method is deprecated. use markProfileOwnerOnOrganizationOwnedDevice"
13029                     + " instead.");
13030         } else {
13031             markProfileOwnerOnOrganizationOwnedDevice(who);
13032         }
13033     }
13034 
13035     /**
13036      * Marks the profile owner of the given user as managing an organization-owned device.
13037      * That will give it access to device identifiers (such as serial number, IMEI and MEID)
13038      * as well as other privileges.
13039      *
13040      * @hide
13041      */
13042     @TestApi
13043     @RequiresPermission(anyOf = {
13044             android.Manifest.permission.MARK_DEVICE_ORGANIZATION_OWNED,
13045             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
13046     }, conditional = true)
markProfileOwnerOnOrganizationOwnedDevice(@onNull ComponentName who)13047     public void markProfileOwnerOnOrganizationOwnedDevice(@NonNull ComponentName who) {
13048         if (mService == null) {
13049             return;
13050         }
13051         try {
13052             mService.markProfileOwnerOnOrganizationOwnedDevice(who, myUserId());
13053         } catch (RemoteException re) {
13054             throw re.rethrowFromSystemServer();
13055         }
13056     }
13057 
13058     /**
13059      * Allows a set of packages to access cross-profile calendar APIs.
13060      *
13061      * <p>Called by a profile owner of a managed profile.
13062      *
13063      * <p>Calling with a {@code null} value for the set disables the restriction so that all
13064      * packages are allowed to access cross-profile calendar APIs. Calling with an empty set
13065      * disallows all packages from accessing cross-profile calendar APIs. If this method isn't
13066      * called, no package is allowed to access cross-profile calendar APIs by default.
13067      *
13068      * @param admin which {@link DeviceAdminReceiver} this request is associated with
13069      * @param packageNames set of packages to be allowlisted
13070      * @throws SecurityException if {@code admin} is not a profile owner
13071      *
13072      * @see #getCrossProfileCalendarPackages(ComponentName)
13073      */
setCrossProfileCalendarPackages(@onNull ComponentName admin, @Nullable Set<String> packageNames)13074     public void setCrossProfileCalendarPackages(@NonNull ComponentName admin,
13075             @Nullable Set<String> packageNames) {
13076         throwIfParentInstance("setCrossProfileCalendarPackages");
13077         if (mService != null) {
13078             try {
13079                 mService.setCrossProfileCalendarPackages(admin, packageNames == null ? null
13080                         : new ArrayList<>(packageNames));
13081             } catch (RemoteException e) {
13082                 throw e.rethrowFromSystemServer();
13083             }
13084         }
13085     }
13086 
13087     /**
13088      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
13089      *
13090      * <p>Called by a profile owner of a managed profile.
13091      *
13092      * @param admin which {@link DeviceAdminReceiver} this request is associated with
13093      * @return the set of names of packages that were previously allowed via
13094      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
13095      * empty set if none have been allowed
13096      * @throws SecurityException if {@code admin} is not a profile owner
13097      *
13098      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
13099      */
getCrossProfileCalendarPackages(@onNull ComponentName admin)13100     public @Nullable Set<String> getCrossProfileCalendarPackages(@NonNull ComponentName admin) {
13101         throwIfParentInstance("getCrossProfileCalendarPackages");
13102         if (mService != null) {
13103             try {
13104                 final List<String> packageNames = mService.getCrossProfileCalendarPackages(admin);
13105                 return packageNames == null ? null : new ArraySet<>(packageNames);
13106             } catch (RemoteException e) {
13107                 throw e.rethrowFromSystemServer();
13108             }
13109         }
13110         return Collections.emptySet();
13111     }
13112 
13113     /**
13114      * Returns if a package is allowed to access cross-profile calendar APIs.
13115      *
13116      * <p>A package is allowed to access cross-profile calendar APIs if it's allowed by
13117      * admins via {@link #setCrossProfileCalendarPackages(ComponentName, Set)} and
13118      * {@link android.provider.Settings.Secure#CROSS_PROFILE_CALENDAR_ENABLED}
13119      * is turned on in the managed profile.
13120      *
13121      * <p>To query for a specific user, use
13122      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
13123      * that user, and get a {@link DevicePolicyManager} from this context.
13124      *
13125      * @param packageName the name of the package
13126      * @return {@code true} if the package is allowed to access cross-profile calendar APIs,
13127      * {@code false} otherwise
13128      *
13129      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
13130      * @see #getCrossProfileCalendarPackages(ComponentName)
13131      * @hide
13132      */
13133     @RequiresPermission(anyOf = {
13134             permission.INTERACT_ACROSS_USERS_FULL,
13135             permission.INTERACT_ACROSS_USERS
13136     }, conditional = true)
isPackageAllowedToAccessCalendar(@onNull String packageName)13137     public boolean isPackageAllowedToAccessCalendar(@NonNull  String packageName) {
13138         throwIfParentInstance("isPackageAllowedToAccessCalendar");
13139         if (mService != null) {
13140             try {
13141                 return mService.isPackageAllowedToAccessCalendarForUser(packageName,
13142                         myUserId());
13143             } catch (RemoteException e) {
13144                 throw e.rethrowFromSystemServer();
13145             }
13146         }
13147         return false;
13148     }
13149 
13150     /**
13151      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
13152      *
13153      * <p>To query for a specific user, use
13154      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
13155      * that user, and get a {@link DevicePolicyManager} from this context.
13156      *
13157      * @return the set of names of packages that were previously allowed via
13158      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
13159      * empty set if none have been allowed
13160      *
13161      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
13162      * @see #getCrossProfileCalendarPackages(ComponentName)
13163      * @hide
13164      */
13165     @RequiresPermission(anyOf = {
13166             permission.INTERACT_ACROSS_USERS_FULL,
13167             permission.INTERACT_ACROSS_USERS
13168     })
getCrossProfileCalendarPackages()13169     public @Nullable Set<String> getCrossProfileCalendarPackages() {
13170         throwIfParentInstance("getCrossProfileCalendarPackages");
13171         if (mService != null) {
13172             try {
13173                 final List<String> packageNames = mService.getCrossProfileCalendarPackagesForUser(
13174                         myUserId());
13175                 return packageNames == null ? null : new ArraySet<>(packageNames);
13176             } catch (RemoteException e) {
13177                 throw e.rethrowFromSystemServer();
13178             }
13179         }
13180         return Collections.emptySet();
13181     }
13182 
13183     /**
13184      * Sets the set of admin-allowlisted package names that are allowed to request user consent for
13185      * cross-profile communication.
13186      *
13187      * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
13188      *
13189      * <p>Previous calls are overridden by each subsequent call to this method.
13190      *
13191      * <p>Note that other apps may be able to request user consent for cross-profile communication
13192      * if they have been explicitly allowlisted by the OEM.
13193      *
13194      * <p>When previously-set cross-profile packages are missing from {@code packageNames}, the
13195      * app-op for {@code INTERACT_ACROSS_PROFILES} will be reset for those packages. This will not
13196      * occur for packages that are allowlisted by the OEM.
13197      *
13198      * @param admin the {@link DeviceAdminReceiver} this request is associated with
13199      * @param packageNames the new cross-profile package names
13200      */
setCrossProfilePackages( @onNull ComponentName admin, @NonNull Set<String> packageNames)13201     public void setCrossProfilePackages(
13202             @NonNull ComponentName admin, @NonNull Set<String> packageNames) {
13203         throwIfParentInstance("setCrossProfilePackages");
13204         if (mService != null) {
13205             try {
13206                 mService.setCrossProfilePackages(admin, new ArrayList<>(packageNames));
13207             } catch (RemoteException e) {
13208                 throw e.rethrowFromSystemServer();
13209             }
13210         }
13211     }
13212 
13213     /**
13214      * Returns the set of package names that the admin has previously set as allowed to request user
13215      * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
13216      * Set)}.
13217      *
13218      * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
13219      *
13220      * <p>Note that other apps not included in the returned set may be able to request user consent
13221      * for cross-profile communication if they have been explicitly allowlisted by the OEM.
13222      *
13223      * @param admin the {@link DeviceAdminReceiver} this request is associated with
13224      * @return the set of package names the admin has previously set as allowed to request user
13225      * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
13226      * Set)}
13227      */
getCrossProfilePackages(@onNull ComponentName admin)13228     public @NonNull Set<String> getCrossProfilePackages(@NonNull ComponentName admin) {
13229         throwIfParentInstance("getCrossProfilePackages");
13230         if (mService != null) {
13231             try {
13232                 return new ArraySet<>(mService.getCrossProfilePackages(admin));
13233             } catch (RemoteException e) {
13234                 throw e.rethrowFromSystemServer();
13235             }
13236         }
13237         return Collections.emptySet();
13238     }
13239 
13240     /**
13241      * Returns the combined set of the following:
13242      * <ul>
13243      * <li>The package names that the admin has previously set as allowed to request user consent
13244      * for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
13245      * Set)}.</li>
13246      * <li>The default package names set by the OEM that are allowed to request user consent for
13247      * cross-profile communication without being explicitly enabled by the admin, via {@link
13248      * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array
13249      * #vendor_cross_profile_apps}.</li>
13250      * </ul>
13251      *
13252      * @return the combined set of allowlisted package names set via
13253      * {@link #setCrossProfilePackages(ComponentName, Set)}, {@link com.android.internal.R.array
13254      * #cross_profile_apps}, and {@link com.android.internal.R.array#vendor_cross_profile_apps}.
13255      *
13256      * @hide
13257      */
13258     @RequiresPermission(anyOf = {
13259             permission.INTERACT_ACROSS_USERS_FULL,
13260             permission.INTERACT_ACROSS_USERS,
13261             permission.INTERACT_ACROSS_PROFILES
13262     })
getAllCrossProfilePackages()13263     public @NonNull Set<String> getAllCrossProfilePackages() {
13264         throwIfParentInstance("getAllCrossProfilePackages");
13265         if (mService != null) {
13266             try {
13267                 return new ArraySet<>(mService.getAllCrossProfilePackages());
13268             } catch (RemoteException e) {
13269                 throw e.rethrowFromSystemServer();
13270             }
13271         }
13272         return Collections.emptySet();
13273     }
13274 
13275     /**
13276      * Returns the default package names set by the OEM that are allowed to request user consent for
13277      * cross-profile communication without being explicitly enabled by the admin, via {@link
13278      * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array
13279      * #vendor_cross_profile_apps}.
13280      *
13281      * @hide
13282      */
13283     @TestApi
getDefaultCrossProfilePackages()13284     public @NonNull Set<String> getDefaultCrossProfilePackages() {
13285         throwIfParentInstance("getDefaultCrossProfilePackages");
13286         if (mService != null) {
13287             try {
13288                 return new ArraySet<>(mService.getDefaultCrossProfilePackages());
13289             } catch (RemoteException e) {
13290                 throw e.rethrowFromSystemServer();
13291             }
13292         }
13293         return Collections.emptySet();
13294     }
13295 
13296     /**
13297      * Returns whether the device is being used as a managed kiosk. These requirements are as
13298      * follows:
13299      * <ul>
13300      *     <li>The device is in Lock Task (therefore there is also a Device Owner app on the
13301      *     device)</li>
13302      *     <li>The Lock Task feature {@link DevicePolicyManager#LOCK_TASK_FEATURE_SYSTEM_INFO} is
13303      *     not enabled, so the system info in the status bar is not visible</li>
13304      *     <li>The device does not have a secure lock screen (e.g. it has no lock screen or has
13305      *     swipe-to-unlock)</li>
13306      *     <li>The device is not in the middle of an ephemeral user session</li>
13307      * </ul>
13308      *
13309      * <p>Publicly-accessible dedicated devices don't have the same privacy model as
13310      * personally-used devices. In particular, user consent popups don't make sense as a barrier to
13311      * accessing persistent data on these devices since the user giving consent and the user whose
13312      * data is on the device are unlikely to be the same. These consent popups prevent the true
13313      * remote management of these devices.
13314      *
13315      * <p>This condition is not sufficient to cover APIs that would access data that only lives for
13316      * the duration of the user's session, since the user has an expectation of privacy in these
13317      * conditions that more closely resembles use of a personal device. In those cases, see {@link
13318      * #isUnattendedManagedKiosk()}.
13319      *
13320      * @hide
13321      */
13322     @SystemApi
13323     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isManagedKiosk()13324     public boolean isManagedKiosk() {
13325         throwIfParentInstance("isManagedKiosk");
13326         if (mService != null) {
13327             try {
13328                 return mService.isManagedKiosk();
13329             } catch (RemoteException e) {
13330                 throw e.rethrowFromSystemServer();
13331             }
13332         }
13333         return false;
13334     }
13335 
13336     /**
13337      * Returns whether the device is being used as an unattended managed kiosk. These requirements
13338      * are as follows:
13339      * <ul>
13340      *     <li>The device is being used as a managed kiosk, as defined at {@link
13341      *     #isManagedKiosk()}</li>
13342      *     <li>The device has not received user input for at least 30 minutes</li>
13343      * </ul>
13344      *
13345      * <p>See {@link #isManagedKiosk()} for context. This is a stronger requirement that also
13346      * ensures that the device hasn't been interacted with recently, making it an appropriate check
13347      * for privacy-sensitive APIs that wouldn't be appropriate during an active user session.
13348      *
13349      * @hide
13350      */
13351     @SystemApi
13352     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isUnattendedManagedKiosk()13353     public boolean isUnattendedManagedKiosk() {
13354         throwIfParentInstance("isUnattendedManagedKiosk");
13355         if (mService != null) {
13356             try {
13357                 return mService.isUnattendedManagedKiosk();
13358             } catch (RemoteException e) {
13359                 throw e.rethrowFromSystemServer();
13360             }
13361         }
13362         return false;
13363     }
13364 
13365     /**
13366      * Starts an activity to view calendar events in the managed profile.
13367      *
13368      * @param eventId the id of the event to be viewed
13369      * @param start the start time of the event
13370      * @param end the end time of the event
13371      * @param allDay if the event is an all-day event
13372      * @param flags flags to be set for the intent
13373      * @return {@code true} if the activity is started successfully, {@code false} otherwise
13374      *
13375      * @see CalendarContract#startViewCalendarEventInManagedProfile(Context, String, long, long,
13376      * long, boolean, int)
13377      *
13378      * @hide
13379      */
startViewCalendarEventInManagedProfile(long eventId, long start, long end, boolean allDay, int flags)13380     public boolean startViewCalendarEventInManagedProfile(long eventId, long start, long end,
13381             boolean allDay, int flags) {
13382         throwIfParentInstance("startViewCalendarEventInManagedProfile");
13383         if (mService != null) {
13384             try {
13385                 return mService.startViewCalendarEventInManagedProfile(mContext.getPackageName(),
13386                         eventId, start, end, allDay, flags);
13387             } catch (RemoteException e) {
13388                 throw e.rethrowFromSystemServer();
13389             }
13390         }
13391         return false;
13392     }
13393 
13394     /**
13395      * Called by Device owner to disable user control over apps. User will not be able to clear
13396      * app data or force-stop packages.
13397      *
13398      * @param admin which {@link DeviceAdminReceiver} this request is associated with
13399      * @param packages The package names for the apps.
13400      * @throws SecurityException if {@code admin} is not a device owner.
13401      */
setUserControlDisabledPackages(@onNull ComponentName admin, @NonNull List<String> packages)13402     public void setUserControlDisabledPackages(@NonNull ComponentName admin,
13403             @NonNull List<String> packages) {
13404         throwIfParentInstance("setUserControlDisabledPackages");
13405         if (mService != null) {
13406             try {
13407                 mService.setUserControlDisabledPackages(admin, packages);
13408             } catch (RemoteException re) {
13409                 throw re.rethrowFromSystemServer();
13410             }
13411         }
13412     }
13413 
13414     /**
13415      * Returns the list of packages over which user control is disabled by the device owner.
13416      *
13417      * @param admin which {@link DeviceAdminReceiver} this request is associated with
13418      * @throws SecurityException if {@code admin} is not a device owner.
13419      */
getUserControlDisabledPackages(@onNull ComponentName admin)13420     public @NonNull List<String> getUserControlDisabledPackages(@NonNull ComponentName admin) {
13421         throwIfParentInstance("getUserControlDisabledPackages");
13422         if (mService != null) {
13423             try {
13424                 return mService.getUserControlDisabledPackages(admin);
13425             } catch (RemoteException re) {
13426                 throw re.rethrowFromSystemServer();
13427             }
13428         }
13429         return Collections.emptyList();
13430     }
13431 
13432     /**
13433      * Called by device owner or profile owner of an organization-owned managed profile to toggle
13434      * Common Criteria mode for the device. When the device is in Common Criteria mode,
13435      * certain device functionalities are tuned to meet the higher
13436      * security level required by Common Criteria certification. For example:
13437      * <ul>
13438      * <li> Bluetooth long term key material is additionally integrity-protected with AES-GCM. </li>
13439      * <li> WiFi configuration store is additionally integrity-protected with AES-GCM. </li>
13440      * </ul>
13441      * Common Criteria mode is disabled by default.
13442      *
13443      * <p><em>Note:</em> if Common Critera mode is turned off after being enabled previously,
13444      * all existing WiFi configurations will be lost.
13445      *
13446      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
13447      * @param enabled whether Common Criteria mode should be enabled or not.
13448      */
setCommonCriteriaModeEnabled(@onNull ComponentName admin, boolean enabled)13449     public void setCommonCriteriaModeEnabled(@NonNull ComponentName admin, boolean enabled) {
13450         throwIfParentInstance("setCommonCriteriaModeEnabled");
13451         if (mService != null) {
13452             try {
13453                 mService.setCommonCriteriaModeEnabled(admin, enabled);
13454             } catch (RemoteException e) {
13455                 throw e.rethrowFromSystemServer();
13456             }
13457         }
13458     }
13459 
13460     /**
13461      * Returns whether Common Criteria mode is currently enabled. Device owner and profile owner of
13462      * an organization-owned managed profile can query its own Common Criteria mode setting by
13463      * calling this method with its admin {@link ComponentName}. Any caller can obtain the
13464      * aggregated device-wide Common Criteria mode state by passing {@code null} as the
13465      * {@code admin} argument.
13466      *
13467      * @param admin which {@link DeviceAdminReceiver} this request is associated with, or
13468      *     {@code null} if the caller is not a device admin.
13469      * @return {@code true} if Common Criteria mode is enabled, {@code false} otherwise.
13470      */
isCommonCriteriaModeEnabled(@ullable ComponentName admin)13471     public boolean isCommonCriteriaModeEnabled(@Nullable ComponentName admin) {
13472         throwIfParentInstance("isCommonCriteriaModeEnabled");
13473         if (mService != null) {
13474             try {
13475                 return mService.isCommonCriteriaModeEnabled(admin);
13476             } catch (RemoteException e) {
13477                 throw e.rethrowFromSystemServer();
13478             }
13479         }
13480         return false;
13481     }
13482 
13483     /**
13484      * Called by profile owner of an organization-owned managed profile to check whether
13485      * personal apps are suspended.
13486      *
13487      * @return a bitmask of reasons for personal apps suspension or
13488      *     {@link #PERSONAL_APPS_NOT_SUSPENDED} if apps are not suspended.
13489      * @see #setPersonalAppsSuspended
13490      */
getPersonalAppsSuspendedReasons( @onNull ComponentName admin)13491     public @PersonalAppsSuspensionReason int getPersonalAppsSuspendedReasons(
13492             @NonNull ComponentName admin) {
13493         throwIfParentInstance("getPersonalAppsSuspendedReasons");
13494         if (mService != null) {
13495             try {
13496                 return mService.getPersonalAppsSuspendedReasons(admin);
13497             } catch (RemoteException re) {
13498                 throw re.rethrowFromSystemServer();
13499             }
13500         }
13501         return 0;
13502     }
13503 
13504     /**
13505      * Called by a profile owner of an organization-owned managed profile to suspend personal
13506      * apps on the device. When personal apps are suspended the device can only be used for calls.
13507      *
13508      * <p>When personal apps are suspended, an ongoing notification about that is shown to the user.
13509      * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE}
13510      * in the profile owner package. Profile owner implementation that uses personal apps suspension
13511      * must handle this intent.
13512      *
13513      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
13514      * @param suspended Whether personal apps should be suspended.
13515      * @throws IllegalStateException if the profile owner doesn't have an activity that handles
13516      *        {@link #ACTION_CHECK_POLICY_COMPLIANCE}
13517      */
setPersonalAppsSuspended(@onNull ComponentName admin, boolean suspended)13518     public void setPersonalAppsSuspended(@NonNull ComponentName admin, boolean suspended) {
13519         throwIfParentInstance("setPersonalAppsSuspended");
13520         if (mService != null) {
13521             try {
13522                 mService.setPersonalAppsSuspended(admin, suspended);
13523             } catch (RemoteException re) {
13524                 throw re.rethrowFromSystemServer();
13525             }
13526         }
13527     }
13528 
13529     /**
13530      * Called by a profile owner of an organization-owned managed profile to set maximum time
13531      * the profile is allowed to be turned off. If the profile is turned off for longer, personal
13532      * apps are suspended on the device.
13533      *
13534      * <p>When personal apps are suspended, an ongoing notification about that is shown to the user.
13535      * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE}
13536      * in the profile owner package. Profile owner implementation that uses personal apps suspension
13537      * must handle this intent.
13538      *
13539      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
13540      * @param timeoutMillis Maximum time the profile is allowed to be off in milliseconds or 0 if
13541      *        not limited. The minimum non-zero value corresponds to 72 hours. If an admin sets a
13542      *        smaller non-zero vaulue, 72 hours will be set instead.
13543      * @throws IllegalStateException if the profile owner doesn't have an activity that handles
13544      *        {@link #ACTION_CHECK_POLICY_COMPLIANCE}
13545      * @see #setPersonalAppsSuspended
13546      */
setManagedProfileMaximumTimeOff(@onNull ComponentName admin, long timeoutMillis)13547     public void setManagedProfileMaximumTimeOff(@NonNull ComponentName admin, long timeoutMillis) {
13548         throwIfParentInstance("setManagedProfileMaximumTimeOff");
13549         if (mService != null) {
13550             try {
13551                 mService.setManagedProfileMaximumTimeOff(admin, timeoutMillis);
13552             } catch (RemoteException re) {
13553                 throw re.rethrowFromSystemServer();
13554             }
13555         }
13556     }
13557 
13558      /**
13559      * Called by a profile owner of an organization-owned managed profile to get maximum time
13560      * the profile is allowed to be turned off.
13561      *
13562      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
13563      * @return Maximum time the profile is allowed to be off in milliseconds or 0 if not limited.
13564      * @see #setPersonalAppsSuspended
13565      */
getManagedProfileMaximumTimeOff(@onNull ComponentName admin)13566     public long getManagedProfileMaximumTimeOff(@NonNull ComponentName admin) {
13567         throwIfParentInstance("getManagedProfileMaximumTimeOff");
13568         if (mService != null) {
13569             try {
13570                 return mService.getManagedProfileMaximumTimeOff(admin);
13571             } catch (RemoteException re) {
13572                 throw re.rethrowFromSystemServer();
13573             }
13574         }
13575         return 0;
13576     }
13577 
13578     /**
13579      * Called by a profile owner of an organization-owned managed profile to acknowledge that the
13580      * device is compliant and the user can turn the profile off if needed according to the maximum
13581      * time off policy.
13582      *
13583      * This method should be called when the device is deemed compliant after getting
13584      * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)} callback in
13585      * case it is overridden. Before this method is called the user is still free to turn the
13586      * profile off, but the timer won't be reset, so personal apps will be suspended sooner.
13587      *
13588      * DPCs only need acknowledging device compliance if they override
13589      * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)}, otherwise
13590      * compliance is acknowledged automatically.
13591      *
13592      * @throws IllegalStateException if the user isn't unlocked
13593      * @see #isComplianceAcknowledgementRequired()
13594      * @see #setManagedProfileMaximumTimeOff(ComponentName, long)
13595      * @see DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)
13596      */
acknowledgeDeviceCompliant()13597     public void acknowledgeDeviceCompliant() {
13598         throwIfParentInstance("acknowledgeDeviceCompliant");
13599         if (mService != null) {
13600             try {
13601                 mService.acknowledgeDeviceCompliant();
13602             } catch (RemoteException re) {
13603                 throw re.rethrowFromSystemServer();
13604             }
13605         }
13606     }
13607 
13608     /**
13609      * Called by a profile owner of an organization-owned managed profile to query whether it needs
13610      * to acknowledge device compliance to allow the user to turn the profile off if needed
13611      * according to the maximum profile time off policy.
13612      *
13613      * Normally when acknowledgement is needed the DPC gets a
13614      * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)} callback.
13615      * But if the callback was not delivered or handled for some reason, this method can be used to
13616      * verify if acknowledgement is needed.
13617      *
13618      * @throws IllegalStateException if the user isn't unlocked
13619      * @see #acknowledgeDeviceCompliant()
13620      * @see #setManagedProfileMaximumTimeOff(ComponentName, long)
13621      * @see DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)
13622      */
isComplianceAcknowledgementRequired()13623     public boolean isComplianceAcknowledgementRequired() {
13624         throwIfParentInstance("isComplianceAcknowledgementRequired");
13625         if (mService != null) {
13626             try {
13627                 return mService.isComplianceAcknowledgementRequired();
13628             } catch (RemoteException re) {
13629                 throw re.rethrowFromSystemServer();
13630             }
13631         }
13632         return false;
13633     }
13634 
13635     /**
13636      * Returns {@code true} when {@code userId} has a profile owner that is capable of resetting
13637      * password in RUNNING_LOCKED state. For that it should have at least one direct boot aware
13638      * component and have an active password reset token. Can only be called by the system.
13639      * @hide
13640      */
canProfileOwnerResetPasswordWhenLocked(int userId)13641     public boolean canProfileOwnerResetPasswordWhenLocked(int userId) {
13642         if (mService != null) {
13643             try {
13644                 return mService.canProfileOwnerResetPasswordWhenLocked(userId);
13645             } catch (RemoteException re) {
13646                 throw re.rethrowFromSystemServer();
13647             }
13648         }
13649         return false;
13650     }
13651 
13652     /**
13653      * Used by CTS to set the result of the next safety operation check.
13654      *
13655      * @hide
13656      */
13657     @TestApi
13658     @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
setNextOperationSafety(@evicePolicyOperation int operation, @OperationSafetyReason int reason)13659     public void setNextOperationSafety(@DevicePolicyOperation int operation,
13660             @OperationSafetyReason int reason) {
13661         if (mService != null) {
13662             try {
13663                 mService.setNextOperationSafety(operation, reason);
13664             } catch (RemoteException re) {
13665                 throw re.rethrowFromSystemServer();
13666             }
13667         }
13668     }
13669 
13670     /**
13671      * Returns an enrollment-specific identifier of this device, which is guaranteed to be the same
13672      * value for the same device, enrolled into the same organization by the same managing app.
13673      * This identifier is high-entropy, useful for uniquely identifying individual devices within
13674      * the same organisation.
13675      * It is available both in a work profile and on a fully-managed device.
13676      * The identifier would be consistent even if the work profile is removed and enrolled again
13677      * (to the same organization), or the device is factory reset and re-enrolled.
13678      *
13679      * Can only be called by the Profile Owner or Device Owner, if the
13680      * {@link #setOrganizationId(String)} was previously called.
13681      * If {@link #setOrganizationId(String)} was not called, then the returned value will be an
13682      * empty string.
13683      *
13684      * <p>Note about access to device identifiers: a device owner, a profile owner of an
13685      * organization-owned device or the delegated certificate installer (holding the
13686      * {@link #DELEGATION_CERT_INSTALL} delegation) on such a device can still obtain hardware
13687      * identifiers by calling e.g. {@link android.os.Build#getSerial()}, in addition to using
13688      * this method. However, a profile owner on a personal (non organization-owned) device, or the
13689      * delegated certificate installer on such a device, cannot obtain hardware identifiers anymore
13690      * and must switch to using this method.
13691      *
13692      * @return A stable, enrollment-specific identifier.
13693      * @throws SecurityException if the caller is not a profile owner or device owner.
13694      */
getEnrollmentSpecificId()13695     @NonNull public String getEnrollmentSpecificId() {
13696         throwIfParentInstance("getEnrollmentSpecificId");
13697         if (mService == null) {
13698             return "";
13699         }
13700 
13701         try {
13702             return mService.getEnrollmentSpecificId(mContext.getPackageName());
13703         } catch (RemoteException re) {
13704             throw re.rethrowFromSystemServer();
13705         }
13706     }
13707 
13708     /**
13709      * Sets the Enterprise ID for the work profile or managed device. This is a requirement for
13710      * generating an enrollment-specific ID for the device, see {@link #getEnrollmentSpecificId()}.
13711      *
13712      * It is recommended that the Enterprise ID is at least 6 characters long, and no more than
13713      * 64 characters.
13714      *
13715      * @param enterpriseId An identifier of the organization this work profile or device is
13716      *                     enrolled into.
13717      */
setOrganizationId(@onNull String enterpriseId)13718     public void setOrganizationId(@NonNull String enterpriseId) {
13719         throwIfParentInstance("setOrganizationId");
13720         setOrganizationIdForUser(mContext.getPackageName(), enterpriseId, myUserId());
13721     }
13722 
13723     /**
13724      * Sets the Enterprise ID for the work profile or managed device. This is a requirement for
13725      * generating an enrollment-specific ID for the device, see
13726      * {@link #getEnrollmentSpecificId()}.
13727      *
13728      * @hide
13729      */
setOrganizationIdForUser(@onNull String packageName, @NonNull String enterpriseId, @UserIdInt int userId)13730     public void setOrganizationIdForUser(@NonNull String packageName,
13731             @NonNull String enterpriseId, @UserIdInt int userId) {
13732         if (mService == null) {
13733             return;
13734         }
13735         try {
13736             mService.setOrganizationIdForUser(packageName, enterpriseId, userId);
13737         } catch (RemoteException re) {
13738             throw re.rethrowFromSystemServer();
13739         }
13740     }
13741 
13742     /**
13743      * Creates and provisions a managed profile and sets the
13744      * {@link ManagedProfileProvisioningParams#getProfileAdminComponentName()} as the profile
13745      * owner.
13746      *
13747      * <p>The method {@link #checkProvisioningPreCondition} must be returning {@link #CODE_OK}
13748      * before calling this method.
13749      *
13750      * @param provisioningParams Params required to provision a managed profile,
13751      * see {@link ManagedProfileProvisioningParams}.
13752      * @return The {@link UserHandle} of the created profile or {@code null} if the service is
13753      * not available.
13754      * @throws SecurityException if the caller does not hold
13755      * {@link android.Manifest.permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
13756      * @throws ProvisioningException if an error occurred during provisioning.
13757      * @hide
13758      */
13759     @Nullable
13760     @TestApi
createAndProvisionManagedProfile( @onNull ManagedProfileProvisioningParams provisioningParams)13761     public UserHandle createAndProvisionManagedProfile(
13762             @NonNull ManagedProfileProvisioningParams provisioningParams)
13763             throws ProvisioningException {
13764         if (mService == null) {
13765             return null;
13766         }
13767         try {
13768             return mService.createAndProvisionManagedProfile(
13769                     provisioningParams, mContext.getPackageName());
13770         } catch (ServiceSpecificException e) {
13771             throw new ProvisioningException(e, e.errorCode);
13772         } catch (RemoteException e) {
13773             throw e.rethrowFromSystemServer();
13774         }
13775     }
13776 
13777     /**
13778      * Provisions a managed device and sets the {@code deviceAdminComponentName} as the device
13779      * owner.
13780      *
13781      * <p>The method {@link #checkProvisioningPreCondition} must be returning {@link #CODE_OK}
13782      * before calling this method.
13783      *
13784      * @param provisioningParams Params required to provision a fully managed device,
13785      * see {@link FullyManagedDeviceProvisioningParams}.
13786      *
13787      * @throws SecurityException if the caller does not hold
13788      * {@link android.Manifest.permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
13789      * @throws ProvisioningException if an error occurred during provisioning.
13790      *
13791      * @hide
13792      */
13793     @TestApi
13794     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
provisionFullyManagedDevice( @onNull FullyManagedDeviceProvisioningParams provisioningParams)13795     public void provisionFullyManagedDevice(
13796             @NonNull FullyManagedDeviceProvisioningParams provisioningParams)
13797             throws ProvisioningException {
13798         if (mService != null) {
13799             try {
13800                 mService.provisionFullyManagedDevice(provisioningParams, mContext.getPackageName());
13801             } catch (ServiceSpecificException e) {
13802                 throw new ProvisioningException(e, e.errorCode);
13803             } catch (RemoteException re) {
13804                 throw re.rethrowFromSystemServer();
13805             }
13806         }
13807     }
13808 
13809     /**
13810      * Resets the default cross profile intent filters that were set during
13811      * {@link #createAndProvisionManagedProfile} between {@code userId} and all it's managed
13812      * profiles if any.
13813      *
13814      * @hide
13815      */
13816     @TestApi
13817     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
resetDefaultCrossProfileIntentFilters(@serIdInt int userId)13818     public void resetDefaultCrossProfileIntentFilters(@UserIdInt int userId) {
13819         if (mService != null) {
13820             try {
13821                 mService.resetDefaultCrossProfileIntentFilters(userId);
13822             } catch (RemoteException re) {
13823                 throw re.rethrowFromSystemServer();
13824             }
13825         }
13826     }
13827 
13828     /**
13829      * Returns true if the caller is running on a device where the admin can grant
13830      * permissions related to device sensors.
13831      * This is a signal that the device is a fully-managed device where personal usage is
13832      * discouraged.
13833      * The list of permissions is listed in
13834      * {@link #setPermissionGrantState(ComponentName, String, String, int)}.
13835      *
13836      * May be called by any app.
13837      * @return true if the app can grant device sensors-related permissions, false otherwise.
13838      */
canAdminGrantSensorsPermissions()13839     public boolean canAdminGrantSensorsPermissions() {
13840         throwIfParentInstance("canAdminGrantSensorsPermissions");
13841         if (mService == null) {
13842             return false;
13843         }
13844         try {
13845             return mService.canAdminGrantSensorsPermissionsForUser(myUserId());
13846         } catch (RemoteException re) {
13847             throw re.rethrowFromSystemServer();
13848         }
13849     }
13850 
13851     /**
13852      * Sets the device owner type for a managed device (e.g. financed device).
13853      *
13854      * @param admin The {@link DeviceAdminReceiver} that is the device owner.
13855      * @param deviceOwnerType The device owner type is set to. Use
13856      * {@link #DEVICE_OWNER_TYPE_DEFAULT} for the default device owner type. Use
13857      * {@link #DEVICE_OWNER_TYPE_FINANCED} for the financed device owner type.
13858      *
13859      * @throws IllegalStateException When admin is not the device owner, or there is no device
13860      *     owner, or attempting to set the device owner type again for the same admin.
13861      * @throws SecurityException If the caller does not have the permission
13862      *     {@link permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
13863      *
13864      * @hide
13865      */
setDeviceOwnerType(@onNull ComponentName admin, @DeviceOwnerType int deviceOwnerType)13866     public void setDeviceOwnerType(@NonNull ComponentName admin,
13867             @DeviceOwnerType int deviceOwnerType) {
13868         throwIfParentInstance("setDeviceOwnerType");
13869         if (mService != null) {
13870             try {
13871                 mService.setDeviceOwnerType(admin, deviceOwnerType);
13872             } catch (RemoteException re) {
13873                 throw re.rethrowFromSystemServer();
13874             }
13875         }
13876     }
13877 
13878     /**
13879      * Returns the device owner type for the admin used in
13880      * {@link #setDeviceOwnerType(ComponentName, int)}. {@link #DEVICE_OWNER_TYPE_DEFAULT}
13881      * would be returned when the device owner type is not set for the device owner admin.
13882      *
13883      * @param admin The {@link DeviceAdminReceiver} that is the device owner.
13884      *
13885      * @throws IllegalStateException When admin is not the device owner or there is no device owner.
13886      *
13887      * @hide
13888      */
13889     @DeviceOwnerType
getDeviceOwnerType(@onNull ComponentName admin)13890     public int getDeviceOwnerType(@NonNull ComponentName admin) {
13891         throwIfParentInstance("getDeviceOwnerType");
13892         if (mService != null) {
13893             try {
13894                 return mService.getDeviceOwnerType(admin);
13895             } catch (RemoteException re) {
13896                 throw re.rethrowFromSystemServer();
13897             }
13898         }
13899         return DEVICE_OWNER_TYPE_DEFAULT;
13900     }
13901 
13902     /**
13903      * Called by device owner or profile owner of an organization-owned managed profile to
13904      * enable or disable USB data signaling for the device. When disabled, USB data connections
13905      * (except from charging functions) are prohibited.
13906      *
13907      * <p> This API is not supported on all devices, the caller should call
13908      * {@link #canUsbDataSignalingBeDisabled()} to check whether enabling or disabling USB data
13909      * signaling is supported on the device.
13910      *
13911      * @param enabled whether USB data signaling should be enabled or not.
13912      * @throws SecurityException if the caller is not a device owner or a profile owner on
13913      *         an organization-owned managed profile.
13914      * @throws IllegalStateException if disabling USB data signaling is not supported or
13915      *         if USB data signaling fails to be enabled/disabled.
13916      */
setUsbDataSignalingEnabled(boolean enabled)13917     public void setUsbDataSignalingEnabled(boolean enabled) {
13918         throwIfParentInstance("setUsbDataSignalingEnabled");
13919         if (mService != null) {
13920             try {
13921                 mService.setUsbDataSignalingEnabled(mContext.getPackageName(), enabled);
13922             } catch (RemoteException e) {
13923                 throw e.rethrowFromSystemServer();
13924             }
13925         }
13926     }
13927 
13928     /**
13929      * Returns whether USB data signaling is currently enabled.
13930      *
13931      * <p> When called by a device owner or profile owner of an organization-owned managed profile,
13932      * this API returns whether USB data signaling is currently enabled by that admin. When called
13933      * by any other app, returns whether USB data signaling is currently enabled on the device.
13934      *
13935      * @return {@code true} if USB data signaling is enabled, {@code false} otherwise.
13936      */
isUsbDataSignalingEnabled()13937     public boolean isUsbDataSignalingEnabled() {
13938         throwIfParentInstance("isUsbDataSignalingEnabled");
13939         if (mService != null) {
13940             try {
13941                 return mService.isUsbDataSignalingEnabled(mContext.getPackageName());
13942             } catch (RemoteException e) {
13943                 throw e.rethrowFromSystemServer();
13944             }
13945         }
13946         return true;
13947     }
13948 
13949     /**
13950      * Called by the system to check whether USB data signaling is currently enabled for this user.
13951      *
13952      * @param userId which user to check for.
13953      * @return {@code true} if USB data signaling is enabled, {@code false} otherwise.
13954      * @hide
13955      */
isUsbDataSignalingEnabledForUser(@serIdInt int userId)13956     public boolean isUsbDataSignalingEnabledForUser(@UserIdInt int userId) {
13957         throwIfParentInstance("isUsbDataSignalingEnabledForUser");
13958         if (mService != null) {
13959             try {
13960                 return mService.isUsbDataSignalingEnabledForUser(userId);
13961             } catch (RemoteException e) {
13962                 throw e.rethrowFromSystemServer();
13963             }
13964         }
13965         return true;
13966     }
13967 
13968     /**
13969      * Returns whether enabling or disabling USB data signaling is supported on the device.
13970      *
13971      * @return {@code true} if the device supports enabling and disabling USB data signaling.
13972      */
canUsbDataSignalingBeDisabled()13973     public boolean canUsbDataSignalingBeDisabled() {
13974         throwIfParentInstance("canUsbDataSignalingBeDisabled");
13975         if (mService != null) {
13976             try {
13977                 return mService.canUsbDataSignalingBeDisabled();
13978             } catch (RemoteException re) {
13979                 throw re.rethrowFromSystemServer();
13980             }
13981         }
13982         return false;
13983     }
13984 
13985     /**
13986      * Gets the list of {@link #isAffiliatedUser() affiliated} users running on foreground.
13987      *
13988      * @return list of {@link #isAffiliatedUser() affiliated} users running on foreground.
13989      *
13990      * @throws SecurityException if the calling application is not a device owner
13991      */
13992     @NonNull
listForegroundAffiliatedUsers()13993     public List<UserHandle> listForegroundAffiliatedUsers() {
13994         if (mService == null) return Collections.emptyList();
13995 
13996         try {
13997             return mService.listForegroundAffiliatedUsers();
13998         } catch (RemoteException re) {
13999             throw re.rethrowFromSystemServer();
14000         }
14001     }
14002 
14003     /**
14004      * Lists apps that are exempt from policies (such as
14005      * {@link #setPackagesSuspended(ComponentName, String[], boolean)}).
14006      *
14007      * @hide
14008      */
14009     @TestApi
14010     @RequiresPermission(value = android.Manifest.permission.MANAGE_DEVICE_ADMINS)
getPolicyExemptApps()14011     public @NonNull Set<String> getPolicyExemptApps() {
14012         if (mService == null) return Collections.emptySet();
14013 
14014         try {
14015             return new HashSet<>(mService.listPolicyExemptApps());
14016         } catch (RemoteException e) {
14017             throw e.rethrowFromSystemServer();
14018         }
14019     }
14020 }
14021