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.accounts.Account;
23 import android.annotation.CallbackExecutor;
24 import android.annotation.ColorInt;
25 import android.annotation.IntDef;
26 import android.annotation.NonNull;
27 import android.annotation.Nullable;
28 import android.annotation.RequiresFeature;
29 import android.annotation.RequiresPermission;
30 import android.annotation.SdkConstant;
31 import android.annotation.SdkConstant.SdkConstantType;
32 import android.annotation.StringDef;
33 import android.annotation.SuppressLint;
34 import android.annotation.SystemApi;
35 import android.annotation.SystemService;
36 import android.annotation.TestApi;
37 import android.annotation.UserHandleAware;
38 import android.annotation.UserIdInt;
39 import android.annotation.WorkerThread;
40 import android.app.Activity;
41 import android.app.IServiceConnection;
42 import android.app.KeyguardManager;
43 import android.app.admin.SecurityLog.SecurityEvent;
44 import android.compat.annotation.UnsupportedAppUsage;
45 import android.content.ComponentName;
46 import android.content.Context;
47 import android.content.Intent;
48 import android.content.IntentFilter;
49 import android.content.ServiceConnection;
50 import android.content.pm.ApplicationInfo;
51 import android.content.pm.IPackageDataObserver;
52 import android.content.pm.PackageManager;
53 import android.content.pm.PackageManager.NameNotFoundException;
54 import android.content.pm.ParceledListSlice;
55 import android.content.pm.UserInfo;
56 import android.graphics.Bitmap;
57 import android.net.PrivateDnsConnectivityChecker;
58 import android.net.ProxyInfo;
59 import android.net.Uri;
60 import android.os.Build;
61 import android.os.Bundle;
62 import android.os.ParcelFileDescriptor;
63 import android.os.Parcelable;
64 import android.os.PersistableBundle;
65 import android.os.Process;
66 import android.os.RemoteCallback;
67 import android.os.RemoteException;
68 import android.os.ServiceSpecificException;
69 import android.os.UserHandle;
70 import android.os.UserManager;
71 import android.os.UserManager.UserOperationException;
72 import android.os.UserManager.UserOperationResult;
73 import android.provider.CalendarContract;
74 import android.provider.ContactsContract.Directory;
75 import android.provider.Settings;
76 import android.security.AttestedKeyPair;
77 import android.security.Credentials;
78 import android.security.KeyChain;
79 import android.security.KeyChainException;
80 import android.security.keymaster.KeymasterCertificateChain;
81 import android.security.keystore.AttestationUtils;
82 import android.security.keystore.KeyAttestationException;
83 import android.security.keystore.KeyGenParameterSpec;
84 import android.security.keystore.ParcelableKeyGenParameterSpec;
85 import android.security.keystore.StrongBoxUnavailableException;
86 import android.service.restrictions.RestrictionsReceiver;
87 import android.telephony.TelephonyManager;
88 import android.telephony.data.ApnSetting;
89 import android.text.TextUtils;
90 import android.util.ArraySet;
91 import android.util.DebugUtils;
92 import android.util.Log;
93 import android.util.Pair;
94 
95 import com.android.internal.annotations.VisibleForTesting;
96 import com.android.internal.net.NetworkUtilsInternal;
97 import com.android.internal.os.BackgroundThread;
98 import com.android.internal.util.Preconditions;
99 import com.android.org.conscrypt.TrustedCertificateStore;
100 
101 import java.io.ByteArrayInputStream;
102 import java.io.FileNotFoundException;
103 import java.io.IOException;
104 import java.lang.annotation.Retention;
105 import java.lang.annotation.RetentionPolicy;
106 import java.net.InetSocketAddress;
107 import java.net.Proxy;
108 import java.security.KeyFactory;
109 import java.security.KeyPair;
110 import java.security.NoSuchAlgorithmException;
111 import java.security.PrivateKey;
112 import java.security.cert.Certificate;
113 import java.security.cert.CertificateException;
114 import java.security.cert.CertificateFactory;
115 import java.security.cert.X509Certificate;
116 import java.security.spec.InvalidKeySpecException;
117 import java.security.spec.PKCS8EncodedKeySpec;
118 import java.util.ArrayList;
119 import java.util.Arrays;
120 import java.util.Collections;
121 import java.util.HashSet;
122 import java.util.List;
123 import java.util.Map;
124 import java.util.Objects;
125 import java.util.Set;
126 import java.util.concurrent.CompletableFuture;
127 import java.util.concurrent.ExecutionException;
128 import java.util.concurrent.Executor;
129 
130 // TODO(b/172376923) - add CarDevicePolicyManager examples below (or remove reference to it).
131 /**
132  * Public interface for managing policies enforced on a device. Most clients of this class must be
133  * registered with the system as a <a href="{@docRoot}guide/topics/admin/device-admin.html">device
134  * administrator</a>. Additionally, a device administrator may be registered as either a profile or
135  * device owner. A given method is accessible to all device administrators unless the documentation
136  * for that method specifies that it is restricted to either device or profile owners. Any
137  * application calling an api may only pass as an argument a device administrator component it
138  * owns. Otherwise, a {@link SecurityException} will be thrown.
139  *
140  * <p><b>Note: </b>on
141  * {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, some methods can
142  * throw an {@link UnsafeStateException} exception (for example, if the vehicle is moving), so
143  * callers running on automotive builds should wrap every method call under the methods provided by
144  * {@code android.car.admin.CarDevicePolicyManager}.
145  *
146  * <div class="special reference">
147  * <h3>Developer Guides</h3>
148  * <p>
149  * For more information about managing policies for device administration, read the <a href=
150  * "{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a> developer
151  * guide. </div>
152  */
153 @SystemService(Context.DEVICE_POLICY_SERVICE)
154 @RequiresFeature(PackageManager.FEATURE_DEVICE_ADMIN)
155 @SuppressLint("UseIcu")
156 public class DevicePolicyManager {
157 
158     private static String TAG = "DevicePolicyManager";
159 
160     private final Context mContext;
161     private final IDevicePolicyManager mService;
162     private final boolean mParentInstance;
163 
164     /** @hide */
DevicePolicyManager(Context context, IDevicePolicyManager service)165     public DevicePolicyManager(Context context, IDevicePolicyManager service) {
166         this(context, service, false);
167     }
168 
169     /**
170      * Called when a managed profile has been provisioned.
171      *
172      * @throws SecurityException if the caller does not hold
173      * {@link android.Manifest.permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
174      * @hide
175      */
176     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
finalizeWorkProfileProvisioning( @onNull UserHandle managedProfileUser, @Nullable Account migratedAccount)177     public void finalizeWorkProfileProvisioning(
178             @NonNull UserHandle managedProfileUser, @Nullable Account migratedAccount) {
179         Objects.requireNonNull(managedProfileUser, "managedProfileUser can't be null");
180         if (mService == null) {
181             throw new IllegalStateException("Could not find DevicePolicyManagerService");
182         }
183         try {
184             mService.finalizeWorkProfileProvisioning(managedProfileUser, migratedAccount);
185         } catch (RemoteException e) {
186             throw e.rethrowFromSystemServer();
187         }
188     }
189 
190     /** @hide */
191     @VisibleForTesting
DevicePolicyManager(Context context, IDevicePolicyManager service, boolean parentInstance)192     protected DevicePolicyManager(Context context, IDevicePolicyManager service,
193             boolean parentInstance) {
194         mContext = context;
195         mService = service;
196         mParentInstance = parentInstance;
197     }
198 
199     /** @hide test will override it. */
200     @VisibleForTesting
myUserId()201     protected int myUserId() {
202         return mContext.getUserId();
203     }
204 
205     /**
206      * Activity action: Starts the provisioning flow which sets up a managed profile.
207      *
208      * <p>A managed profile allows data separation for example for the usage of a
209      * device as a personal and corporate device. The user which provisioning is started from and
210      * the managed profile share a launcher.
211      *
212      * <p>This intent will typically be sent by a mobile device management application (MDM).
213      * Provisioning adds a managed profile and sets the MDM as the profile owner who has full
214      * control over the profile.
215      *
216      * <p>It is possible to check if provisioning is allowed or not by querying the method
217      * {@link #isProvisioningAllowed(String)}.
218      *
219      * <p>In version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this intent must contain the
220      * extra {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}.
221      * As of {@link android.os.Build.VERSION_CODES#M}, it should contain the extra
222      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead, although specifying only
223      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported.
224      *
225      * <p>The intent may also contain the following extras:
226      * <ul>
227      * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, optional </li>
228      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional, supported from
229      * {@link android.os.Build.VERSION_CODES#N}</li>
230      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
231      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
232      * <li>{@link #EXTRA_PROVISIONING_SKIP_USER_CONSENT}, optional</li>
233      * <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION}, optional</li>
234      * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
235      * </ul>
236      *
237      * <p>When managed provisioning has completed, broadcasts are sent to the application specified
238      * in the provisioning intent. The
239      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the
240      * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in
241      * the primary profile.
242      *
243      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when managed provisioning has
244      * completed, along with the above broadcast, activity intent
245      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the profile owner.
246      *
247      * <p>If provisioning fails, the managedProfile is removed so the device returns to its
248      * previous state.
249      *
250      * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
251      * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
252      * the provisioning flow was successful, although this doesn't guarantee the full flow will
253      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
254      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
255      */
256     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
257     public static final String ACTION_PROVISION_MANAGED_PROFILE
258         = "android.app.action.PROVISION_MANAGED_PROFILE";
259 
260     /**
261      * Activity action: Starts the provisioning flow which sets up a managed user.
262      *
263      * <p>This intent will typically be sent by a mobile device management application (MDM).
264      * Provisioning configures the user as managed user and sets the MDM as the profile
265      * owner who has full control over the user. Provisioning can only happen before user setup has
266      * been completed. Use {@link #isProvisioningAllowed(String)} to check if provisioning is
267      * allowed.
268      *
269      * <p>The intent contains the following extras:
270      * <ul>
271      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
272      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
273      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
274      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
275      * </ul>
276      *
277      * <p>If provisioning fails, the device returns to its previous state.
278      *
279      * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
280      * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
281      * the provisioning flow was successful, although this doesn't guarantee the full flow will
282      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
283      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
284      *
285      * @hide
286      */
287     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
288     public static final String ACTION_PROVISION_MANAGED_USER
289         = "android.app.action.PROVISION_MANAGED_USER";
290 
291     /**
292      * Activity action: Starts the provisioning flow which sets up a managed device.
293      * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
294      *
295      * <p> During device owner provisioning a device admin app is set as the owner of the device.
296      * A device owner has full control over the device. The device owner can not be modified by the
297      * user.
298      *
299      * <p> A typical use case would be a device that is owned by a company, but used by either an
300      * employee or client.
301      *
302      * <p> An intent with this action can be sent only on an unprovisioned device.
303      * It is possible to check if provisioning is allowed or not by querying the method
304      * {@link #isProvisioningAllowed(String)}.
305      *
306      * <p>The intent contains the following extras:
307      * <ul>
308      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
309      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
310      * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
311      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
312      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
313      * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
314      * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional</li>
315      * </ul>
316      *
317      * <p>When device owner provisioning has completed, an intent of the type
318      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
319      * device owner.
320      *
321      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
322      * completed, along with the above broadcast, activity intent
323      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
324      *
325      * <p>If provisioning fails, the device is factory reset.
326      *
327      * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
328      * of the provisioning flow was successful, although this doesn't guarantee the full flow will
329      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
330      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
331      *
332      * @deprecated to support {@link android.os.Build.VERSION_CODES#S} and later, admin apps must
333      * implement activities with intent filters for the {@link #ACTION_GET_PROVISIONING_MODE} and
334      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} intent actions; using {@link
335      * #ACTION_PROVISION_MANAGED_DEVICE} to start provisioning will cause the provisioning to fail;
336      * to additionally support pre-{@link android.os.Build.VERSION_CODES#S}, admin apps must also
337      * continue to use this constant.
338      */
339     @Deprecated
340     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
341     public static final String ACTION_PROVISION_MANAGED_DEVICE
342         = "android.app.action.PROVISION_MANAGED_DEVICE";
343 
344     /**
345      * Activity action: launch when user provisioning completed, i.e.
346      * {@link #getUserProvisioningState()} returns one of the complete state.
347      *
348      * <p> Please note that the API behavior is not necessarily consistent across various releases,
349      * and devices, as it's contract between SetupWizard and ManagedProvisioning. The default
350      * implementation is that ManagedProvisioning launches SetupWizard in NFC provisioning only.
351      *
352      * <p> The activity must be protected by permission
353      * {@link android.Manifest.permission#BIND_DEVICE_ADMIN}, and the process must hold
354      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE} to be launched.
355      * Only one {@link ComponentName} in the entire system should be enabled, and the rest of the
356      * components are not started by this intent.
357      * @hide
358      */
359     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
360     @SystemApi
361     public static final String ACTION_STATE_USER_SETUP_COMPLETE =
362             "android.app.action.STATE_USER_SETUP_COMPLETE";
363 
364     /**
365      * Activity action: Starts the provisioning flow which sets up a managed device.
366      *
367      * <p>During device owner provisioning, a device admin app is downloaded and set as the owner of
368      * the device. A device owner has full control over the device. The device owner can not be
369      * modified by the user and the only way of resetting the device is via factory reset.
370      *
371      * <p>From version {@link android.os.Build.VERSION_CODES#Q}, the admin app can choose
372      * whether to set up a fully managed device or a managed profile. For the admin app to support
373      * this, it must have an activity with intent filter {@link #ACTION_GET_PROVISIONING_MODE} and
374      * another one with intent filter {@link #ACTION_ADMIN_POLICY_COMPLIANCE}. For example:
375      * <pre>
376      * &lt;activity
377      *     android:name=".GetProvisioningModeActivity"
378      *     android:label="@string/app_name"
379      *     android:permission="android.permission.BIND_DEVICE_ADMIN"&gt;
380      *     &lt;intent-filter&gt;
381      *         &lt;action
382      *             android:name="android.app.action.GET_PROVISIONING_MODE" /&gt;
383      *         &lt;category android:name="android.intent.category.DEFAULT" /&gt;
384      *     &lt;/intent-filter&gt;
385      * &lt;/activity&gt;
386      *
387      * &lt;activity
388      *     android:name=".PolicyComplianceActivity"
389      *     android:label="@string/app_name"
390      *     android:permission="android.permission.BIND_DEVICE_ADMIN"&gt;
391      *     &lt;intent-filter&gt;
392      *         &lt;action
393      *             android:name="android.app.action.ADMIN_POLICY_COMPLIANCE" /&gt;
394      *         &lt;category android:name="android.intent.category.DEFAULT" /&gt;
395      *     &lt;/intent-filter&gt;
396      * &lt;/activity&gt;</pre>
397      *
398      * <p>A typical use case would be a device that is owned by a company, but used by either an
399      * employee or client.
400      *
401      * <p>The provisioning message should be sent to an unprovisioned device.
402      *
403      * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
404      * by a privileged app with the permission
405      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
406      *
407      * <p>The provisioning intent contains the following properties:
408      * <ul>
409      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
410      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
411      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
412      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
413      * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
414      * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
415      * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
416      * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
417      * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
418      * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
419      * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
420      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
421      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
422      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
423      * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
424      * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
425      * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
426      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
427      * <li>{@link #EXTRA_PROVISIONING_USE_MOBILE_DATA}, optional </li>
428      * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional - when not used for
429      * cloud enrollment, NFC or QR provisioning</li>
430      * </ul>
431      *
432      * @hide
433      */
434     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
435     @SystemApi
436     public static final String ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
437             "android.app.action.PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
438 
439     /**
440      * Activity action: Starts the provisioning flow which sets up a financed device.
441      *
442      * <p>During financed device provisioning, a device admin app is downloaded and set as the owner
443      * of the device. A device owner has full control over the device. The device owner can not be
444      * modified by the user.
445      *
446      * <p>A typical use case would be a device that is bought from the reseller through financing
447      * program.
448      *
449      * <p>An intent with this action can be sent only on an unprovisioned device.
450      *
451      * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
452      * by a privileged app with the permission
453      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
454      *
455      * <p>The provisioning intent contains the following properties:
456      * <ul>
457      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
458      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
459      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
460      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
461      * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
462      * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
463      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
464      * </ul>
465      *
466      * @hide
467      */
468     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
469     @SystemApi
470     public static final String ACTION_PROVISION_FINANCED_DEVICE =
471             "android.app.action.PROVISION_FINANCED_DEVICE";
472 
473     /**
474      * Activity action: Finalizes management provisioning, should be used after user-setup
475      * has been completed and {@link #getUserProvisioningState()} returns one of:
476      * <ul>
477      * <li>{@link #STATE_USER_SETUP_INCOMPLETE}</li>
478      * <li>{@link #STATE_USER_SETUP_COMPLETE}</li>
479      * <li>{@link #STATE_USER_PROFILE_COMPLETE}</li>
480      * </ul>
481      *
482      * @hide
483      */
484     @SystemApi
485     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
486     public static final String ACTION_PROVISION_FINALIZATION
487             = "android.app.action.PROVISION_FINALIZATION";
488 
489     /**
490      * Action: Bugreport sharing with device owner has been accepted by the user.
491      *
492      * @hide
493      */
494     public static final String ACTION_BUGREPORT_SHARING_ACCEPTED =
495             "com.android.server.action.REMOTE_BUGREPORT_SHARING_ACCEPTED";
496 
497     /**
498      * Action: Bugreport sharing with device owner has been declined by the user.
499      *
500      * @hide
501      */
502     public static final String ACTION_BUGREPORT_SHARING_DECLINED =
503             "com.android.server.action.REMOTE_BUGREPORT_SHARING_DECLINED";
504 
505     /**
506      * Action: Bugreport has been collected and is dispatched to {@code DevicePolicyManagerService}.
507      *
508      * @hide
509      */
510     public static final String ACTION_REMOTE_BUGREPORT_DISPATCH =
511             "android.intent.action.REMOTE_BUGREPORT_DISPATCH";
512 
513     /**
514      * Extra for shared bugreport's SHA-256 hash.
515      *
516      * @hide
517      */
518     public static final String EXTRA_REMOTE_BUGREPORT_HASH =
519             "android.intent.extra.REMOTE_BUGREPORT_HASH";
520 
521     /**
522      * Extra for remote bugreport notification shown type.
523      *
524      * @hide
525      */
526     public static final String EXTRA_BUGREPORT_NOTIFICATION_TYPE =
527             "android.app.extra.bugreport_notification_type";
528 
529     /**
530      * Default value for preferential network service enabling.
531      *
532      * @hide
533      */
534     public static final boolean PREFERENTIAL_NETWORK_SERVICE_ENABLED_DEFAULT = false;
535 
536     /**
537      * Notification type for a started remote bugreport flow.
538      *
539      * @hide
540      */
541     public static final int NOTIFICATION_BUGREPORT_STARTED = 1;
542 
543     /**
544      * Notification type for a bugreport that has already been accepted to be shared, but is still
545      * being taken.
546      *
547      * @hide
548      */
549     public static final int NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED = 2;
550 
551     /**
552      * Notification type for a bugreport that has been taken and can be shared or declined.
553      *
554      * @hide
555      */
556     public static final int NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED = 3;
557 
558     /**
559      * Default and maximum timeout in milliseconds after which unlocking with weak auth times out,
560      * i.e. the user has to use a strong authentication method like password, PIN or pattern.
561      *
562      * @hide
563      */
564     public static final long DEFAULT_STRONG_AUTH_TIMEOUT_MS = 72 * 60 * 60 * 1000; // 72h
565 
566     /**
567      * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that
568      * allows a mobile device management application or NFC programmer application which starts
569      * managed provisioning to pass data to the management application instance after provisioning.
570      * <p>
571      * If used with {@link #ACTION_PROVISION_MANAGED_PROFILE} it can be used by the application that
572      * sends the intent to pass data to itself on the newly created profile.
573      * If used with {@link #ACTION_PROVISION_MANAGED_DEVICE} it allows passing data to the same
574      * instance of the app on the primary user.
575      * Starting from {@link android.os.Build.VERSION_CODES#M}, if used with
576      * {@link #MIME_TYPE_PROVISIONING_NFC} as part of NFC managed device provisioning, the NFC
577      * message should contain a stringified {@link java.util.Properties} instance, whose string
578      * properties will be converted into a {@link android.os.PersistableBundle} and passed to the
579      * management application after provisioning.
580      *
581      * <p>Admin apps will receive this extra in their {@link #ACTION_GET_PROVISIONING_MODE} and
582      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} intent handlers. Additionally, {@link
583      * #ACTION_GET_PROVISIONING_MODE} may also return this extra which will then be sent over to
584      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE}, alongside the original values that were passed to
585      * {@link #ACTION_GET_PROVISIONING_MODE}.
586      *
587      * <p>
588      * In both cases the application receives the data in
589      * {@link DeviceAdminReceiver#onProfileProvisioningComplete} via an intent with the action
590      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}. The bundle is not changed
591      * during the managed provisioning.
592      */
593     public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE =
594             "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE";
595 
596     /**
597      * A String extra holding the package name of the mobile device management application that
598      * will be set as the profile owner or device owner.
599      *
600      * <p>If an application starts provisioning directly via an intent with action
601      * {@link #ACTION_PROVISION_MANAGED_PROFILE} this package has to match the package name of the
602      * application that started provisioning. The package will be set as profile owner in that case.
603      *
604      * <p>This package is set as device owner when device owner provisioning is started by an NFC
605      * message containing an NFC record with MIME type {@link #MIME_TYPE_PROVISIONING_NFC}.
606      *
607      * <p> When this extra is set, the application must have exactly one device admin receiver.
608      * This receiver will be set as the profile or device owner and active admin.
609      *
610      * @see DeviceAdminReceiver
611      * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}. This extra is still
612      * supported, but only if there is only one device admin receiver in the package that requires
613      * the permission {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
614      */
615     @Deprecated
616     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME
617         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME";
618 
619     /**
620      * A ComponentName extra indicating the device admin receiver of the mobile device management
621      * application that will be set as the profile owner or device owner and active admin.
622      *
623      * <p>If an application starts provisioning directly via an intent with action
624      * {@link #ACTION_PROVISION_MANAGED_PROFILE} or
625      * {@link #ACTION_PROVISION_MANAGED_DEVICE} the package name of this
626      * component has to match the package name of the application that started provisioning.
627      *
628      * <p>This component is set as device owner and active admin when device owner provisioning is
629      * started by an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or by an NFC
630      * message containing an NFC record with MIME type
631      * {@link #MIME_TYPE_PROVISIONING_NFC}. For the NFC record, the component name must be
632      * flattened to a string, via {@link ComponentName#flattenToShortString()}.
633      *
634      * @see DeviceAdminReceiver
635      */
636     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME
637         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME";
638 
639     /**
640      * An {@link android.accounts.Account} extra holding the account to migrate during managed
641      * profile provisioning. If the account supplied is present in the primary user, it will be
642      * copied, along with its credentials to the managed profile and removed from the primary user.
643      *
644      * Use with {@link #ACTION_PROVISION_MANAGED_PROFILE}, with managed account provisioning, or
645      * return as an extra to the intent result from the {@link #ACTION_GET_PROVISIONING_MODE}
646      * activity.
647      */
648 
649     public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
650         = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE";
651 
652     /**
653      * Boolean extra to indicate that the migrated account should be kept. This is used in
654      * conjunction with {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}. If it's set to {@code true},
655      * the account will not be removed from the primary user after it is migrated to the newly
656      * created user or profile.
657      *
658      * <p> Defaults to {@code false}
659      *
660      * <p> Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or set as an extra to the
661      * intent result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
662      *
663      * @see #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
664      */
665     public static final String EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION
666             = "android.app.extra.PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION";
667 
668     /**
669      * @deprecated From {@link android.os.Build.VERSION_CODES#O}, never used while provisioning the
670      * device.
671      */
672     @Deprecated
673     public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
674         = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
675 
676     /**
677      * A integer extra indicating the predominant color to show during the provisioning.
678      * Refer to {@link android.graphics.Color} for how the color is represented.
679      *
680      * <p>Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or
681      * {@link #ACTION_PROVISION_MANAGED_DEVICE}.
682      *
683      * @deprecated Color customization is no longer supported in the provisioning flow.
684      */
685     @Deprecated
686     public static final String EXTRA_PROVISIONING_MAIN_COLOR =
687              "android.app.extra.PROVISIONING_MAIN_COLOR";
688 
689     /**
690      * A Boolean extra that can be used by the mobile device management application to skip the
691      * disabling of system apps during provisioning when set to {@code true}.
692      *
693      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC}, an intent with action
694      * {@link #ACTION_PROVISION_MANAGED_PROFILE} that starts profile owner provisioning or
695      * set as an extra to the intent result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
696      */
697     public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED =
698             "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED";
699 
700     /**
701      * A String extra holding the time zone {@link android.app.AlarmManager} that the device
702      * will be set to.
703      *
704      * <p>Use only for device owner provisioning. This extra can be returned by the admin app when
705      * performing the admin-integrated provisioning flow as a result of the {@link
706      * #ACTION_GET_PROVISIONING_MODE} activity.
707      */
708     public static final String EXTRA_PROVISIONING_TIME_ZONE
709         = "android.app.extra.PROVISIONING_TIME_ZONE";
710 
711     /**
712      * A Long extra holding the wall clock time (in milliseconds) to be set on the device's
713      * {@link android.app.AlarmManager}.
714      *
715      * <p>Use only for device owner provisioning. This extra can be returned by the admin app when
716      * performing the admin-integrated provisioning flow as a result of the {@link
717      * #ACTION_GET_PROVISIONING_MODE} activity.
718      */
719     public static final String EXTRA_PROVISIONING_LOCAL_TIME
720         = "android.app.extra.PROVISIONING_LOCAL_TIME";
721 
722     /**
723      * A String extra holding the {@link java.util.Locale} that the device will be set to.
724      * Format: xx_yy, where xx is the language code, and yy the country code.
725      *
726      * <p>Use only for device owner provisioning. This extra can be returned by the admin app when
727      * performing the admin-integrated provisioning flow as a result of the {@link
728      * #ACTION_GET_PROVISIONING_MODE} activity.
729      */
730     public static final String EXTRA_PROVISIONING_LOCALE
731         = "android.app.extra.PROVISIONING_LOCALE";
732 
733     /**
734      * A String extra holding the ssid of the wifi network that should be used during nfc device
735      * owner provisioning for downloading the mobile device management application.
736      *
737      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
738      * provisioning via an NFC bump.
739      */
740     public static final String EXTRA_PROVISIONING_WIFI_SSID
741         = "android.app.extra.PROVISIONING_WIFI_SSID";
742 
743     /**
744      * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
745      * is hidden or not.
746      *
747      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
748      * provisioning via an NFC bump.
749      */
750     public static final String EXTRA_PROVISIONING_WIFI_HIDDEN
751         = "android.app.extra.PROVISIONING_WIFI_HIDDEN";
752 
753     /**
754      * A String extra indicating the security type of the wifi network in
755      * {@link #EXTRA_PROVISIONING_WIFI_SSID} and could be one of {@code NONE}, {@code WPA},
756      * {@code WEP} or {@code EAP}.
757      *
758      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
759      * provisioning via an NFC bump.
760      */
761     public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE
762         = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE";
763 
764     /**
765      * A String extra holding the password of the wifi network in
766      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
767      *
768      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
769      * provisioning via an NFC bump.
770      */
771     public static final String EXTRA_PROVISIONING_WIFI_PASSWORD =
772             "android.app.extra.PROVISIONING_WIFI_PASSWORD";
773 
774     /**
775      * The EAP method of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
776      * and could be one of {@code PEAP}, {@code TLS}, {@code TTLS}, {@code PWD}, {@code SIM},
777      * {@code AKA} or {@code AKA_PRIME}. This is only used if the
778      * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
779      *
780      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
781      * provisioning via an NFC bump. It can also be used for QR code provisioning.
782      */
783     public static final String EXTRA_PROVISIONING_WIFI_EAP_METHOD =
784             "android.app.extra.PROVISIONING_WIFI_EAP_METHOD";
785 
786     /**
787      * The phase 2 authentication of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
788      * and could be one of {@code NONE}, {@code PAP}, {@code MSCHAP}, {@code MSCHAPV2}, {@code GTC},
789      * {@code SIM}, {@code AKA} or {@code AKA_PRIME}. This is only used if the
790      * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
791      *
792      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
793      * provisioning via an NFC bump. It can also be used for QR code provisioning.
794      */
795     public static final String EXTRA_PROVISIONING_WIFI_PHASE2_AUTH =
796             "android.app.extra.PROVISIONING_WIFI_PHASE2_AUTH";
797 
798     /**
799      * The CA certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This should
800      * be an X.509 certificate Base64 encoded DER format, ie. PEM representation of a certificate
801      * without header, footer and line breaks. <a href=
802      * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only
803      * used if the {@link
804      * #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
805      *
806      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
807      * provisioning via an NFC bump. It can also be used for QR code provisioning.
808      */
809     public static final String EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE =
810             "android.app.extra.PROVISIONING_WIFI_CA_CERTIFICATE";
811 
812     /**
813      * The user certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This
814      * should be an X.509 certificate and private key Base64 encoded DER format, ie. PEM
815      * representation of a certificate and key without header, footer and line breaks. <a href=
816      * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only
817      * used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
818      *
819      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
820      * provisioning via an NFC bump. It can also be used for QR code provisioning.
821      */
822     public static final String EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE =
823             "android.app.extra.PROVISIONING_WIFI_USER_CERTIFICATE";
824 
825     /**
826      * The identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used
827      * if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
828      *
829      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
830      * provisioning via an NFC bump. It can also be used for QR code provisioning.
831      */
832     public static final String EXTRA_PROVISIONING_WIFI_IDENTITY =
833             "android.app.extra.PROVISIONING_WIFI_IDENTITY";
834 
835     /**
836      * The anonymous identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is
837      * only used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
838      *
839      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
840      * provisioning via an NFC bump. It can also be used for QR code provisioning.
841      */
842 
843     public static final String EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY =
844             "android.app.extra.PROVISIONING_WIFI_ANONYMOUS_IDENTITY";
845     /**
846      * The domain of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used if
847      * the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
848      *
849      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
850      * provisioning via an NFC bump. It can also be used for QR code provisioning.
851      */
852     public static final String EXTRA_PROVISIONING_WIFI_DOMAIN =
853             "android.app.extra.PROVISIONING_WIFI_DOMAIN";
854 
855     /**
856      * A String extra holding the proxy host for the wifi network in
857      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
858      *
859      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
860      * provisioning via an NFC bump.
861      */
862     public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST
863         = "android.app.extra.PROVISIONING_WIFI_PROXY_HOST";
864 
865     /**
866      * An int extra holding the proxy port for the wifi network in
867      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
868      *
869      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
870      * provisioning via an NFC bump.
871      */
872     public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT
873         = "android.app.extra.PROVISIONING_WIFI_PROXY_PORT";
874 
875     /**
876      * A String extra holding the proxy bypass for the wifi network in
877      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
878      *
879      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
880      * provisioning via an NFC bump.
881      */
882     public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS
883         = "android.app.extra.PROVISIONING_WIFI_PROXY_BYPASS";
884 
885     /**
886      * A String extra holding the proxy auto-config (PAC) URL for the wifi network in
887      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
888      *
889      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
890      * provisioning via an NFC bump.
891      */
892     public static final String EXTRA_PROVISIONING_WIFI_PAC_URL
893         = "android.app.extra.PROVISIONING_WIFI_PAC_URL";
894 
895     /**
896      * A String extra holding a url that specifies the download location of the device admin
897      * package. When not provided it is assumed that the device admin package is already installed.
898      *
899      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
900      * provisioning via an NFC bump.
901      */
902     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION
903         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION";
904 
905     /**
906      * A String extra holding the localized name of the organization under management.
907      *
908      * The name is displayed only during provisioning.
909      *
910      * <p>Use in an intent with action {@link #ACTION_PROVISION_FINANCED_DEVICE}
911      *
912      * @hide
913      */
914     @SystemApi
915     public static final String EXTRA_PROVISIONING_ORGANIZATION_NAME =
916             "android.app.extra.PROVISIONING_ORGANIZATION_NAME";
917 
918     /**
919      * A String extra holding a url to the website of the device provider so the user can open it
920      * during provisioning. If the url is not HTTPS, an error will be shown.
921      *
922      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
923      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
924      *
925      * @hide
926      */
927     @SystemApi
928     public static final String EXTRA_PROVISIONING_SUPPORT_URL =
929             "android.app.extra.PROVISIONING_SUPPORT_URL";
930 
931     /**
932      * A String extra holding the localized name of the device admin package. It should be the same
933      * as the app label of the package.
934      *
935      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
936      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
937      *
938      * @deprecated This extra is no longer respected in the provisioning flow.
939      * @hide
940      */
941     @Deprecated
942     @SystemApi
943     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL =
944             "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL";
945 
946     /**
947      * A {@link Uri} extra pointing to the app icon of device admin package. This image will be
948      * shown during the provisioning.
949      * <h5>The following URI schemes are accepted:</h5>
950      * <ul>
951      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
952      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
953      * </ul>
954      *
955      * <p> It is the responsibility of the caller to provide an image with a reasonable
956      * pixel density for the device.
957      *
958      * <p> If a content: URI is passed, the intent should have the flag
959      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
960      * {@link android.content.ClipData} of the intent too.
961      *
962      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
963      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
964      *
965      * @deprecated This extra is no longer respected in the provisioning flow.
966      * @hide
967      */
968     @SystemApi
969     @Deprecated
970     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI =
971             "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI";
972 
973     /**
974      * An int extra holding a minimum required version code for the device admin package. If the
975      * device admin is already installed on the device, it will only be re-downloaded from
976      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION} if the version of the
977      * installed package is less than this version code.
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     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE
983         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE";
984 
985     /**
986      * A String extra holding a http cookie header which should be used in the http request to the
987      * url specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
988      *
989      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
990      * provisioning via an NFC bump.
991      */
992     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER
993         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER";
994 
995     /**
996      * A String extra holding the URL-safe base64 encoded SHA-256 hash of the file at download
997      * location specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
998      *
999      * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM} must be
1000      * present. The provided checksum must match the checksum of the file at the download
1001      * location. If the checksum doesn't match an error will be shown to the user and the user will
1002      * be asked to factory reset the device.
1003      *
1004      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1005      * provisioning via an NFC bump.
1006      *
1007      * <p><strong>Note:</strong> for devices running {@link android.os.Build.VERSION_CODES#LOLLIPOP}
1008      * and {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} only SHA-1 hash is supported.
1009      * Starting from {@link android.os.Build.VERSION_CODES#M}, this parameter accepts SHA-256 in
1010      * addition to SHA-1. From {@link android.os.Build.VERSION_CODES#Q}, only SHA-256 hash is
1011      * supported.
1012      */
1013     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM
1014         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM";
1015 
1016     /**
1017      * A boolean extra indicating the admin of a fully-managed device opts out of controlling
1018      * permission grants for sensor-related permissions,
1019      * see {@link #setPermissionGrantState(ComponentName, String, String, int)}.
1020      *
1021      * The default for this extra is {@code false} - by default, the admin of a fully-managed
1022      * device has the ability to grant sensors-related permissions.
1023      *
1024      * <p>Use only for device owner provisioning. This extra can be returned by the
1025      * admin app when performing the admin-integrated provisioning flow as a result of the
1026      * {@link #ACTION_GET_PROVISIONING_MODE} activity.
1027      *
1028      * @see #ACTION_GET_PROVISIONING_MODE
1029      */
1030     public static final String EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT =
1031             "android.app.extra.PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT";
1032 
1033     /**
1034      * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
1035      * android package archive at the download location specified in {@link
1036      * #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
1037      *
1038      * <p>The signatures of an android package archive can be obtained using
1039      * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
1040      * {@link android.content.pm.PackageManager#GET_SIGNATURES}.
1041      *
1042      * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM} must be
1043      * present. The provided checksum must match the checksum of any signature of the file at
1044      * the download location. If the checksum does not match an error will be shown to the user and
1045      * the user will be asked to factory reset the device.
1046      *
1047      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1048      * provisioning via an NFC bump.
1049      */
1050     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM
1051         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM";
1052 
1053     /**
1054      * Broadcast Action: This broadcast is sent to indicate that provisioning of a managed profile
1055      * has completed successfully.
1056      *
1057      * <p>The broadcast is limited to the primary profile, to the app specified in the provisioning
1058      * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
1059      *
1060      * <p>This intent will contain the following extras
1061      * <ul>
1062      * <li>{@link Intent#EXTRA_USER}, corresponds to the {@link UserHandle} of the managed
1063      * profile.</li>
1064      * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, corresponds to the account requested to
1065      * be migrated at provisioning time, if any.</li>
1066      * </ul>
1067      */
1068     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1069     public static final String ACTION_MANAGED_PROFILE_PROVISIONED
1070         = "android.app.action.MANAGED_PROFILE_PROVISIONED";
1071 
1072     /**
1073      * Activity action: This activity action is sent to indicate that provisioning of a managed
1074      * profile or managed device has completed successfully. It'll be sent at the same time as
1075      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast but this will be
1076      * delivered faster as it's an activity intent.
1077      *
1078      * <p>The intent is only sent to the new device or profile owner.
1079      *
1080      * @see #ACTION_PROVISION_MANAGED_PROFILE
1081      * @see #ACTION_PROVISION_MANAGED_DEVICE
1082      */
1083     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1084     public static final String ACTION_PROVISIONING_SUCCESSFUL =
1085             "android.app.action.PROVISIONING_SUCCESSFUL";
1086 
1087     /**
1088      * A boolean extra indicating whether device encryption can be skipped as part of device owner
1089      * or managed profile provisioning.
1090      *
1091      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
1092      * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
1093      *
1094      * <p>From {@link android.os.Build.VERSION_CODES#N} onwards, this is also supported for an
1095      * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
1096      *
1097      * <p>This extra can also be returned by the admin app when performing the admin-integrated
1098      * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
1099      */
1100     public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION =
1101              "android.app.extra.PROVISIONING_SKIP_ENCRYPTION";
1102 
1103     /**
1104      * A {@link Uri} extra pointing to a logo image. This image will be shown during the
1105      * provisioning. If this extra is not passed, a default image will be shown.
1106      * <h5>The following URI schemes are accepted:</h5>
1107      * <ul>
1108      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1109      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1110      * </ul>
1111      *
1112      * <p> It is the responsibility of the caller to provide an image with a reasonable
1113      * pixel density for the device.
1114      *
1115      * <p> If a content: URI is passed, the intent should have the flag
1116      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1117      * {@link android.content.ClipData} of the intent too.
1118      *
1119      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1120      * {@link #ACTION_PROVISION_MANAGED_DEVICE}
1121      */
1122     public static final String EXTRA_PROVISIONING_LOGO_URI =
1123             "android.app.extra.PROVISIONING_LOGO_URI";
1124 
1125     /**
1126      * A {@link Bundle}[] extra consisting of list of disclaimer headers and disclaimer contents.
1127      * Each {@link Bundle} must have both {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}
1128      * as disclaimer header, and {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} as disclaimer
1129      * content.
1130      *
1131      * <p> The extra typically contains one disclaimer from the company of mobile device
1132      * management application (MDM), and one disclaimer from the organization.
1133      *
1134      * <p> Call {@link Bundle#putParcelableArray(String, Parcelable[])} to put the {@link Bundle}[]
1135      *
1136      * <p> Maximum 3 key-value pairs can be specified. The rest will be ignored.
1137      *
1138      * <p> Can be used in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}. This
1139      * extra can also be returned by the admin app when performing the admin-integrated
1140      * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
1141      */
1142     public static final String EXTRA_PROVISIONING_DISCLAIMERS =
1143             "android.app.extra.PROVISIONING_DISCLAIMERS";
1144 
1145     /**
1146      * A String extra of localized disclaimer header.
1147      *
1148      * <p> The extra is typically the company name of mobile device management application (MDM)
1149      * or the organization name.
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_CONTENT}. Here is the example:
1156      *
1157      * <pre>
1158      *  &lt;meta-data
1159      *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_HEADER"
1160      *      android:resource="@string/disclaimer_header"
1161      * /&gt;</pre>
1162      */
1163     public static final String EXTRA_PROVISIONING_DISCLAIMER_HEADER =
1164             "android.app.extra.PROVISIONING_DISCLAIMER_HEADER";
1165 
1166     /**
1167      * A {@link Uri} extra pointing to disclaimer content.
1168      *
1169      * <h5>The following URI schemes are accepted:</h5>
1170      * <ul>
1171      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1172      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1173      * </ul>
1174      *
1175      * <p> Styled text is supported in the disclaimer content. The content is parsed by
1176      * {@link android.text.Html#fromHtml(String)} and displayed in a
1177      * {@link android.widget.TextView}.
1178      *
1179      * <p> If a <code>content:</code> URI is passed, URI is passed, the intent should have the flag
1180      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1181      * {@link android.content.ClipData} of the intent too.
1182      *
1183      * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
1184      *
1185      * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
1186      * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
1187      * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}. Here is the example:
1188      *
1189      * <pre>
1190      *  &lt;meta-data
1191      *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_CONTENT"
1192      *      android:resource="@string/disclaimer_content"
1193      * /&gt;</pre>
1194      */
1195     public static final String EXTRA_PROVISIONING_DISCLAIMER_CONTENT =
1196             "android.app.extra.PROVISIONING_DISCLAIMER_CONTENT";
1197 
1198     /**
1199      * A boolean extra indicating if the user consent steps from the provisioning flow should be
1200      * skipped. If unspecified, defaults to {@code false}.
1201      *
1202      * It can only be used by an existing device owner trying to create a managed profile via
1203      * {@link #ACTION_PROVISION_MANAGED_PROFILE}. Otherwise it is ignored.
1204      *
1205      * @deprecated this extra is no longer relevant as device owners cannot create managed profiles
1206      */
1207     @Deprecated
1208     public static final String EXTRA_PROVISIONING_SKIP_USER_CONSENT =
1209             "android.app.extra.PROVISIONING_SKIP_USER_CONSENT";
1210 
1211     /**
1212      * A boolean extra indicating if the education screens from the provisioning flow should be
1213      * skipped. If unspecified, defaults to {@code false}.
1214      *
1215      * <p>This extra can be set in the following ways:
1216      * <ul>
1217      * <li>By the admin app when performing the admin-integrated
1218      * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity</li>
1219      * <li>For managed account enrollment</li>
1220      * </ul>
1221      *
1222      * <p>If the education screens are skipped, it is the admin application's responsibility
1223      * to display its own user education screens.
1224      */
1225     public static final String EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS =
1226             "android.app.extra.PROVISIONING_SKIP_EDUCATION_SCREENS";
1227 
1228     /**
1229      * A boolean extra indicating if mobile data should be used during NFC device owner provisioning
1230      * for downloading the mobile device management application. If {@link
1231      * #EXTRA_PROVISIONING_WIFI_SSID} is also specified, wifi network will be used instead.
1232      *
1233      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1234      * provisioning via an NFC bump.
1235      *
1236      * @hide
1237      */
1238     public static final String EXTRA_PROVISIONING_USE_MOBILE_DATA =
1239             "android.app.extra.PROVISIONING_USE_MOBILE_DATA";
1240 
1241     /**
1242      * Possible values for {@link #EXTRA_PROVISIONING_TRIGGER}.
1243      *
1244      * @hide
1245      */
1246     @IntDef(prefix = { "PROVISIONING_TRIGGER_" }, value = {
1247             PROVISIONING_TRIGGER_UNSPECIFIED,
1248             PROVISIONING_TRIGGER_CLOUD_ENROLLMENT,
1249             PROVISIONING_TRIGGER_QR_CODE,
1250             PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER,
1251             PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1252     })
1253     @Retention(RetentionPolicy.SOURCE)
1254     public @interface ProvisioningTrigger {}
1255 
1256     /**
1257      * Flags for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES}.
1258      *
1259      * @hide
1260      */
1261     @IntDef(flag = true, prefix = { "FLAG_SUPPORTED_MODES_" }, value = {
1262             FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED,
1263             FLAG_SUPPORTED_MODES_PERSONALLY_OWNED,
1264             FLAG_SUPPORTED_MODES_DEVICE_OWNER
1265     })
1266     @Retention(RetentionPolicy.SOURCE)
1267     public @interface ProvisioningConfiguration {}
1268 
1269     /**
1270      * A String extra holding the provisioning trigger. It could be one of
1271      * {@link #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT}, {@link #PROVISIONING_TRIGGER_QR_CODE},
1272      * {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} or {@link
1273      * #PROVISIONING_TRIGGER_UNSPECIFIED}.
1274      *
1275      * <p>Use in an intent with action {@link
1276      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}.
1277      * @hide
1278      */
1279     @SystemApi
1280     public static final String EXTRA_PROVISIONING_TRIGGER =
1281             "android.app.extra.PROVISIONING_TRIGGER";
1282 
1283     /**
1284      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1285      * trigger has not been specified.
1286      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1287      * @see #PROVISIONING_TRIGGER_QR_CODE
1288      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1289      * @hide
1290      */
1291     @SystemApi
1292     public static final int PROVISIONING_TRIGGER_UNSPECIFIED = 0;
1293 
1294     /**
1295      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1296      * trigger is cloud enrollment.
1297      * @see #PROVISIONING_TRIGGER_QR_CODE
1298      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1299      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1300      * @hide
1301      */
1302     @SystemApi
1303     public static final int PROVISIONING_TRIGGER_CLOUD_ENROLLMENT = 1;
1304 
1305     /**
1306      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1307      * trigger is the QR code scanner.
1308      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1309      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1310      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1311      * @hide
1312      */
1313     @SystemApi
1314     public static final int PROVISIONING_TRIGGER_QR_CODE = 2;
1315 
1316     /**
1317      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1318      * trigger is persistent device owner enrollment.
1319      * <p>This constant is meant to represent a specific type of managed account provisioning which
1320      * provisions a device to a device owner by invoking the standard provisioning flow (where
1321      * the ManagedProvisioning component downloads and installs the admin app), as opposed to
1322      * relying on the provisioning trigger to handle download and install of the admin app.
1323      * <p>As of {@link android.os.Build.VERSION_CODES#S}, this constant is no longer used in favor
1324      * of the more general {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} which handles all managed
1325      * account provisioning types.
1326      * @deprecated Use the broader {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} instead
1327      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1328      * @see #PROVISIONING_TRIGGER_QR_CODE
1329      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1330      * @hide
1331      */
1332     @SystemApi
1333     @Deprecated
1334     public static final int PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER = 3;
1335 
1336     /**
1337      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1338      * trigger is managed account enrollment.
1339      * <p>
1340      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1341      * @see #PROVISIONING_TRIGGER_QR_CODE
1342      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1343      * @hide
1344      */
1345     @SystemApi
1346     public static final int PROVISIONING_TRIGGER_MANAGED_ACCOUNT = 4;
1347 
1348     /**
1349      * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that provisioning is
1350      * organization-owned.
1351      *
1352      * <p>Using this value indicates the admin app can only be provisioned in either a
1353      * fully-managed device or a corporate-owned work profile. This will cause the admin app's
1354      * {@link #ACTION_GET_PROVISIONING_MODE} activity to have the {@link
1355      * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
1356      * #PROVISIONING_MODE_MANAGED_PROFILE} and {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}.
1357      *
1358      * <p>Also, if this flag is set, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity
1359      * will not receive the {@link #EXTRA_PROVISIONING_IMEI} and {@link
1360      * #EXTRA_PROVISIONING_SERIAL_NUMBER} extras.
1361      *
1362      * <p>This flag can be combined with {@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}. In
1363      * that case, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity will have
1364      * the {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
1365      * #PROVISIONING_MODE_MANAGED_PROFILE}, {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE} and
1366      * {@link #PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE}.
1367      *
1368      * @hide
1369      */
1370     @SystemApi
1371     public static final int FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED = 1;
1372 
1373     /**
1374      * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that provisioning
1375      * is personally-owned.
1376      *
1377      * <p>Using this flag will cause the admin app's {@link #ACTION_GET_PROVISIONING_MODE}
1378      * activity to have the {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra
1379      * contain only {@link #PROVISIONING_MODE_MANAGED_PROFILE}.
1380      *
1381      * <p>This flag can be combined with {@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}. In
1382      * that case, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity will have the
1383      * {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
1384      * #PROVISIONING_MODE_MANAGED_PROFILE}, {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE} and
1385      * {@link #PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE}.
1386      *
1387      * @hide
1388      */
1389     @SystemApi
1390     public static final int FLAG_SUPPORTED_MODES_PERSONALLY_OWNED = 1 << 1;
1391 
1392     /**
1393      * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that the only
1394      * supported provisioning mode is device owner.
1395      *
1396      * @hide
1397      */
1398     @SystemApi
1399     public static final int FLAG_SUPPORTED_MODES_DEVICE_OWNER = 1 << 2;
1400 
1401     /**
1402      * This MIME type is used for starting the device owner provisioning.
1403      *
1404      * <p>During device owner provisioning a device admin app is set as the owner of the device.
1405      * A device owner has full control over the device. The device owner can not be modified by the
1406      * user and the only way of resetting the device is if the device owner app calls a factory
1407      * reset.
1408      *
1409      * <p> A typical use case would be a device that is owned by a company, but used by either an
1410      * employee or client.
1411      *
1412      * <p> The NFC message must be sent to an unprovisioned device.
1413      *
1414      * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
1415      * contains the following properties:
1416      * <ul>
1417      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
1418      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
1419      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
1420      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
1421      * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
1422      * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
1423      * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
1424      * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
1425      * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
1426      * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
1427      * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
1428      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
1429      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
1430      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
1431      * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
1432      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional, supported from {@link
1433      * android.os.Build.VERSION_CODES#M} </li>
1434      * <li>{@link #EXTRA_PROVISIONING_WIFI_EAP_METHOD}, optional, supported from {@link
1435      * android.os.Build.VERSION_CODES#Q}</li>
1436      * <li>{@link #EXTRA_PROVISIONING_WIFI_PHASE2_AUTH}, optional, supported from {@link
1437      * android.os.Build.VERSION_CODES#Q}</li>
1438      * <li>{@link #EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE}, optional, supported from {@link
1439      * android.os.Build.VERSION_CODES#Q}</li>
1440      * <li>{@link #EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE}, optional, supported from {@link
1441      * android.os.Build.VERSION_CODES#Q}</li>
1442      * <li>{@link #EXTRA_PROVISIONING_WIFI_IDENTITY}, optional, supported from {@link
1443      * android.os.Build.VERSION_CODES#Q}</li>
1444      * <li>{@link #EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY}, optional, supported from {@link
1445      * android.os.Build.VERSION_CODES#Q}</li>
1446      * <li>{@link #EXTRA_PROVISIONING_WIFI_DOMAIN}, optional, supported from {@link
1447      * android.os.Build.VERSION_CODES#Q}</li></ul>
1448      *
1449      * <p>
1450      * As of {@link android.os.Build.VERSION_CODES#M}, the properties should contain
1451      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of
1452      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only
1453      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported).
1454      */
1455     public static final String MIME_TYPE_PROVISIONING_NFC
1456         = "application/com.android.managedprovisioning";
1457 
1458     /**
1459      * Activity action: ask the user to add a new device administrator to the system.
1460      * The desired policy is the ComponentName of the policy in the
1461      * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
1462      * bring the user through adding the device administrator to the system (or
1463      * allowing them to reject it).
1464      *
1465      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1466      * field to provide the user with additional explanation (in addition
1467      * to your component's description) about what is being added.
1468      *
1469      * <p>If your administrator is already active, this will ordinarily return immediately (without
1470      * user intervention).  However, if your administrator has been updated and is requesting
1471      * additional uses-policy flags, the user will be presented with the new list.  New policies
1472      * will not be available to the updated administrator until the user has accepted the new list.
1473      */
1474     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1475     public static final String ACTION_ADD_DEVICE_ADMIN
1476             = "android.app.action.ADD_DEVICE_ADMIN";
1477 
1478     /**
1479      * @hide
1480      * Activity action: ask the user to add a new device administrator as the profile owner
1481      * for this user. Only system apps can launch this intent.
1482      *
1483      * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN}
1484      * extra field. This will invoke a UI to bring the user through adding the profile owner admin
1485      * to remotely control restrictions on the user.
1486      *
1487      * <p>The intent must be invoked via {@link Activity#startActivityForResult} to receive the
1488      * result of whether or not the user approved the action. If approved, the result will
1489      * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well
1490      * as a profile owner.
1491      *
1492      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1493      * field to provide the user with additional explanation (in addition
1494      * to your component's description) about what is being added.
1495      *
1496      * <p>If there is already a profile owner active or the caller is not a system app, the
1497      * operation will return a failure result.
1498      */
1499     @SystemApi
1500     public static final String ACTION_SET_PROFILE_OWNER
1501             = "android.app.action.SET_PROFILE_OWNER";
1502 
1503     /**
1504      * @hide
1505      * Name of the profile owner admin that controls the user.
1506      */
1507     @SystemApi
1508     public static final String EXTRA_PROFILE_OWNER_NAME
1509             = "android.app.extra.PROFILE_OWNER_NAME";
1510 
1511     /**
1512      * Broadcast action: send when any policy admin changes a policy.
1513      * This is generally used to find out when a new policy is in effect.
1514      *
1515      * If the profile owner of an organization-owned managed profile changes some user
1516      * restriction explicitly on the parent user, this broadcast will <em>not</em> be
1517      * sent to the parent user.
1518      * @hide
1519      */
1520     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1521     public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
1522             = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
1523 
1524     /**
1525      * Broadcast action: sent when the device owner is set, changed or cleared.
1526      *
1527      * This broadcast is sent only to the primary user.
1528      * @see #ACTION_PROVISION_MANAGED_DEVICE
1529      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
1530      */
1531     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1532     public static final String ACTION_DEVICE_OWNER_CHANGED
1533             = "android.app.action.DEVICE_OWNER_CHANGED";
1534 
1535     /**
1536      * Broadcast action: sent when the factory reset protection (FRP) policy is changed.
1537      *
1538      * @see #setFactoryResetProtectionPolicy
1539      * @hide
1540      */
1541     @RequiresPermission(android.Manifest.permission.MANAGE_FACTORY_RESET_PROTECTION)
1542     @SystemApi
1543     public static final String ACTION_RESET_PROTECTION_POLICY_CHANGED =
1544             "android.app.action.RESET_PROTECTION_POLICY_CHANGED";
1545 
1546     /**
1547      * The ComponentName of the administrator component.
1548      *
1549      * @see #ACTION_ADD_DEVICE_ADMIN
1550      */
1551     public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
1552 
1553     /**
1554      * An optional CharSequence providing additional explanation for why the
1555      * admin is being added.
1556      *
1557      * @see #ACTION_ADD_DEVICE_ADMIN
1558      */
1559     public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
1560 
1561     /**
1562      * Constant to indicate the feature of disabling the camera. Used as argument to
1563      * {@link #createAdminSupportIntent(String)}.
1564      * @see #setCameraDisabled(ComponentName, boolean)
1565      */
1566     public static final String POLICY_DISABLE_CAMERA = "policy_disable_camera";
1567 
1568     /**
1569      * Constant to indicate the feature of disabling screen captures. Used as argument to
1570      * {@link #createAdminSupportIntent(String)}.
1571      * @see #setScreenCaptureDisabled(ComponentName, boolean)
1572      */
1573     public static final String POLICY_DISABLE_SCREEN_CAPTURE = "policy_disable_screen_capture";
1574 
1575     /**
1576      * Constant to indicate the feature of suspending app. Use it as the value of
1577      * {@link #EXTRA_RESTRICTION}.
1578      * @hide
1579      */
1580     public static final String POLICY_SUSPEND_PACKAGES = "policy_suspend_packages";
1581 
1582     /**
1583      * A String indicating a specific restricted feature. Can be a user restriction from the
1584      * {@link UserManager}, e.g. {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the values
1585      * {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
1586      * @see #createAdminSupportIntent(String)
1587      * @hide
1588      */
1589     @SystemApi
1590     public static final String EXTRA_RESTRICTION = "android.app.extra.RESTRICTION";
1591 
1592     /**
1593      * Activity action: have the user enter a new password.
1594      *
1595      * <p>For admin apps, this activity should be launched after using {@link
1596      * #setPasswordQuality(ComponentName, int)}, or {@link
1597      * #setPasswordMinimumLength(ComponentName, int)} to have the user enter a new password that
1598      * meets the current requirements. You can use {@link #isActivePasswordSufficient()} to
1599      * determine whether you need to have the user select a new password in order to meet the
1600      * current constraints. Upon being resumed from this activity, you can check the new
1601      * password characteristics to see if they are sufficient.
1602      *
1603      * <p>Non-admin apps can use {@link #getPasswordComplexity()} to check the current screen lock
1604      * complexity, and use this activity with extra {@link #EXTRA_PASSWORD_COMPLEXITY} to suggest
1605      * to users how complex the app wants the new screen lock to be. Note that both {@link
1606      * #getPasswordComplexity()} and the extra {@link #EXTRA_PASSWORD_COMPLEXITY} require the
1607      * calling app to have the permission {@link permission#REQUEST_PASSWORD_COMPLEXITY}.
1608      *
1609      * <p>If the intent is launched from within a managed profile with a profile
1610      * owner built against {@link android.os.Build.VERSION_CODES#M} or before,
1611      * this will trigger entering a new password for the parent of the profile.
1612      * For all other cases it will trigger entering a new password for the user
1613      * or profile it is launched from.
1614      *
1615      * @see #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1616      */
1617     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1618     public static final String ACTION_SET_NEW_PASSWORD
1619             = "android.app.action.SET_NEW_PASSWORD";
1620 
1621     /**
1622      * An integer indicating the complexity level of the new password an app would like the user to
1623      * set when launching the action {@link #ACTION_SET_NEW_PASSWORD}.
1624      *
1625      * <p>Must be one of
1626      * <ul>
1627      *     <li>{@link #PASSWORD_COMPLEXITY_HIGH}
1628      *     <li>{@link #PASSWORD_COMPLEXITY_MEDIUM}
1629      *     <li>{@link #PASSWORD_COMPLEXITY_LOW}
1630      *     <li>{@link #PASSWORD_COMPLEXITY_NONE}
1631      * </ul>
1632      *
1633      * <p>If an invalid value is used, it will be treated as {@link #PASSWORD_COMPLEXITY_NONE}.
1634      */
1635     @RequiresPermission(android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY)
1636     public static final String EXTRA_PASSWORD_COMPLEXITY =
1637             "android.app.extra.PASSWORD_COMPLEXITY";
1638 
1639     /**
1640      * Constant for {@link #getPasswordComplexity()} and
1641      * {@link #setRequiredPasswordComplexity(int)}: no password.
1642      *
1643      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
1644      * the exact complexity band the password is in.
1645      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
1646      * band which the password must meet.
1647      */
1648     public static final int PASSWORD_COMPLEXITY_NONE = 0;
1649 
1650     /**
1651      * Constant for {@link #getPasswordComplexity()} and
1652      * {@link #setRequiredPasswordComplexity(int)}.
1653      * Define the low password complexity band as:
1654      * <ul>
1655      * <li>pattern
1656      * <li>PIN with repeating (4444) or ordered (1234, 4321, 2468) sequences
1657      * </ul>
1658      *
1659      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
1660      * the exact complexity band the password is in.
1661      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
1662      * band which the password must meet.
1663      *
1664      * @see #PASSWORD_QUALITY_SOMETHING
1665      * @see #PASSWORD_QUALITY_NUMERIC
1666      */
1667     public static final int PASSWORD_COMPLEXITY_LOW = 0x10000;
1668 
1669     /**
1670      * Constant for {@link #getPasswordComplexity()} and
1671      * {@link #setRequiredPasswordComplexity(int)}.
1672      * Define the medium password complexity band as:
1673      * <ul>
1674      * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
1675      * least 4
1676      * <li>alphabetic, length at least 4
1677      * <li>alphanumeric, length at least 4
1678      * </ul>
1679      *
1680      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
1681      * the exact complexity band the password is in.
1682      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
1683      * band which the password must meet.
1684      *
1685      * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX
1686      * @see #PASSWORD_QUALITY_ALPHABETIC
1687      * @see #PASSWORD_QUALITY_ALPHANUMERIC
1688      */
1689     public static final int PASSWORD_COMPLEXITY_MEDIUM = 0x30000;
1690 
1691     /**
1692      * Constant for {@link #getPasswordComplexity()} and
1693      * {@link #setRequiredPasswordComplexity(int)}.
1694      * Define the high password complexity band as:
1695      * <ul>
1696      * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
1697      * least 8
1698      * <li>alphabetic, length at least 6
1699      * <li>alphanumeric, length at least 6
1700      * </ul>
1701      *
1702      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
1703      * the exact complexity band the password is in.
1704      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
1705      * band which the password must meet.
1706      *
1707      * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX
1708      * @see #PASSWORD_QUALITY_ALPHABETIC
1709      * @see #PASSWORD_QUALITY_ALPHANUMERIC
1710      */
1711     public static final int PASSWORD_COMPLEXITY_HIGH = 0x50000;
1712 
1713     /**
1714      * A boolean extra for {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} requesting that only
1715      * device password requirement is enforced during the parent profile password enrolment flow.
1716      * <p> Normally when enrolling password for the parent profile, both the device-wide password
1717      * requirement (requirement set via {@link #getParentProfileInstance(ComponentName)} instance)
1718      * and the profile password requirement are enforced, if the profile currently does not have a
1719      * separate work challenge. By setting this to {@code true}, profile password requirement is
1720      * explicitly disregarded.
1721      *
1722      * @see #isActivePasswordSufficientForDeviceRequirement()
1723      */
1724     public static final String EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY =
1725             "android.app.extra.DEVICE_PASSWORD_REQUIREMENT_ONLY";
1726 
1727     /**
1728      * @hide
1729      */
1730     @Retention(RetentionPolicy.SOURCE)
1731     @IntDef(prefix = {"PASSWORD_COMPLEXITY_"}, value = {
1732             PASSWORD_COMPLEXITY_NONE,
1733             PASSWORD_COMPLEXITY_LOW,
1734             PASSWORD_COMPLEXITY_MEDIUM,
1735             PASSWORD_COMPLEXITY_HIGH,
1736     })
1737     public @interface PasswordComplexity {}
1738 
1739     /**
1740      * Indicates that nearby streaming is not controlled by policy, which means nearby streaming is
1741      * allowed.
1742      */
1743     public static final int NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY = 0;
1744 
1745     /** Indicates that nearby streaming is disabled. */
1746     public static final int NEARBY_STREAMING_DISABLED = 1;
1747 
1748     /** Indicates that nearby streaming is enabled. */
1749     public static final int NEARBY_STREAMING_ENABLED = 2;
1750 
1751     /**
1752      * Indicates that nearby streaming is enabled only to devices offering a comparable level of
1753      * security, with the same authenticated managed account.
1754      */
1755     public static final int NEARBY_STREAMING_SAME_MANAGED_ACCOUNT_ONLY = 3;
1756 
1757     /**
1758      * @hide
1759      */
1760     @Retention(RetentionPolicy.SOURCE)
1761     @IntDef(prefix = {"NEARBY_STREAMING_"}, value = {
1762         NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY,
1763         NEARBY_STREAMING_DISABLED,
1764         NEARBY_STREAMING_ENABLED,
1765         NEARBY_STREAMING_SAME_MANAGED_ACCOUNT_ONLY,
1766     })
1767     public @interface NearbyStreamingPolicy {}
1768 
1769     /**
1770      * Activity action: have the user enter a new password for the parent profile.
1771      * If the intent is launched from within a managed profile, this will trigger
1772      * entering a new password for the parent of the profile. The caller can optionally
1773      * set {@link #EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY} to only enforce device-wide
1774      * password requirement. In all other cases the behaviour is identical to
1775      * {@link #ACTION_SET_NEW_PASSWORD}.
1776      */
1777     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1778     public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1779             = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD";
1780 
1781     /**
1782      * Broadcast action: Tell the status bar to open the device monitoring dialog, e.g. when
1783      * Network logging was enabled and the user tapped the notification.
1784      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1785      * @hide
1786      */
1787     public static final String ACTION_SHOW_DEVICE_MONITORING_DIALOG
1788             = "android.app.action.SHOW_DEVICE_MONITORING_DIALOG";
1789 
1790     /**
1791      * Broadcast Action: Sent after application delegation scopes are changed. The new delegation
1792      * scopes will be sent in an {@code ArrayList<String>} extra identified by the
1793      * {@link #EXTRA_DELEGATION_SCOPES} key.
1794      *
1795      * <p class="note"><b>Note:</b> This is a protected intent that can only be sent by the
1796      * system.</p>
1797      */
1798     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1799     public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED =
1800             "android.app.action.APPLICATION_DELEGATION_SCOPES_CHANGED";
1801 
1802     /**
1803      * An {@code ArrayList<String>} corresponding to the delegation scopes given to an app in the
1804      * {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} broadcast.
1805      */
1806     public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES";
1807 
1808     /**
1809      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1810      * the parent profile to access intents sent from the managed profile.
1811      * That is, when an app in the managed profile calls
1812      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1813      * matching activity in the parent profile.
1814      */
1815     public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
1816 
1817     /**
1818      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1819      * the managed profile to access intents sent from the parent profile.
1820      * That is, when an app in the parent profile calls
1821      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1822      * matching activity in the managed profile.
1823      */
1824     public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
1825 
1826     /**
1827      * Broadcast action: notify that a new local system update policy has been set by the device
1828      * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
1829      */
1830     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1831     public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
1832             = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
1833 
1834     /**
1835      * Broadcast action from ManagedProvisioning to notify that the latest change to
1836      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has been successfully
1837      * applied (cross profile intent filters updated). Only usesd for CTS tests.
1838      * @hide
1839      */
1840     @TestApi
1841     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1842     public static final String ACTION_DATA_SHARING_RESTRICTION_APPLIED =
1843             "android.app.action.DATA_SHARING_RESTRICTION_APPLIED";
1844 
1845     /**
1846      * Broadcast action: notify that a value of {@link Settings.Global#DEVICE_POLICY_CONSTANTS}
1847      * has been changed.
1848      * @hide
1849      */
1850     @TestApi
1851     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1852     public static final String ACTION_DEVICE_POLICY_CONSTANTS_CHANGED =
1853             "android.app.action.DEVICE_POLICY_CONSTANTS_CHANGED";
1854 
1855     /**
1856      * Permission policy to prompt user for new permission requests for runtime permissions.
1857      * Already granted or denied permissions are not affected by this.
1858      */
1859     public static final int PERMISSION_POLICY_PROMPT = 0;
1860 
1861     /**
1862      * Permission policy to always grant new permission requests for runtime permissions.
1863      * Already granted or denied permissions are not affected by this.
1864      */
1865     public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
1866 
1867     /**
1868      * Permission policy to always deny new permission requests for runtime permissions.
1869      * Already granted or denied permissions are not affected by this.
1870      */
1871     public static final int PERMISSION_POLICY_AUTO_DENY = 2;
1872 
1873     /**
1874      * Possible policy values for permissions.
1875      *
1876      * @hide
1877      */
1878     @IntDef(prefix = { "PERMISSION_GRANT_STATE_" }, value = {
1879             PERMISSION_GRANT_STATE_DEFAULT,
1880             PERMISSION_GRANT_STATE_GRANTED,
1881             PERMISSION_GRANT_STATE_DENIED
1882     })
1883     @Retention(RetentionPolicy.SOURCE)
1884     public @interface PermissionGrantState {}
1885 
1886     /**
1887      * Runtime permission state: The user can manage the permission
1888      * through the UI.
1889      */
1890     public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
1891 
1892     /**
1893      * Runtime permission state: The permission is granted to the app
1894      * and the user cannot manage the permission through the UI.
1895      */
1896     public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
1897 
1898     /**
1899      * Runtime permission state: The permission is denied to the app
1900      * and the user cannot manage the permission through the UI.
1901      */
1902     public static final int PERMISSION_GRANT_STATE_DENIED = 2;
1903 
1904     /**
1905      * Delegation of certificate installation and management. This scope grants access to the
1906      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
1907      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair} APIs.
1908      * This scope also grants the ability to read identifiers that the delegating device owner or
1909      * profile owner can obtain. See {@link #getEnrollmentSpecificId()}.
1910      */
1911     public static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
1912 
1913     /**
1914      * Delegation of application restrictions management. This scope grants access to the
1915      * {@link #setApplicationRestrictions} and {@link #getApplicationRestrictions} APIs.
1916      */
1917     public static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions";
1918 
1919     /**
1920      * Delegation of application uninstall block. This scope grants access to the
1921      * {@link #setUninstallBlocked} API.
1922      */
1923     public static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall";
1924 
1925     /**
1926      * Delegation of permission policy and permission grant state. This scope grants access to the
1927      * {@link #setPermissionPolicy}, {@link #getPermissionGrantState},
1928      * and {@link #setPermissionGrantState} APIs.
1929      */
1930     public static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant";
1931 
1932     /**
1933      * Delegation of package access state. This scope grants access to the
1934      * {@link #isApplicationHidden}, {@link #setApplicationHidden}, {@link #isPackageSuspended}, and
1935      * {@link #setPackagesSuspended} APIs.
1936      */
1937     public static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
1938 
1939     /**
1940      * Delegation for enabling system apps. This scope grants access to the {@link #enableSystemApp}
1941      * API.
1942      */
1943     public static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app";
1944 
1945     /**
1946      * Delegation for installing existing packages. This scope grants access to the
1947      * {@link #installExistingPackage} API.
1948      */
1949     public static final String DELEGATION_INSTALL_EXISTING_PACKAGE =
1950             "delegation-install-existing-package";
1951 
1952     /**
1953      * Delegation of management of uninstalled packages. This scope grants access to the
1954      * {@link #setKeepUninstalledPackages} and {@link #getKeepUninstalledPackages} APIs.
1955      */
1956     public static final String DELEGATION_KEEP_UNINSTALLED_PACKAGES =
1957             "delegation-keep-uninstalled-packages";
1958 
1959     /**
1960      * Grants access to {@link #setNetworkLoggingEnabled}, {@link #isNetworkLoggingEnabled} and
1961      * {@link #retrieveNetworkLogs}. Once granted the delegated app will start receiving
1962      * DelegatedAdminReceiver.onNetworkLogsAvailable() callback, and Device owner or Profile Owner
1963      * will no longer receive the DeviceAdminReceiver.onNetworkLogsAvailable() callback.
1964      * There can be at most one app that has this delegation.
1965      * If another app already had delegated network logging access,
1966      * it will lose the delegation when a new app is delegated.
1967      *
1968      * <p> Can only be granted by Device Owner or Profile Owner of a managed profile.
1969      */
1970     public static final String DELEGATION_NETWORK_LOGGING = "delegation-network-logging";
1971 
1972     /**
1973      * Grants access to selection of KeyChain certificates on behalf of requesting apps.
1974      * Once granted the app will start receiving
1975      * {@link DelegatedAdminReceiver#onChoosePrivateKeyAlias}. The caller (PO/DO) will
1976      * no longer receive {@link DeviceAdminReceiver#onChoosePrivateKeyAlias}.
1977      * There can be at most one app that has this delegation.
1978      * If another app already had delegated certificate selection access,
1979      * it will lose the delegation when a new app is delegated.
1980      * <p> The delegaetd app can also call {@link #grantKeyPairToApp} and
1981      * {@link #revokeKeyPairFromApp} to directly grant KeyCain keys to other apps.
1982      * <p> Can be granted by Device Owner or Profile Owner.
1983      */
1984     public static final String DELEGATION_CERT_SELECTION = "delegation-cert-selection";
1985 
1986     /**
1987      * Grants access to {@link #setSecurityLoggingEnabled}, {@link #isSecurityLoggingEnabled},
1988      * {@link #retrieveSecurityLogs}, and {@link #retrievePreRebootSecurityLogs}. Once granted the
1989      * delegated app will start receiving {@link DelegatedAdminReceiver#onSecurityLogsAvailable}
1990      * callback, and Device owner or Profile Owner will no longer receive the
1991      * {@link DeviceAdminReceiver#onSecurityLogsAvailable} callback. There can be at most one app
1992      * that has this delegation. If another app already had delegated security logging access, it
1993      * will lose the delegation when a new app is delegated.
1994      *
1995      * <p> Can only be granted by Device Owner or Profile Owner of an organnization owned and
1996      * managed profile.
1997      */
1998     public static final String DELEGATION_SECURITY_LOGGING = "delegation-security-logging";
1999 
2000     /**
2001      * No management for current user in-effect. This is the default.
2002      * @hide
2003      */
2004     @SystemApi
2005     public static final int STATE_USER_UNMANAGED = 0;
2006 
2007     /**
2008      * Management partially setup, user setup needs to be completed.
2009      * @hide
2010      */
2011     @SystemApi
2012     public static final int STATE_USER_SETUP_INCOMPLETE = 1;
2013 
2014     /**
2015      * Management partially setup, user setup completed.
2016      * @hide
2017      */
2018     @SystemApi
2019     public static final int STATE_USER_SETUP_COMPLETE = 2;
2020 
2021     /**
2022      * Management setup and active on current user.
2023      * @hide
2024      */
2025     @SystemApi
2026     public static final int STATE_USER_SETUP_FINALIZED = 3;
2027 
2028     /**
2029      * Management partially setup on a managed profile.
2030      * @hide
2031      */
2032     @SystemApi
2033     public static final int STATE_USER_PROFILE_COMPLETE = 4;
2034 
2035     /**
2036      * Management setup on a managed profile.
2037      * <p>This is used as an intermediate state after {@link #STATE_USER_PROFILE_COMPLETE} once the
2038      * work profile has been created.
2039      * @hide
2040      */
2041     @SystemApi
2042     public static final int STATE_USER_PROFILE_FINALIZED = 5;
2043 
2044     /**
2045      * @hide
2046      */
2047     @IntDef(prefix = { "STATE_USER_" }, value = {
2048             STATE_USER_UNMANAGED,
2049             STATE_USER_SETUP_INCOMPLETE,
2050             STATE_USER_SETUP_COMPLETE,
2051             STATE_USER_SETUP_FINALIZED,
2052             STATE_USER_PROFILE_COMPLETE,
2053             STATE_USER_PROFILE_FINALIZED
2054     })
2055     @Retention(RetentionPolicy.SOURCE)
2056     public @interface UserProvisioningState {}
2057 
2058     /**
2059      * Result code for {@link #checkProvisioningPreCondition}.
2060      *
2061      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
2062      * {@link #ACTION_PROVISION_MANAGED_PROFILE} and {@link #ACTION_PROVISION_MANAGED_USER}
2063      * when provisioning is allowed.
2064      *
2065      * @hide
2066      */
2067     @TestApi
2068     public static final int CODE_OK = 0;
2069 
2070     /**
2071      * Result code for {@link #checkProvisioningPreCondition}.
2072      *
2073      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the device already has a
2074      * device owner.
2075      *
2076      * @hide
2077      */
2078     @TestApi
2079     public static final int CODE_HAS_DEVICE_OWNER = 1;
2080 
2081     /**
2082      * Result code for {@link #checkProvisioningPreCondition}.
2083      *
2084      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the user has a profile owner
2085      *  and for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the profile owner is already set.
2086      *
2087      * @hide
2088      */
2089     @TestApi
2090     public static final int CODE_USER_HAS_PROFILE_OWNER = 2;
2091 
2092     /**
2093      * Result code for {@link #checkProvisioningPreCondition}.
2094      *
2095      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the user isn't running.
2096      *
2097      * @hide
2098      */
2099     @TestApi
2100     public static final int CODE_USER_NOT_RUNNING = 3;
2101 
2102     /**
2103      * Result code for {@link #checkProvisioningPreCondition}.
2104      *
2105      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} if the device has already been
2106      * setup and for {@link #ACTION_PROVISION_MANAGED_USER} if the user has already been setup.
2107      *
2108      * @hide
2109      */
2110     @TestApi
2111     public static final int CODE_USER_SETUP_COMPLETED = 4;
2112 
2113     /**
2114      * Code used to indicate that the device also has a user other than the system user.
2115      *
2116      * @hide
2117      */
2118     @TestApi
2119     public static final int CODE_NONSYSTEM_USER_EXISTS = 5;
2120 
2121     /**
2122      * Code used to indicate that device has an account that prevents provisioning.
2123      *
2124      * @hide
2125      */
2126     @TestApi
2127     public static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
2128 
2129     /**
2130      * Result code for {@link #checkProvisioningPreCondition}.
2131      *
2132      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} if the user is not a system user.
2133      *
2134      * @hide
2135      */
2136     @TestApi
2137     public static final int CODE_NOT_SYSTEM_USER = 7;
2138 
2139     /**
2140      * Result code for {@link #checkProvisioningPreCondition}.
2141      *
2142      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
2143      * {@link #ACTION_PROVISION_MANAGED_USER} when the device is a watch and is already paired.
2144      *
2145      * @hide
2146      */
2147     @TestApi
2148     public static final int CODE_HAS_PAIRED = 8;
2149 
2150     /**
2151      * Result code for {@link #checkProvisioningPreCondition}.
2152      *
2153      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} and
2154      * {@link #ACTION_PROVISION_MANAGED_USER} on devices which do not support managed users.
2155      *
2156      * @see {@link PackageManager#FEATURE_MANAGED_USERS}
2157      * @hide
2158      */
2159     @TestApi
2160     public static final int CODE_MANAGED_USERS_NOT_SUPPORTED = 9;
2161 
2162     /**
2163      * Result code for {@link #checkProvisioningPreCondition}.
2164      *
2165      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} if the user is a system user and
2166      * for {@link #ACTION_PROVISION_MANAGED_DEVICE} on devices running headless system user mode
2167      * and the user is a system user.
2168      *
2169      * @hide
2170      */
2171     @TestApi
2172     public static final int CODE_SYSTEM_USER = 10;
2173 
2174     /**
2175      * Result code for {@link #checkProvisioningPreCondition}.
2176      *
2177      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the user cannot have more
2178      * managed profiles.
2179      *
2180      * @hide
2181      */
2182     @TestApi
2183     public static final int CODE_CANNOT_ADD_MANAGED_PROFILE = 11;
2184 
2185     /**
2186      * TODO (b/137101239): clean up split system user codes
2187      *
2188      * @hide
2189      * @deprecated not used anymore but can't be removed since it's a @TestApi.
2190      **/
2191     @Deprecated
2192     @TestApi
2193     public static final int CODE_NOT_SYSTEM_USER_SPLIT = 12;
2194 
2195     /**
2196      * Result code for {@link #checkProvisioningPreCondition}.
2197      *
2198      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
2199      * {@link #ACTION_PROVISION_MANAGED_PROFILE} on devices which do not support device
2200      * admins.
2201      *
2202      * @hide
2203      */
2204     @TestApi
2205     public static final int CODE_DEVICE_ADMIN_NOT_SUPPORTED = 13;
2206 
2207     /**
2208      * TODO (b/137101239): clean up split system user codes
2209      * Result code for {@link #checkProvisioningPreCondition}.
2210      *
2211      * @hide
2212      * @deprecated not used anymore but can't be removed since it's a @TestApi.
2213      */
2214     @Deprecated
2215     @TestApi
2216     public static final int CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER = 14;
2217 
2218     /**
2219      * Result code for {@link #checkProvisioningPreCondition}.
2220      *
2221      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
2222      * {@link #ACTION_PROVISION_MANAGED_PROFILE} on devices which do not support provisioning.
2223      *
2224      * @hide
2225      */
2226     @TestApi
2227     public static final int CODE_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS = 15;
2228 
2229     /**
2230      * Result codes for {@link #checkProvisioningPreCondition} indicating all the provisioning pre
2231      * conditions.
2232      *
2233      * @hide
2234      */
2235     @Retention(RetentionPolicy.SOURCE)
2236     @IntDef(prefix = { "CODE_" }, value = {
2237             CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
2238             CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER, CODE_HAS_PAIRED,
2239             CODE_MANAGED_USERS_NOT_SUPPORTED, CODE_SYSTEM_USER, CODE_CANNOT_ADD_MANAGED_PROFILE,
2240             CODE_NOT_SYSTEM_USER_SPLIT, CODE_DEVICE_ADMIN_NOT_SUPPORTED,
2241             CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER,
2242             CODE_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS
2243     })
2244     public @interface ProvisioningPreCondition {}
2245 
2246     /**
2247      * Service-specific error code for {@link #provisionFullyManagedDevice} and
2248      * {@link #createAndProvisionManagedProfile}:
2249      * Indicates the call to {@link #checkProvisioningPreCondition} returned an error code.
2250      *
2251      * @hide
2252      */
2253     @TestApi
2254     public static final int PROVISIONING_RESULT_PRE_CONDITION_FAILED = 1;
2255 
2256     /**
2257      * Service-specific error code for {@link #createAndProvisionManagedProfile}:
2258      * Indicates the call to {@link UserManager#createProfileForUserEvenWhenDisallowed}
2259      * returned {@code null}.
2260      *
2261      * @hide
2262      */
2263     @TestApi
2264     public static final int PROVISIONING_RESULT_PROFILE_CREATION_FAILED = 2;
2265 
2266     /**
2267      * Service-specific error code for {@link #createAndProvisionManagedProfile}:
2268      * Indicates the call to {@link PackageManager#installExistingPackageAsUser} has failed.
2269      *
2270      * @hide
2271      */
2272     @TestApi
2273     public static final int PROVISIONING_RESULT_ADMIN_PACKAGE_INSTALLATION_FAILED = 3;
2274 
2275     /**
2276      * Service-specific error code for {@link #createAndProvisionManagedProfile}:
2277      * Indicates the call to {@link #setProfileOwner} returned {@code false}.
2278      *
2279      * @hide
2280      */
2281     @TestApi
2282     public static final int PROVISIONING_RESULT_SETTING_PROFILE_OWNER_FAILED = 4;
2283 
2284     /**
2285      * Service-specific error code for {@link #createAndProvisionManagedProfile}:
2286      * Indicates that starting the newly created profile has failed.
2287      *
2288      * @hide
2289      */
2290     @TestApi
2291     public static final int PROVISIONING_RESULT_STARTING_PROFILE_FAILED = 5;
2292 
2293     /**
2294      * Service-specific error code for {@link #provisionFullyManagedDevice}:
2295      * Indicates that removing the non required apps have failed.
2296      *
2297      * @hide
2298      */
2299     @TestApi
2300     public static final int PROVISIONING_RESULT_REMOVE_NON_REQUIRED_APPS_FAILED = 6;
2301 
2302     /**
2303      * Service-specific error code for {@link #provisionFullyManagedDevice}:
2304      * Indicates the call to {@link #setDeviceOwner} returned {@code false}.
2305      *
2306      * @hide
2307      */
2308     @TestApi
2309     public static final int PROVISIONING_RESULT_SET_DEVICE_OWNER_FAILED = 7;
2310 
2311     /**
2312      * Service-specific error codes for {@link #createAndProvisionManagedProfile} and
2313      * {@link #provisionFullyManagedDevice} indicating all the errors during provisioning.
2314      *
2315      * @hide
2316      */
2317     @Retention(RetentionPolicy.SOURCE)
2318     @IntDef(prefix = { "PROVISIONING_RESULT_" }, value = {
2319             PROVISIONING_RESULT_PRE_CONDITION_FAILED, PROVISIONING_RESULT_PROFILE_CREATION_FAILED,
2320             PROVISIONING_RESULT_ADMIN_PACKAGE_INSTALLATION_FAILED,
2321             PROVISIONING_RESULT_SETTING_PROFILE_OWNER_FAILED,
2322             PROVISIONING_RESULT_STARTING_PROFILE_FAILED,
2323             PROVISIONING_RESULT_REMOVE_NON_REQUIRED_APPS_FAILED,
2324             PROVISIONING_RESULT_SET_DEVICE_OWNER_FAILED
2325     })
2326     public @interface ProvisioningResult {}
2327 
2328     /**
2329      * Disable all configurable SystemUI features during LockTask mode. This includes,
2330      * <ul>
2331      *     <li>system info area in the status bar (connectivity icons, clock, etc.)
2332      *     <li>notifications (including alerts, icons, and the notification shade)
2333      *     <li>Home button
2334      *     <li>Recents button and UI
2335      *     <li>global actions menu (i.e. power button menu)
2336      *     <li>keyguard
2337      * </ul>
2338      *
2339      * @see #setLockTaskFeatures(ComponentName, int)
2340      */
2341     public static final int LOCK_TASK_FEATURE_NONE = 0;
2342 
2343     /**
2344      * Enable the system info area in the status bar during LockTask mode. The system info area
2345      * usually occupies the right side of the status bar (although this can differ across OEMs). It
2346      * includes all system information indicators, such as date and time, connectivity, battery,
2347      * vibration mode, etc.
2348      *
2349      * @see #setLockTaskFeatures(ComponentName, int)
2350      */
2351     public static final int LOCK_TASK_FEATURE_SYSTEM_INFO = 1;
2352 
2353     /**
2354      * Enable notifications during LockTask mode. This includes notification icons on the status
2355      * bar, heads-up notifications, and the expandable notification shade. Note that the Quick
2356      * Settings panel remains disabled. This feature flag can only be used in combination with
2357      * {@link #LOCK_TASK_FEATURE_HOME}. {@link #setLockTaskFeatures(ComponentName, int)}
2358      * throws an {@link IllegalArgumentException} if this feature flag is defined without
2359      * {@link #LOCK_TASK_FEATURE_HOME}.
2360      *
2361      * @see #setLockTaskFeatures(ComponentName, int)
2362      */
2363     public static final int LOCK_TASK_FEATURE_NOTIFICATIONS = 1 << 1;
2364 
2365     /**
2366      * Enable the Home button during LockTask mode. Note that if a custom launcher is used, it has
2367      * to be registered as the default launcher with
2368      * {@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}, and its
2369      * package needs to be allowlisted for LockTask with
2370      * {@link #setLockTaskPackages(ComponentName, String[])}.
2371      *
2372      * @see #setLockTaskFeatures(ComponentName, int)
2373      */
2374     public static final int LOCK_TASK_FEATURE_HOME = 1 << 2;
2375 
2376     /**
2377      * Enable the Overview button and the Overview screen during LockTask mode. This feature flag
2378      * can only be used in combination with {@link #LOCK_TASK_FEATURE_HOME}, and
2379      * {@link #setLockTaskFeatures(ComponentName, int)} will throw an
2380      * {@link IllegalArgumentException} if this feature flag is defined without
2381      * {@link #LOCK_TASK_FEATURE_HOME}.
2382      *
2383      * @see #setLockTaskFeatures(ComponentName, int)
2384      */
2385     public static final int LOCK_TASK_FEATURE_OVERVIEW = 1 << 3;
2386 
2387     /**
2388      * Enable the global actions dialog during LockTask mode. This is the dialog that shows up when
2389      * the user long-presses the power button, for example. Note that the user may not be able to
2390      * power off the device if this flag is not set.
2391      *
2392      * <p>This flag is enabled by default until {@link #setLockTaskFeatures(ComponentName, int)} is
2393      * called for the first time.
2394      *
2395      * @see #setLockTaskFeatures(ComponentName, int)
2396      */
2397     public static final int LOCK_TASK_FEATURE_GLOBAL_ACTIONS = 1 << 4;
2398 
2399     /**
2400      * Enable the keyguard during LockTask mode. Note that if the keyguard is already disabled with
2401      * {@link #setKeyguardDisabled(ComponentName, boolean)}, setting this flag will have no effect.
2402      * If this flag is not set, the keyguard will not be shown even if the user has a lock screen
2403      * credential.
2404      *
2405      * @see #setLockTaskFeatures(ComponentName, int)
2406      */
2407     public static final int LOCK_TASK_FEATURE_KEYGUARD = 1 << 5;
2408 
2409     /**
2410      * Enable blocking of non-allowlisted activities from being started into a locked task.
2411      *
2412      * @see #setLockTaskFeatures(ComponentName, int)
2413      */
2414     public static final int LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK = 1 << 6;
2415 
2416     /**
2417      * Flags supplied to {@link #setLockTaskFeatures(ComponentName, int)}.
2418      *
2419      * @hide
2420      */
2421     @Retention(RetentionPolicy.SOURCE)
2422     @IntDef(flag = true, prefix = { "LOCK_TASK_FEATURE_" }, value = {
2423             LOCK_TASK_FEATURE_NONE,
2424             LOCK_TASK_FEATURE_SYSTEM_INFO,
2425             LOCK_TASK_FEATURE_NOTIFICATIONS,
2426             LOCK_TASK_FEATURE_HOME,
2427             LOCK_TASK_FEATURE_OVERVIEW,
2428             LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
2429             LOCK_TASK_FEATURE_KEYGUARD,
2430             LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK
2431     })
2432     public @interface LockTaskFeature {}
2433 
2434     /**
2435      * Service action: Action for a service that device owner and profile owner can optionally
2436      * own.  If a device owner or a profile owner has such a service, the system tries to keep
2437      * a bound connection to it, in order to keep their process always running.
2438      * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN}
2439      * permission.
2440      */
2441     @SdkConstant(SdkConstantType.SERVICE_ACTION)
2442     public static final String ACTION_DEVICE_ADMIN_SERVICE
2443             = "android.app.action.DEVICE_ADMIN_SERVICE";
2444 
2445     /** @hide */
2446     @Retention(RetentionPolicy.SOURCE)
2447     @IntDef(flag = true, prefix = {"ID_TYPE_"}, value = {
2448         ID_TYPE_BASE_INFO,
2449         ID_TYPE_SERIAL,
2450         ID_TYPE_IMEI,
2451         ID_TYPE_MEID,
2452         ID_TYPE_INDIVIDUAL_ATTESTATION
2453     })
2454     public @interface AttestationIdType {}
2455 
2456     /**
2457      * Specifies that the device should attest its manufacturer details. For use with
2458      * {@link #generateKeyPair}.
2459      *
2460      * @see #generateKeyPair
2461      */
2462     public static final int ID_TYPE_BASE_INFO = 1;
2463 
2464     /**
2465      * Specifies that the device should attest its serial number. For use with
2466      * {@link #generateKeyPair}.
2467      *
2468      * @see #generateKeyPair
2469      */
2470     public static final int ID_TYPE_SERIAL = 2;
2471 
2472     /**
2473      * Specifies that the device should attest its IMEI. For use with {@link #generateKeyPair}.
2474      *
2475      * @see #generateKeyPair
2476      */
2477     public static final int ID_TYPE_IMEI = 4;
2478 
2479     /**
2480      * Specifies that the device should attest its MEID. For use with {@link #generateKeyPair}.
2481      *
2482      * @see #generateKeyPair
2483      */
2484     public static final int ID_TYPE_MEID = 8;
2485 
2486     /**
2487      * Specifies that the device should attest using an individual attestation certificate.
2488      * For use with {@link #generateKeyPair}.
2489      *
2490      * @see #generateKeyPair
2491      */
2492     public static final int ID_TYPE_INDIVIDUAL_ATTESTATION = 16;
2493 
2494     /**
2495      * Service-specific error code for {@link #generateKeyPair}:
2496      * Indicates the call has failed due to StrongBox unavailability.
2497      * @hide
2498      */
2499     public static final int KEY_GEN_STRONGBOX_UNAVAILABLE = 1;
2500 
2501     /**
2502      * Specifies that the calling app should be granted access to the installed credentials
2503      * immediately. Otherwise, access to the credentials will be gated by user approval.
2504      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
2505      *
2506      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
2507      */
2508     public static final int INSTALLKEY_REQUEST_CREDENTIALS_ACCESS = 1;
2509 
2510     /**
2511      * Specifies that a user can select the key via the Certificate Selection prompt.
2512      * If this flag is not set when calling {@link #installKeyPair}, the key can only be granted
2513      * access by implementing {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
2514      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
2515      *
2516      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
2517      */
2518     public static final int INSTALLKEY_SET_USER_SELECTABLE = 2;
2519 
2520     /**
2521      * Broadcast action: sent when the profile owner is set, changed or cleared.
2522      *
2523      * This broadcast is sent only to the user managed by the new profile owner.
2524      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
2525      */
2526     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2527     public static final String ACTION_PROFILE_OWNER_CHANGED =
2528             "android.app.action.PROFILE_OWNER_CHANGED";
2529 
2530     /** @hide */
2531     @Retention(RetentionPolicy.SOURCE)
2532     @IntDef(prefix = {"PRIVATE_DNS_MODE_"}, value = {
2533             PRIVATE_DNS_MODE_UNKNOWN,
2534             PRIVATE_DNS_MODE_OFF,
2535             PRIVATE_DNS_MODE_OPPORTUNISTIC,
2536             PRIVATE_DNS_MODE_PROVIDER_HOSTNAME
2537     })
2538     public @interface PrivateDnsMode {}
2539 
2540     /**
2541      * Specifies that the Private DNS setting is in an unknown state.
2542      */
2543     public static final int PRIVATE_DNS_MODE_UNKNOWN = 0;
2544 
2545     /**
2546      * Specifies that Private DNS was turned off completely.
2547      */
2548     public static final int PRIVATE_DNS_MODE_OFF = 1;
2549 
2550     /**
2551      * Specifies that the device owner requested opportunistic DNS over TLS
2552      */
2553     public static final int PRIVATE_DNS_MODE_OPPORTUNISTIC = 2;
2554 
2555     /**
2556      * Specifies that the device owner configured a specific host to use for Private DNS.
2557      */
2558     public static final int PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = 3;
2559 
2560     /**
2561      * Callback used in {@link #installSystemUpdate} to indicate that there was an error while
2562      * trying to install an update.
2563      */
2564     public abstract static class InstallSystemUpdateCallback {
2565         /** Represents an unknown error while trying to install an update. */
2566         public static final int UPDATE_ERROR_UNKNOWN = 1;
2567 
2568         /** Represents the update file being intended for different OS version. */
2569         public static final int UPDATE_ERROR_INCORRECT_OS_VERSION = 2;
2570 
2571         /**
2572          * Represents the update file being wrong; e.g. payloads are mismatched, or the wrong
2573          * compression method is used.
2574          */
2575         public static final int UPDATE_ERROR_UPDATE_FILE_INVALID = 3;
2576 
2577         /** Represents that the file could not be found. */
2578         public static final int UPDATE_ERROR_FILE_NOT_FOUND = 4;
2579 
2580         /** Represents the battery being too low to apply an update. */
2581         public static final int UPDATE_ERROR_BATTERY_LOW = 5;
2582 
2583         /**
2584          * Method invoked when there was an error while installing an update.
2585          *
2586          * <p>The given error message is not intended to be user-facing. It is intended to be
2587          * reported back to the IT admin to be read.
2588          */
onInstallUpdateError( @nstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage)2589         public void onInstallUpdateError(
2590                 @InstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage) {
2591         }
2592     }
2593 
2594     /**
2595      * @hide
2596      */
2597     @IntDef(prefix = { "UPDATE_ERROR_" }, value = {
2598             InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN,
2599             InstallSystemUpdateCallback.UPDATE_ERROR_INCORRECT_OS_VERSION,
2600             InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
2601             InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
2602             InstallSystemUpdateCallback.UPDATE_ERROR_BATTERY_LOW
2603     })
2604     @Retention(RetentionPolicy.SOURCE)
2605     public @interface InstallUpdateCallbackErrorConstants {}
2606 
2607     /**
2608      * The selected mode has been set successfully. If the mode is
2609      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} then it implies the supplied host is valid
2610      * and reachable.
2611      */
2612     public static final int PRIVATE_DNS_SET_NO_ERROR = 0;
2613 
2614     /**
2615      * If the {@code privateDnsHost} provided was of a valid hostname but that host was found
2616      * to not support DNS-over-TLS.
2617      */
2618     public static final int PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING = 1;
2619 
2620     /**
2621      * General failure to set the Private DNS mode, not due to one of the reasons listed above.
2622      */
2623     public static final int PRIVATE_DNS_SET_ERROR_FAILURE_SETTING = 2;
2624 
2625     /**
2626      * @hide
2627      */
2628     @IntDef(prefix = {"PRIVATE_DNS_SET_"}, value = {
2629             PRIVATE_DNS_SET_NO_ERROR,
2630             PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING,
2631             PRIVATE_DNS_SET_ERROR_FAILURE_SETTING
2632     })
2633     @Retention(RetentionPolicy.SOURCE)
2634     public @interface PrivateDnsModeErrorCodes {}
2635 
2636     /**
2637      * Activity action: Starts the administrator to get the mode for the provisioning.
2638      * This intent may contain the following extras:
2639      * <ul>
2640      *     <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}</li>
2641      *     <li>{@link #EXTRA_PROVISIONING_IMEI}</li>
2642      *     <li>{@link #EXTRA_PROVISIONING_SERIAL_NUMBER}</li>
2643      * </ul>
2644      *
2645      * <p>The target activity should return one of the following values in
2646      * {@link #EXTRA_PROVISIONING_MODE} as result:
2647      * <ul>
2648      *     <li>{@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}</li>
2649      *     <li>{@link #PROVISIONING_MODE_MANAGED_PROFILE}</li>
2650      * </ul>
2651      *
2652      * <p>If performing fully-managed device provisioning and the admin app desires to show its
2653      * own education screens, the target activity can additionally return
2654      * {@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS} set to <code>true</code>.
2655      *
2656      * <p>The target activity may also return the account that needs to be migrated from primary
2657      * user to managed profile in case of a profile owner provisioning in
2658      * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE} as result.
2659      *
2660      * <p>The target activity may also include the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}
2661      * extra in the intent result. The values of this {@link android.os.PersistableBundle} will be
2662      * sent as an intent extra of the same name to the {@link #ACTION_ADMIN_POLICY_COMPLIANCE}
2663      * activity, along with the values of the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE} extra
2664      * that are already supplied to this activity.
2665      *
2666      * @see #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION
2667      * @see #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED
2668      * @see #ACTION_ADMIN_POLICY_COMPLIANCE
2669      */
2670     public static final String ACTION_GET_PROVISIONING_MODE =
2671             "android.app.action.GET_PROVISIONING_MODE";
2672 
2673     /**
2674      * A string extra holding the IMEI (International Mobile Equipment Identity) of the device.
2675      */
2676     public static final String EXTRA_PROVISIONING_IMEI = "android.app.extra.PROVISIONING_IMEI";
2677 
2678     /**
2679      * A string extra holding the serial number of the device.
2680      */
2681     public static final String EXTRA_PROVISIONING_SERIAL_NUMBER =
2682             "android.app.extra.PROVISIONING_SERIAL_NUMBER";
2683 
2684     /**
2685      * An intent extra holding the provisioning mode returned by the administrator.
2686      * The value of this extra must be one of the values provided in {@link
2687      * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES}, which is provided as an intent extra to
2688      * the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity.
2689      *
2690      * @see #PROVISIONING_MODE_FULLY_MANAGED_DEVICE
2691      * @see #PROVISIONING_MODE_MANAGED_PROFILE
2692      */
2693     public static final String EXTRA_PROVISIONING_MODE =
2694             "android.app.extra.PROVISIONING_MODE";
2695 
2696     /**
2697      * An integer extra indication what provisioning modes should be available for the admin app
2698      * to pick.
2699      *
2700      * <p>The default value is {@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}.
2701      *
2702      * <p>The value of this extra will determine the contents of the {@link
2703      * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array that is passed to the admin app as an
2704      * extra to its {@link #ACTION_GET_PROVISIONING_MODE} activity.
2705      *
2706      * <p>If one of the possible admin app choices is a personally-owned work profile, then the
2707      * IMEI and serial number will not be passed to the admin app's {@link
2708      * #ACTION_GET_PROVISIONING_MODE} activity via the {@link #EXTRA_PROVISIONING_IMEI} and {@link
2709      * #EXTRA_PROVISIONING_SERIAL_NUMBER} respectively.
2710      *
2711      * <p>The allowed flag combinations are:
2712      * <ul>
2713      *     <li>{@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}</li>
2714      *     <li>{@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}</li>
2715      *     <li>{@link #FLAG_SUPPORTED_MODES_DEVICE_OWNER}</li>
2716      *     <li>{@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}
2717      *             | {@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}</li>
2718      * </ul>
2719      *
2720      * <p>This extra is only respected when provided alongside the {@link
2721      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
2722      *
2723      * @see #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED
2724      * @see #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED
2725      * @see #FLAG_SUPPORTED_MODES_DEVICE_OWNER
2726      * @hide
2727      */
2728     @SystemApi
2729     public static final String EXTRA_PROVISIONING_SUPPORTED_MODES =
2730             "android.app.extra.PROVISIONING_SUPPORTED_MODES";
2731 
2732     /**
2733      * A boolean extra which determines whether to skip the ownership disclaimer screen during the
2734      * provisioning flow. The default value is {@code false}.
2735      *
2736      * If the value is {@code true}, the provisioning initiator must display a device ownership
2737      * disclaimer screen similar to that provided in AOSP.
2738      *
2739      * <p>This extra is only respected when provided alongside the {@link
2740      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
2741      *
2742      * @hide
2743      */
2744     @SystemApi
2745     public static final String EXTRA_PROVISIONING_SKIP_OWNERSHIP_DISCLAIMER =
2746             "android.app.extra.PROVISIONING_SKIP_OWNERSHIP_DISCLAIMER";
2747 
2748     /**
2749      * An {@link ArrayList} of {@link Integer} extra specifying the allowed provisioning modes.
2750      * <p>This extra will be passed to the admin app's {@link #ACTION_GET_PROVISIONING_MODE}
2751      * activity, whose result intent must contain {@link #EXTRA_PROVISIONING_MODE} set to one of
2752      * the values in this array.
2753      * <p>If the value set to {@link #EXTRA_PROVISIONING_MODE} is not in the array,
2754      * provisioning will fail.
2755      * @see #PROVISIONING_MODE_MANAGED_PROFILE
2756      * @see #PROVISIONING_MODE_FULLY_MANAGED_DEVICE
2757      */
2758     public static final String EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES =
2759             "android.app.extra.PROVISIONING_ALLOWED_PROVISIONING_MODES";
2760 
2761     /**
2762      * The provisioning mode for fully managed device.
2763      */
2764     public static final int PROVISIONING_MODE_FULLY_MANAGED_DEVICE = 1;
2765 
2766     /**
2767      * The provisioning mode for managed profile.
2768      */
2769     public static final int PROVISIONING_MODE_MANAGED_PROFILE = 2;
2770 
2771     /**
2772      * The provisioning mode for a managed profile on a personal device.
2773      * <p>This mode is only available when the provisioning initiator has explicitly instructed the
2774      * provisioning flow to support managed profile on a personal device provisioning. In that case,
2775      * {@link #PROVISIONING_MODE_MANAGED_PROFILE} corresponds to an organization-owned managed
2776      * profile, whereas this constant corresponds to a personally-owned managed profile.
2777      *
2778      * @see #EXTRA_PROVISIONING_MODE
2779      */
2780     public static final int PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE = 3;
2781 
2782     /**
2783      * A {@code boolean} flag that indicates whether the provisioning flow should return before
2784      * starting the admin app's {@link #ACTION_ADMIN_POLICY_COMPLIANCE} handler. The default value
2785      * is {@code true}.
2786      *
2787      * <p>If this extra is set to {@code true}, then when the provisioning flow returns back to the
2788      * provisioning initiator, provisioning will not be complete. The provisioning initiator can
2789      * use this opportunity to do its own preparatory steps prior to the launch of the admin app's
2790      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} handler. It is the responsibility of the
2791      * provisioning initiator to ensure that the provisioning flow is then resumed and completed.
2792      *
2793      * <p>If this extra is set to {@code false}, then when the provisioning flow returns back to
2794      * the provisioning initiator, provisioning will be complete. Note that device owner
2795      * provisioning is not currently supported for the this scenario.
2796      *
2797      * <p>This extra is only respected when provided alongside the {@link
2798      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
2799      *
2800      * @hide
2801      */
2802     @SystemApi
2803     public static final String EXTRA_PROVISIONING_RETURN_BEFORE_POLICY_COMPLIANCE =
2804             "android.app.extra.PROVISIONING_RETURN_BEFORE_POLICY_COMPLIANCE";
2805 
2806     /**
2807      * Activity action: Starts the administrator to show policy compliance for the provisioning.
2808      * This action is used any time that the administrator has an opportunity to show policy
2809      * compliance before the end of setup wizard. This could happen as part of the admin-integrated
2810      * provisioning flow (in which case this gets sent after {@link #ACTION_GET_PROVISIONING_MODE}),
2811      * or it could happen during provisioning finalization if the administrator supports
2812      * finalization during setup wizard.
2813      *
2814      * <p>Intents with this action may also be supplied with the {@link
2815      * #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE} extra.
2816      *
2817      * @see #ACTION_GET_PROVISIONING_MODE
2818      */
2819     public static final String ACTION_ADMIN_POLICY_COMPLIANCE =
2820             "android.app.action.ADMIN_POLICY_COMPLIANCE";
2821 
2822     /**
2823      * Maximum supported password length. Kind-of arbitrary.
2824      * @hide
2825      */
2826     public static final int MAX_PASSWORD_LENGTH = 16;
2827 
2828     /**
2829      * Service Action: Service implemented by a device owner or profile owner supervision app to
2830      * provide a secondary lockscreen.
2831      * @hide
2832      */
2833     @SystemApi
2834     public static final String ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE =
2835             "android.app.action.BIND_SECONDARY_LOCKSCREEN_SERVICE";
2836 
2837     /**
2838      * Return value for {@link #getPersonalAppsSuspendedReasons} when personal apps are not
2839      * suspended.
2840      */
2841     public static final int PERSONAL_APPS_NOT_SUSPENDED = 0;
2842 
2843     /**
2844      * Flag for {@link #getPersonalAppsSuspendedReasons} return value. Set when personal
2845      * apps are suspended by an admin explicitly via {@link #setPersonalAppsSuspended}.
2846      */
2847     public static final int PERSONAL_APPS_SUSPENDED_EXPLICITLY = 1 << 0;
2848 
2849     /**
2850      * Flag for {@link #getPersonalAppsSuspendedReasons} return value. Set when personal apps are
2851      * suspended by framework because managed profile was off for longer than allowed by policy.
2852      * @see #setManagedProfileMaximumTimeOff
2853      */
2854     public static final int PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT = 1 << 1;
2855 
2856     /**
2857      * @hide
2858      */
2859     @IntDef(flag = true, prefix = { "PERSONAL_APPS_" }, value = {
2860             PERSONAL_APPS_NOT_SUSPENDED,
2861             PERSONAL_APPS_SUSPENDED_EXPLICITLY,
2862             PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT
2863     })
2864     @Retention(RetentionPolicy.SOURCE)
2865     public @interface PersonalAppsSuspensionReason {}
2866 
2867     /**
2868      * The default device owner type for a managed device.
2869      *
2870      * @hide
2871      */
2872     public static final int DEVICE_OWNER_TYPE_DEFAULT = 0;
2873 
2874     /**
2875      * The device owner type for a financed device.
2876      *
2877      * @hide
2878      */
2879     public static final int DEVICE_OWNER_TYPE_FINANCED = 1;
2880 
2881     /**
2882      * Different device owner types for a managed device.
2883      *
2884      * @hide
2885      */
2886     @Retention(RetentionPolicy.SOURCE)
2887     @IntDef(prefix = { "DEVICE_OWNER_TYPE_" }, value = {
2888             DEVICE_OWNER_TYPE_DEFAULT,
2889             DEVICE_OWNER_TYPE_FINANCED
2890     })
2891     public @interface DeviceOwnerType {}
2892 
2893     /** @hide */
2894     @TestApi
2895     public static final int OPERATION_LOCK_NOW = 1;
2896     /** @hide */
2897     @TestApi
2898     public static final int OPERATION_SWITCH_USER = 2;
2899     /** @hide */
2900     @TestApi
2901     public static final int OPERATION_START_USER_IN_BACKGROUND = 3;
2902     /** @hide */
2903     @TestApi
2904     public static final int OPERATION_STOP_USER = 4;
2905     /** @hide */
2906     @TestApi
2907     public static final int OPERATION_CREATE_AND_MANAGE_USER = 5;
2908     /** @hide */
2909     @TestApi
2910     public static final int OPERATION_REMOVE_USER = 6;
2911     /** @hide */
2912     @TestApi
2913     public static final int OPERATION_REBOOT = 7;
2914     /** @hide */
2915     @TestApi
2916     public static final int OPERATION_WIPE_DATA = 8;
2917     /** @hide */
2918     @TestApi
2919     public static final int OPERATION_LOGOUT_USER = 9;
2920     /** @hide */
2921     @TestApi
2922     public static final int OPERATION_SET_USER_RESTRICTION = 10;
2923     /** @hide */
2924     @TestApi
2925     public static final int OPERATION_SET_SYSTEM_SETTING = 11;
2926     /** @hide */
2927     @TestApi
2928     public static final int OPERATION_SET_KEYGUARD_DISABLED = 12;
2929     /** @hide */
2930     @TestApi
2931     public static final int OPERATION_SET_STATUS_BAR_DISABLED = 13;
2932     /** @hide */
2933     @TestApi
2934     public static final int OPERATION_SET_SYSTEM_UPDATE_POLICY = 14;
2935     /** @hide */
2936     @TestApi
2937     public static final int OPERATION_SET_APPLICATION_HIDDEN = 15;
2938     /** @hide */
2939     @TestApi
2940     public static final int OPERATION_SET_APPLICATION_RESTRICTIONS = 16;
2941     /** @hide */
2942     @TestApi
2943     public static final int OPERATION_SET_KEEP_UNINSTALLED_PACKAGES = 17;
2944     /** @hide */
2945     @TestApi
2946     public static final int OPERATION_SET_LOCK_TASK_FEATURES = 18;
2947     /** @hide */
2948     @TestApi
2949     public static final int OPERATION_SET_LOCK_TASK_PACKAGES = 19;
2950     /** @hide */
2951     @TestApi
2952     public static final int OPERATION_SET_PACKAGES_SUSPENDED = 20;
2953     /** @hide */
2954     @TestApi
2955     public static final int OPERATION_SET_TRUST_AGENT_CONFIGURATION = 21;
2956     /** @hide */
2957     @TestApi
2958     public static final int OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES = 22;
2959     /** @hide */
2960     @TestApi
2961     public static final int OPERATION_CLEAR_APPLICATION_USER_DATA = 23;
2962     /** @hide */
2963     @TestApi
2964     public static final int OPERATION_INSTALL_CA_CERT = 24;
2965     /** @hide */
2966     @TestApi
2967     public static final int OPERATION_INSTALL_KEY_PAIR = 25;
2968     /** @hide */
2969     @TestApi
2970     public static final int OPERATION_INSTALL_SYSTEM_UPDATE = 26;
2971     /** @hide */
2972     @TestApi
2973     public static final int OPERATION_REMOVE_ACTIVE_ADMIN = 27;
2974     /** @hide */
2975     @TestApi
2976     public static final int OPERATION_REMOVE_KEY_PAIR = 28;
2977     /** @hide */
2978     @TestApi
2979     public static final int OPERATION_REQUEST_BUGREPORT = 29;
2980     /** @hide */
2981     @TestApi
2982     public static final int OPERATION_SET_ALWAYS_ON_VPN_PACKAGE = 30;
2983     /** @hide */
2984     @TestApi
2985     public static final int OPERATION_SET_CAMERA_DISABLED = 31;
2986     /** @hide */
2987     @TestApi
2988     public static final int OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY = 32;
2989     /** @hide */
2990     @TestApi
2991     public static final int OPERATION_SET_GLOBAL_PRIVATE_DNS = 33;
2992     /** @hide */
2993     @TestApi
2994     public static final int OPERATION_SET_LOGOUT_ENABLED = 34;
2995     /** @hide */
2996     @TestApi
2997     public static final int OPERATION_SET_MASTER_VOLUME_MUTED = 35;
2998     /** @hide */
2999     @TestApi
3000     public static final int OPERATION_SET_OVERRIDE_APNS_ENABLED = 36;
3001     /** @hide */
3002     @TestApi
3003     public static final int OPERATION_SET_PERMISSION_GRANT_STATE = 37;
3004     /** @hide */
3005     @TestApi
3006     public static final int OPERATION_SET_PERMISSION_POLICY = 38;
3007     /** @hide */
3008     @TestApi
3009     public static final int OPERATION_SET_RESTRICTIONS_PROVIDER = 39;
3010     /** @hide */
3011     @TestApi
3012     public static final int OPERATION_UNINSTALL_CA_CERT = 40;
3013 
3014     private static final String PREFIX_OPERATION = "OPERATION_";
3015 
3016     /** @hide */
3017     @IntDef(prefix = PREFIX_OPERATION, value = {
3018             OPERATION_LOCK_NOW,
3019             OPERATION_SWITCH_USER,
3020             OPERATION_START_USER_IN_BACKGROUND,
3021             OPERATION_STOP_USER,
3022             OPERATION_CREATE_AND_MANAGE_USER,
3023             OPERATION_REMOVE_USER,
3024             OPERATION_REBOOT,
3025             OPERATION_WIPE_DATA,
3026             OPERATION_LOGOUT_USER,
3027             OPERATION_SET_USER_RESTRICTION,
3028             OPERATION_SET_SYSTEM_SETTING,
3029             OPERATION_SET_KEYGUARD_DISABLED,
3030             OPERATION_SET_STATUS_BAR_DISABLED,
3031             OPERATION_SET_SYSTEM_UPDATE_POLICY,
3032             OPERATION_SET_APPLICATION_HIDDEN,
3033             OPERATION_SET_APPLICATION_RESTRICTIONS,
3034             OPERATION_SET_KEEP_UNINSTALLED_PACKAGES,
3035             OPERATION_SET_LOCK_TASK_FEATURES,
3036             OPERATION_SET_LOCK_TASK_PACKAGES,
3037             OPERATION_SET_PACKAGES_SUSPENDED,
3038             OPERATION_SET_TRUST_AGENT_CONFIGURATION,
3039             OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES,
3040             OPERATION_CLEAR_APPLICATION_USER_DATA,
3041             OPERATION_INSTALL_CA_CERT,
3042             OPERATION_INSTALL_KEY_PAIR,
3043             OPERATION_INSTALL_SYSTEM_UPDATE,
3044             OPERATION_REMOVE_ACTIVE_ADMIN,
3045             OPERATION_REMOVE_KEY_PAIR,
3046             OPERATION_REQUEST_BUGREPORT,
3047             OPERATION_SET_ALWAYS_ON_VPN_PACKAGE,
3048             OPERATION_SET_CAMERA_DISABLED,
3049             OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY,
3050             OPERATION_SET_GLOBAL_PRIVATE_DNS,
3051             OPERATION_SET_LOGOUT_ENABLED,
3052             OPERATION_SET_MASTER_VOLUME_MUTED,
3053             OPERATION_SET_OVERRIDE_APNS_ENABLED,
3054             OPERATION_SET_PERMISSION_GRANT_STATE,
3055             OPERATION_SET_PERMISSION_POLICY,
3056             OPERATION_SET_RESTRICTIONS_PROVIDER,
3057             OPERATION_UNINSTALL_CA_CERT
3058     })
3059     @Retention(RetentionPolicy.SOURCE)
3060     public static @interface DevicePolicyOperation {
3061     }
3062 
3063     /** @hide */
3064     @TestApi
3065     @NonNull
operationToString(@evicePolicyOperation int operation)3066     public static String operationToString(@DevicePolicyOperation int operation) {
3067         return DebugUtils.constantToString(DevicePolicyManager.class, PREFIX_OPERATION, operation);
3068     }
3069 
3070     private static final String PREFIX_OPERATION_SAFETY_REASON = "OPERATION_SAFETY_REASON_";
3071 
3072     /** @hide */
3073     @IntDef(prefix = PREFIX_OPERATION_SAFETY_REASON, value = {
3074             OPERATION_SAFETY_REASON_NONE,
3075             OPERATION_SAFETY_REASON_DRIVING_DISTRACTION
3076     })
3077     @Retention(RetentionPolicy.SOURCE)
3078     public static @interface OperationSafetyReason {
3079     }
3080 
3081     /** @hide */
3082     @TestApi
3083     public static final int OPERATION_SAFETY_REASON_NONE = -1;
3084 
3085     /**
3086      * Indicates that a {@link UnsafeStateException} was thrown because the operation would distract
3087      * the driver of the vehicle.
3088      */
3089     public static final int OPERATION_SAFETY_REASON_DRIVING_DISTRACTION = 1;
3090 
3091     /** @hide */
3092     @NonNull
3093     @TestApi
operationSafetyReasonToString(@perationSafetyReason int reason)3094     public static String operationSafetyReasonToString(@OperationSafetyReason int reason) {
3095         return DebugUtils.constantToString(DevicePolicyManager.class,
3096                 PREFIX_OPERATION_SAFETY_REASON, reason);
3097     }
3098 
3099     /** @hide */
isValidOperationSafetyReason(@perationSafetyReason int reason)3100     public static boolean isValidOperationSafetyReason(@OperationSafetyReason int reason) {
3101         return reason == OPERATION_SAFETY_REASON_DRIVING_DISTRACTION;
3102     }
3103 
3104     /**
3105      * Checks if it's safe to run operations that can be affected by the given {@code reason}.
3106      *
3107      * <p><b>Note:</b> notice that the operation safety state might change between the time this
3108      * method returns and the operation's method is called, so calls to the latter could still throw
3109      * a {@link UnsafeStateException} even when this method returns {@code true}.
3110      *
3111      * @param reason currently, only supported reason is
3112      * {@link #OPERATION_SAFETY_REASON_DRIVING_DISTRACTION}.
3113      *
3114      * @return whether it's safe to run operations that can be affected by the given {@code reason}.
3115      */
3116     // TODO(b/173541467): should it throw SecurityException if caller is not admin?
isSafeOperation(@perationSafetyReason int reason)3117     public boolean isSafeOperation(@OperationSafetyReason int reason) {
3118         throwIfParentInstance("isSafeOperation");
3119         if (mService == null) return false;
3120 
3121         try {
3122             return mService.isSafeOperation(reason);
3123         } catch (RemoteException e) {
3124             throw e.rethrowFromSystemServer();
3125         }
3126     }
3127 
3128     /** @hide */
resetNewUserDisclaimer()3129     public void resetNewUserDisclaimer() {
3130         if (mService != null) {
3131             try {
3132                 mService.resetNewUserDisclaimer();
3133             } catch (RemoteException e) {
3134                 throw e.rethrowFromSystemServer();
3135             }
3136         }
3137     }
3138 
3139     /**
3140      * Return true if the given administrator component is currently active (enabled) in the system.
3141      *
3142      * @param admin The administrator component to check for.
3143      * @return {@code true} if {@code admin} is currently enabled in the system, {@code false}
3144      *         otherwise
3145      */
isAdminActive(@onNull ComponentName admin)3146     public boolean isAdminActive(@NonNull ComponentName admin) {
3147         throwIfParentInstance("isAdminActive");
3148         return isAdminActiveAsUser(admin, myUserId());
3149     }
3150 
3151     /**
3152      * @see #isAdminActive(ComponentName)
3153      * @hide
3154      */
isAdminActiveAsUser(@onNull ComponentName admin, int userId)3155     public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
3156         if (mService != null) {
3157             try {
3158                 return mService.isAdminActive(admin, userId);
3159             } catch (RemoteException e) {
3160                 throw e.rethrowFromSystemServer();
3161             }
3162         }
3163         return false;
3164     }
3165 
3166     /**
3167      * Return true if the given administrator component is currently being removed
3168      * for the user.
3169      * @hide
3170      */
isRemovingAdmin(@onNull ComponentName admin, int userId)3171     public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
3172         if (mService != null) {
3173             try {
3174                 return mService.isRemovingAdmin(admin, userId);
3175             } catch (RemoteException e) {
3176                 throw e.rethrowFromSystemServer();
3177             }
3178         }
3179         return false;
3180     }
3181 
3182     /**
3183      * Return a list of all currently active device administrators' component
3184      * names.  If there are no administrators {@code null} may be
3185      * returned.
3186      */
getActiveAdmins()3187     public @Nullable List<ComponentName> getActiveAdmins() {
3188         throwIfParentInstance("getActiveAdmins");
3189         return getActiveAdminsAsUser(myUserId());
3190     }
3191 
3192     /**
3193      * @see #getActiveAdmins()
3194      * @hide
3195      */
3196     @UnsupportedAppUsage
getActiveAdminsAsUser(int userId)3197     public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) {
3198         if (mService != null) {
3199             try {
3200                 return mService.getActiveAdmins(userId);
3201             } catch (RemoteException e) {
3202                 throw e.rethrowFromSystemServer();
3203             }
3204         }
3205         return null;
3206     }
3207 
3208     /**
3209      * Used by package administration code to determine if a package can be stopped
3210      * or uninstalled.
3211      * @hide
3212      */
3213     @SystemApi
3214     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
packageHasActiveAdmins(String packageName)3215     public boolean packageHasActiveAdmins(String packageName) {
3216         return packageHasActiveAdmins(packageName, myUserId());
3217     }
3218 
3219     /**
3220      * Used by package administration code to determine if a package can be stopped
3221      * or uninstalled.
3222      * @hide
3223      */
3224     @UnsupportedAppUsage
packageHasActiveAdmins(String packageName, int userId)3225     public boolean packageHasActiveAdmins(String packageName, int userId) {
3226         if (mService != null) {
3227             try {
3228                 return mService.packageHasActiveAdmins(packageName, userId);
3229             } catch (RemoteException e) {
3230                 throw e.rethrowFromSystemServer();
3231             }
3232         }
3233         return false;
3234     }
3235 
3236     /**
3237      * Remove a current administration component.  This can only be called
3238      * by the application that owns the administration component; if you
3239      * try to remove someone else's component, a security exception will be
3240      * thrown.
3241      *
3242      * <p>Note that the operation is not synchronous and the admin might still be active (as
3243      * indicated by {@link #getActiveAdmins()}) by the time this method returns.
3244      *
3245      * @param admin The administration compononent to remove.
3246      * @throws SecurityException if the caller is not in the owner application of {@code admin}.
3247      */
removeActiveAdmin(@onNull ComponentName admin)3248     public void removeActiveAdmin(@NonNull ComponentName admin) {
3249         throwIfParentInstance("removeActiveAdmin");
3250         if (mService != null) {
3251             try {
3252                 mService.removeActiveAdmin(admin, myUserId());
3253             } catch (RemoteException e) {
3254                 throw e.rethrowFromSystemServer();
3255             }
3256         }
3257     }
3258 
3259     /**
3260      * Returns true if an administrator has been granted a particular device policy. This can be
3261      * used to check whether the administrator was activated under an earlier set of policies, but
3262      * requires additional policies after an upgrade.
3263      *
3264      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be an
3265      *            active administrator, or an exception will be thrown.
3266      * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
3267      * @throws SecurityException if {@code admin} is not an active administrator.
3268      */
hasGrantedPolicy(@onNull ComponentName admin, int usesPolicy)3269     public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) {
3270         throwIfParentInstance("hasGrantedPolicy");
3271         if (mService != null) {
3272             try {
3273                 return mService.hasGrantedPolicy(admin, usesPolicy, myUserId());
3274             } catch (RemoteException e) {
3275                 throw e.rethrowFromSystemServer();
3276             }
3277         }
3278         return false;
3279     }
3280 
3281     /**
3282      * Returns true if the Profile Challenge is available to use for the given profile user.
3283      *
3284      * @hide
3285      */
isSeparateProfileChallengeAllowed(int userHandle)3286     public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3287         if (mService != null) {
3288             try {
3289                 return mService.isSeparateProfileChallengeAllowed(userHandle);
3290             } catch (RemoteException e) {
3291                 throw e.rethrowFromSystemServer();
3292             }
3293         }
3294         return false;
3295     }
3296 
3297     /**
3298      * Constant for {@link #setPasswordQuality}: the policy has no requirements
3299      * for the password.  Note that quality constants are ordered so that higher
3300      * values are more restrictive.
3301      */
3302     public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
3303 
3304     /**
3305      * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
3306      * recognition technology.  This implies technologies that can recognize the identity of
3307      * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
3308      * Note that quality constants are ordered so that higher values are more restrictive.
3309      */
3310     public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
3311 
3312     /**
3313      * Constant for {@link #setPasswordQuality}: the policy requires some kind
3314      * of password or pattern, but doesn't care what it is. Note that quality constants
3315      * are ordered so that higher values are more restrictive.
3316      */
3317     public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
3318 
3319     /**
3320      * Constant for {@link #setPasswordQuality}: the user must have entered a
3321      * password containing at least numeric characters.  Note that quality
3322      * constants are ordered so that higher values are more restrictive.
3323      */
3324     public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
3325 
3326     /**
3327      * Constant for {@link #setPasswordQuality}: the user must have entered a
3328      * password containing at least numeric characters with no repeating (4444)
3329      * or ordered (1234, 4321, 2468) sequences.  Note that quality
3330      * constants are ordered so that higher values are more restrictive.
3331      */
3332     public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
3333 
3334     /**
3335      * Constant for {@link #setPasswordQuality}: the user must have entered a
3336      * password containing at least alphabetic (or other symbol) characters.
3337      * Note that quality constants are ordered so that higher values are more
3338      * restrictive.
3339      */
3340     public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
3341 
3342     /**
3343      * Constant for {@link #setPasswordQuality}: the user must have entered a
3344      * password containing at least <em>both></em> numeric <em>and</em>
3345      * alphabetic (or other symbol) characters.  Note that quality constants are
3346      * ordered so that higher values are more restrictive.
3347      */
3348     public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
3349 
3350     /**
3351      * Constant for {@link #setPasswordQuality}: allows the admin to set precisely how many
3352      * characters of various types the password should contain to satisfy the policy. The admin
3353      * should set these requirements via {@link #setPasswordMinimumLetters},
3354      * {@link #setPasswordMinimumNumeric}, {@link #setPasswordMinimumSymbols},
3355      * {@link #setPasswordMinimumUpperCase}, {@link #setPasswordMinimumLowerCase},
3356      * {@link #setPasswordMinimumNonLetter}, and {@link #setPasswordMinimumLength}.
3357      * Note that quality constants are ordered so that higher values are more restrictive.
3358      */
3359     public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
3360 
3361     /**
3362      * Constant for {@link #setPasswordQuality}: the user is not allowed to
3363      * modify password. In case this password quality is set, the password is
3364      * managed by a profile owner. The profile owner can set any password,
3365      * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note
3366      * that quality constants are ordered so that higher values are more
3367      * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is
3368      * the highest.
3369      * @hide
3370      */
3371     public static final int PASSWORD_QUALITY_MANAGED = 0x80000;
3372 
3373     /**
3374      * @hide
3375      *
3376      * adb shell dpm set-{device,profile}-owner will normally not allow installing an owner to
3377      * a user with accounts.  {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED}
3378      * and {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} are the account features
3379      * used by authenticator to exempt their accounts from this:
3380      *
3381      * <ul>
3382      *     <li>Non-test-only DO/PO still can't be installed when there are accounts.
3383      *     <p>In order to make an apk test-only, add android:testOnly="true" to the
3384      *     &lt;application&gt; tag in the manifest.
3385      *
3386      *     <li>Test-only DO/PO can be installed even when there are accounts, as long as all the
3387      *     accounts have the {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} feature.
3388      *     Some authenticators claim to have any features, so to detect it, we also check
3389      *     {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} and disallow installing
3390      *     if any of the accounts have it.
3391      * </ul>
3392      */
3393     @SystemApi
3394     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED =
3395             "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED";
3396 
3397     /** @hide See {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} */
3398     @SystemApi
3399     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED =
3400             "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED";
3401 
3402     /**
3403      * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
3404      * manifest element, which declares that the module should be considered a required app for
3405      * managed users.
3406      * <p>Being declared as a required app prevents removal of this package during the
3407      * provisioning process.
3408      * @hide
3409      */
3410     @SystemApi
3411     public static final String REQUIRED_APP_MANAGED_USER = "android.app.REQUIRED_APP_MANAGED_USER";
3412 
3413     /**
3414      * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
3415      * manifest element, which declares that the module should be considered a required app for
3416      * managed devices.
3417      * <p>Being declared as a required app prevents removal of this package during the
3418      * provisioning process.
3419      * @hide
3420      */
3421     @SystemApi
3422     public static final String REQUIRED_APP_MANAGED_DEVICE =
3423             "android.app.REQUIRED_APP_MANAGED_DEVICE";
3424 
3425     /**
3426      * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
3427      * manifest element, which declares that the module should be considered a required app for
3428      * managed profiles.
3429      * <p>Being declared as a required app prevents removal of this package during the
3430      * provisioning process.
3431      * @hide
3432      */
3433     @SystemApi
3434     public static final String REQUIRED_APP_MANAGED_PROFILE =
3435             "android.app.REQUIRED_APP_MANAGED_PROFILE";
3436 
3437     /**
3438      * Called by an application that is administering the device to set the password restrictions it
3439      * is imposing. After setting this, the user will not be able to enter a new password that is
3440      * not at least as restrictive as what has been set. Note that the current password will remain
3441      * until the user has set a new one, so the change does not take place immediately. To prompt
3442      * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
3443      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after calling this method.
3444      * <p>
3445      * Quality constants are ordered so that higher values are more restrictive; thus the highest
3446      * requested quality constant (between the policy set here, the user's preference, and any other
3447      * considerations) is the one that is in effect.
3448      * <p>
3449      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3450      * password is always treated as empty.
3451      * <p>
3452      * The calling device admin must have requested
3453      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3454      * not, a security exception will be thrown.
3455      * <p>
3456      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
3457      * {@link DevicePolicyManager} instance returned by
3458      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3459      * profile. Apps targeting {@link android.os.Build.VERSION_CODES#S} and above, with the
3460      * exception of a profile owner on an organization-owned device (as can be identified by
3461      * {@link #isOrganizationOwnedDeviceWithManagedProfile}), will get a
3462      * {@code IllegalArgumentException} when calling this method on the parent
3463      * {@link DevicePolicyManager} instance.
3464      *
3465      * <p><strong>Note:</strong> Specifying password requirements using this method clears the
3466      * password complexity requirements set using {@link #setRequiredPasswordComplexity(int)}.
3467      * If this method is called on the {@link DevicePolicyManager} instance returned by
3468      * {@link #getParentProfileInstance(ComponentName)}, then password complexity requirements
3469      * set on the primary {@link DevicePolicyManager} must be cleared first by calling
3470      * {@link #setRequiredPasswordComplexity} with {@link #PASSWORD_COMPLEXITY_NONE) first.
3471      *
3472      * <p><string>Note:</strong> this method is ignored on
3473      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
3474      *
3475      * @deprecated Prefer using {@link #setRequiredPasswordComplexity(int)}, to require a password
3476      * that satisfies a complexity level defined by the platform, rather than specifying custom
3477      * password requirement.
3478      * Setting custom, overly-complicated password requirements leads to passwords that are hard
3479      * for users to remember and may not provide any security benefits given as Android uses
3480      * hardware-backed throttling to thwart online and offline brute-forcing of the device's
3481      * screen lock.
3482      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3483      * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED},
3484      *            {@link #PASSWORD_QUALITY_BIOMETRIC_WEAK},
3485      *            {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC},
3486      *            {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
3487      *            {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
3488      * @throws SecurityException if {@code admin} is not an active administrator, if {@code admin}
3489      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} or if the
3490      *             calling app is targeting {@link android.os.Build.VERSION_CODES#S} and above,
3491      *             and is calling the method the {@link DevicePolicyManager} instance returned by
3492      *             {@link #getParentProfileInstance(ComponentName)}.
3493      * @throws IllegalStateException if the caller is trying to set password quality on the parent
3494      *             {@link DevicePolicyManager} instance while password complexity was set on the
3495      *             primary {@link DevicePolicyManager} instance.
3496      */
3497     @Deprecated
setPasswordQuality(@onNull ComponentName admin, int quality)3498     public void setPasswordQuality(@NonNull ComponentName admin, int quality) {
3499         if (mService != null) {
3500             try {
3501                 mService.setPasswordQuality(admin, quality, mParentInstance);
3502             } catch (RemoteException e) {
3503                 throw e.rethrowFromSystemServer();
3504             }
3505         }
3506     }
3507 
3508     /**
3509      * Retrieve the current minimum password quality for a particular admin or all admins that set
3510      * restrictions on this user and its participating profiles. Restrictions on profiles that have
3511      * a separate challenge are not taken into account.
3512      *
3513      * <p>This method can be called on the {@link DevicePolicyManager} instance
3514      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3515      * restrictions on the parent profile.
3516      *
3517      * <p>Note: on devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
3518      * the password is always treated as empty.
3519      *
3520      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3521      *
3522      * @param admin The name of the admin component to check, or {@code null} to aggregate
3523      * all admins.
3524      */
3525     @Deprecated
getPasswordQuality(@ullable ComponentName admin)3526     public int getPasswordQuality(@Nullable ComponentName admin) {
3527         return getPasswordQuality(admin, myUserId());
3528     }
3529 
3530     /** @hide per-user version */
3531     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordQuality(@ullable ComponentName admin, int userHandle)3532     public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) {
3533         if (mService != null) {
3534             try {
3535                 return mService.getPasswordQuality(admin, userHandle, mParentInstance);
3536             } catch (RemoteException e) {
3537                 throw e.rethrowFromSystemServer();
3538             }
3539         }
3540         return PASSWORD_QUALITY_UNSPECIFIED;
3541     }
3542 
3543     /**
3544      * Called by an application that is administering the device to set the minimum allowed password
3545      * length. After setting this, the user will not be able to enter a new password that is not at
3546      * least as restrictive as what has been set. Note that the current password will remain until
3547      * the user has set a new one, so the change does not take place immediately. To prompt the user
3548      * for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
3549      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
3550      * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
3551      * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
3552      * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with
3553      * {@link #setPasswordQuality}. If an app targeting SDK level
3554      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
3555      * password quality to one of these values first, this method will throw
3556      * {@link IllegalStateException}.
3557      * <p>
3558      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3559      * password is always treated as empty.
3560      * <p>
3561      * The calling device admin must have requested
3562      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3563      * not, a security exception will be thrown.
3564      * <p>
3565      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
3566      * {@link DevicePolicyManager} instance returned by
3567      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3568      * profile.
3569      *
3570      * <p><string>Note:</strong> this method is ignored on
3571      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
3572      *
3573      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3574      *
3575      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3576      * @param length The new desired minimum password length. A value of 0 means there is no
3577      *     restriction.
3578      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3579      *     does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3580      * @throws IllegalStateException if the calling app is targeting SDK level
3581      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
3582      *     quality requirement prior to calling this method.
3583      */
3584     @Deprecated
setPasswordMinimumLength(@onNull ComponentName admin, int length)3585     public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
3586         if (mService != null) {
3587             try {
3588                 mService.setPasswordMinimumLength(admin, length, mParentInstance);
3589             } catch (RemoteException e) {
3590                 throw e.rethrowFromSystemServer();
3591             }
3592         }
3593     }
3594 
3595     /**
3596      * Retrieve the current minimum password length for a particular admin or all admins that set
3597      * restrictions on this user and its participating profiles. Restrictions on profiles that have
3598      * a separate challenge are not taken into account.
3599      *
3600      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3601      * password is always treated as empty.
3602      *
3603      * <p>This method can be called on the {@link DevicePolicyManager} instance
3604      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3605      * restrictions on the parent profile.
3606      *
3607      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3608      *
3609      * @param admin The name of the admin component to check, or {@code null} to aggregate
3610      * all admins.
3611      */
3612     @Deprecated
getPasswordMinimumLength(@ullable ComponentName admin)3613     public int getPasswordMinimumLength(@Nullable ComponentName admin) {
3614         return getPasswordMinimumLength(admin, myUserId());
3615     }
3616 
3617     /** @hide per-user version */
3618     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLength(@ullable ComponentName admin, int userHandle)3619     public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) {
3620         if (mService != null) {
3621             try {
3622                 return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance);
3623             } catch (RemoteException e) {
3624                 throw e.rethrowFromSystemServer();
3625             }
3626         }
3627         return 0;
3628     }
3629 
3630     /**
3631      * Called by an application that is administering the device to set the minimum number of upper
3632      * case letters required in the password. After setting this, the user will not be able to enter
3633      * a new password that is not at least as restrictive as what has been set. Note that the
3634      * current password will remain until the user has set a new one, so the change does not take
3635      * place immediately. To prompt the user for a new password, use
3636      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
3637      * setting this value. This constraint is only imposed if the administrator has also requested
3638      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
3639      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
3640      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
3641      * {@link IllegalStateException}. The default value is 0.
3642      * <p>
3643      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3644      * password is always treated as empty.
3645      * <p>
3646      * The calling device admin must have requested
3647      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3648      * not, a security exception will be thrown.
3649      * <p>
3650      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
3651      * {@link DevicePolicyManager} instance returned by
3652      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3653      * profile.
3654      *
3655      * <p><string>Note:</strong> this method is ignored on
3656      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
3657      *
3658      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3659      *
3660      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3661      * @param length The new desired minimum number of upper case letters required in the password.
3662      *            A value of 0 means there is no restriction.
3663      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3664      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3665      * @throws IllegalStateException if the calling app is targeting SDK level
3666      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
3667      *     quality requirement prior to calling this method.
3668      */
3669     @Deprecated
setPasswordMinimumUpperCase(@onNull ComponentName admin, int length)3670     public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
3671         if (mService != null) {
3672             try {
3673                 mService.setPasswordMinimumUpperCase(admin, length, mParentInstance);
3674             } catch (RemoteException e) {
3675                 throw e.rethrowFromSystemServer();
3676             }
3677         }
3678     }
3679 
3680     /**
3681      * Retrieve the current number of upper case letters required in the password
3682      * for a particular admin or all admins that set restrictions on this user and
3683      * its participating profiles. Restrictions on profiles that have a separate challenge
3684      * are not taken into account.
3685      * This is the same value as set by
3686      * {@link #setPasswordMinimumUpperCase(ComponentName, int)}
3687      * and only applies when the password quality is
3688      * {@link #PASSWORD_QUALITY_COMPLEX}.
3689      *
3690      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3691      * password is always treated as empty.
3692      *
3693      * <p>This method can be called on the {@link DevicePolicyManager} instance
3694      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3695      * restrictions on the parent profile.
3696      *
3697      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3698      *
3699      * @param admin The name of the admin component to check, or {@code null} to
3700      *            aggregate all admins.
3701      * @return The minimum number of upper case letters required in the
3702      *         password.
3703      */
3704     @Deprecated
getPasswordMinimumUpperCase(@ullable ComponentName admin)3705     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) {
3706         return getPasswordMinimumUpperCase(admin, myUserId());
3707     }
3708 
3709     /** @hide per-user version */
3710     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumUpperCase(@ullable ComponentName admin, int userHandle)3711     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) {
3712         if (mService != null) {
3713             try {
3714                 return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance);
3715             } catch (RemoteException e) {
3716                 throw e.rethrowFromSystemServer();
3717             }
3718         }
3719         return 0;
3720     }
3721 
3722     /**
3723      * Called by an application that is administering the device to set the minimum number of lower
3724      * case letters required in the password. After setting this, the user will not be able to enter
3725      * a new password that is not at least as restrictive as what has been set. Note that the
3726      * current password will remain until the user has set a new one, so the change does not take
3727      * place immediately. To prompt the user for a new password, use
3728      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
3729      * setting this value. This constraint is only imposed if the administrator has also requested
3730      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
3731      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
3732      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
3733      * {@link IllegalStateException}. The default value is 0.
3734      * <p>
3735      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3736      * password is always treated as empty.
3737      * <p>
3738      * The calling device admin must have requested
3739      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3740      * not, a security exception will be thrown.
3741      * <p>
3742      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
3743      * {@link DevicePolicyManager} instance returned by
3744      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3745      * profile.
3746      *
3747      * <p><string>Note:</strong> this method is ignored on
3748      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
3749      *
3750      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3751      *
3752      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3753      * @param length The new desired minimum number of lower case letters required in the password.
3754      *            A value of 0 means there is no restriction.
3755      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3756      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3757      * @throws IllegalStateException if the calling app is targeting SDK level
3758      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
3759      *     quality requirement prior to calling this method.
3760      */
3761     @Deprecated
setPasswordMinimumLowerCase(@onNull ComponentName admin, int length)3762     public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
3763         if (mService != null) {
3764             try {
3765                 mService.setPasswordMinimumLowerCase(admin, length, mParentInstance);
3766             } catch (RemoteException e) {
3767                 throw e.rethrowFromSystemServer();
3768             }
3769         }
3770     }
3771 
3772     /**
3773      * Retrieve the current number of lower case letters required in the password
3774      * for a particular admin or all admins that set restrictions on this user
3775      * and its participating profiles. Restrictions on profiles that have
3776      * a separate challenge are not taken into account.
3777      * This is the same value as set by
3778      * {@link #setPasswordMinimumLowerCase(ComponentName, int)}
3779      * and only applies when the password quality is
3780      * {@link #PASSWORD_QUALITY_COMPLEX}.
3781      *
3782      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3783      * password is always treated as empty.
3784      *
3785      * <p>This method can be called on the {@link DevicePolicyManager} instance
3786      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3787      * restrictions on the parent profile.
3788      *
3789      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3790      *
3791      * @param admin The name of the admin component to check, or {@code null} to
3792      *            aggregate all admins.
3793      * @return The minimum number of lower case letters required in the
3794      *         password.
3795      */
3796     @Deprecated
getPasswordMinimumLowerCase(@ullable ComponentName admin)3797     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) {
3798         return getPasswordMinimumLowerCase(admin, myUserId());
3799     }
3800 
3801     /** @hide per-user version */
3802     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLowerCase(@ullable ComponentName admin, int userHandle)3803     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) {
3804         if (mService != null) {
3805             try {
3806                 return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance);
3807             } catch (RemoteException e) {
3808                 throw e.rethrowFromSystemServer();
3809             }
3810         }
3811         return 0;
3812     }
3813 
3814     /**
3815      * Called by an application that is administering the device to set the minimum number of
3816      * letters required in the password. After setting this, the user will not be able to enter a
3817      * new password that is not at least as restrictive as what has been set. Note that the current
3818      * password will remain until the user has set a new one, so the change does not take place
3819      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
3820      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
3821      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
3822      * {@link #setPasswordQuality}. If an app targeting SDK level
3823      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
3824      * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
3825      * {@link IllegalStateException}. The default value is 1.
3826      * <p>
3827      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3828      * password is always treated as empty.
3829      * <p>
3830      * The calling device admin must have requested
3831      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3832      * not, a security exception will be thrown.
3833      * <p>
3834      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
3835      * {@link DevicePolicyManager} instance returned by
3836      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3837      * profile.
3838      *
3839      * <p><string>Note:</strong> this method is ignored on
3840      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
3841      *
3842      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3843      *
3844      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3845      * @param length The new desired minimum number of letters required in the password. A value of
3846      *            0 means there is no restriction.
3847      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3848      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3849      * @throws IllegalStateException if the calling app is targeting SDK level
3850      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
3851      *     quality requirement prior to calling this method.
3852      */
3853     @Deprecated
setPasswordMinimumLetters(@onNull ComponentName admin, int length)3854     public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
3855         if (mService != null) {
3856             try {
3857                 mService.setPasswordMinimumLetters(admin, length, mParentInstance);
3858             } catch (RemoteException e) {
3859                 throw e.rethrowFromSystemServer();
3860             }
3861         }
3862     }
3863 
3864     /**
3865      * Retrieve the current number of letters required in the password
3866      * for a particular admin or all admins that set restrictions on this user
3867      * and its participating profiles. Restrictions on profiles that have
3868      * a separate challenge are not taken into account.
3869      * This is the same value as set by
3870      * {@link #setPasswordMinimumLetters(ComponentName, int)}
3871      * and only applies when the password quality is
3872      * {@link #PASSWORD_QUALITY_COMPLEX}.
3873      *
3874      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3875      * password is always treated as empty.
3876      *
3877      * <p>This method can be called on the {@link DevicePolicyManager} instance
3878      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3879      * restrictions on the parent profile.
3880      *
3881      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3882      *
3883      * @param admin The name of the admin component to check, or {@code null} to
3884      *            aggregate all admins.
3885      * @return The minimum number of letters required in the password.
3886      */
3887     @Deprecated
getPasswordMinimumLetters(@ullable ComponentName admin)3888     public int getPasswordMinimumLetters(@Nullable ComponentName admin) {
3889         return getPasswordMinimumLetters(admin, myUserId());
3890     }
3891 
3892     /** @hide per-user version */
3893     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLetters(@ullable ComponentName admin, int userHandle)3894     public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) {
3895         if (mService != null) {
3896             try {
3897                 return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance);
3898             } catch (RemoteException e) {
3899                 throw e.rethrowFromSystemServer();
3900             }
3901         }
3902         return 0;
3903     }
3904 
3905     /**
3906      * Called by an application that is administering the device to set the minimum number of
3907      * numerical digits required in the password. After setting this, the user will not be able to
3908      * enter a new password that is not at least as restrictive as what has been set. Note that the
3909      * current password will remain until the user has set a new one, so the change does not take
3910      * place immediately. To prompt the user for a new password, use
3911      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
3912      * setting this value. This constraint is only imposed if the administrator has also requested
3913      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
3914      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
3915      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
3916      * {@link IllegalStateException}. The default value is 1.
3917      * <p>
3918      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3919      * password is always treated as empty.
3920      * <p>
3921      * The calling device admin must have requested
3922      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3923      * not, a security exception will be thrown.
3924      * <p>
3925      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
3926      * {@link DevicePolicyManager} instance returned by
3927      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3928      * profile.
3929      *
3930      * <p><string>Note:</strong> this method is ignored on
3931      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
3932      *
3933      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3934      *
3935      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3936      * @param length The new desired minimum number of numerical digits required in the password. A
3937      *            value of 0 means there is no restriction.
3938      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3939      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3940      * @throws IllegalStateException if the calling app is targeting SDK level
3941      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
3942      *     quality requirement prior to calling this method.
3943      */
3944     @Deprecated
setPasswordMinimumNumeric(@onNull ComponentName admin, int length)3945     public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
3946         if (mService != null) {
3947             try {
3948                 mService.setPasswordMinimumNumeric(admin, length, mParentInstance);
3949             } catch (RemoteException e) {
3950                 throw e.rethrowFromSystemServer();
3951             }
3952         }
3953     }
3954 
3955     /**
3956      * Retrieve the current number of numerical digits required in the password
3957      * for a particular admin or all admins that set restrictions on this user
3958      * and its participating profiles. Restrictions on profiles that have
3959      * a separate challenge are not taken into account.
3960      * This is the same value as set by
3961      * {@link #setPasswordMinimumNumeric(ComponentName, int)}
3962      * and only applies when the password quality is
3963      * {@link #PASSWORD_QUALITY_COMPLEX}.
3964      *
3965      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3966      * password is always treated as empty.
3967      *
3968      * <p>This method can be called on the {@link DevicePolicyManager} instance
3969      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3970      * restrictions on the parent profile.
3971      *
3972      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
3973      *
3974      * @param admin The name of the admin component to check, or {@code null} to
3975      *            aggregate all admins.
3976      * @return The minimum number of numerical digits required in the password.
3977      */
3978     @Deprecated
getPasswordMinimumNumeric(@ullable ComponentName admin)3979     public int getPasswordMinimumNumeric(@Nullable ComponentName admin) {
3980         return getPasswordMinimumNumeric(admin, myUserId());
3981     }
3982 
3983     /** @hide per-user version */
3984     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumNumeric(@ullable ComponentName admin, int userHandle)3985     public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) {
3986         if (mService != null) {
3987             try {
3988                 return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance);
3989             } catch (RemoteException e) {
3990                 throw e.rethrowFromSystemServer();
3991             }
3992         }
3993         return 0;
3994     }
3995 
3996     /**
3997      * Called by an application that is administering the device to set the minimum number of
3998      * symbols required in the password. After setting this, the user will not be able to enter a
3999      * new password that is not at least as restrictive as what has been set. Note that the current
4000      * password will remain until the user has set a new one, so the change does not take place
4001      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
4002      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
4003      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
4004      * {@link #setPasswordQuality}. If an app targeting SDK level
4005      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
4006      * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4007      * {@link IllegalStateException}. The default value is 1.
4008      * <p>
4009      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4010      * password is always treated as empty.
4011      * <p>
4012      * The calling device admin must have requested
4013      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4014      * not, a security exception will be thrown.
4015      * <p>
4016      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4017      * {@link DevicePolicyManager} instance returned by
4018      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4019      * profile.
4020      *
4021      * <p><string>Note:</strong> this method is ignored on
4022      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4023      *
4024      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4025      *
4026      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4027      * @param length The new desired minimum number of symbols required in the password. A value of
4028      *            0 means there is no restriction.
4029      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4030      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4031      * @throws IllegalStateException if the calling app is targeting SDK level
4032      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4033      *     quality requirement prior to calling this method.
4034      */
4035     @Deprecated
setPasswordMinimumSymbols(@onNull ComponentName admin, int length)4036     public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
4037         if (mService != null) {
4038             try {
4039                 mService.setPasswordMinimumSymbols(admin, length, mParentInstance);
4040             } catch (RemoteException e) {
4041                 throw e.rethrowFromSystemServer();
4042             }
4043         }
4044     }
4045 
4046     /**
4047      * Retrieve the current number of symbols required in the password
4048      * for a particular admin or all admins that set restrictions on this user
4049      * and its participating profiles. Restrictions on profiles that have
4050      * a separate challenge are not taken into account. This is the same value as
4051      * set by {@link #setPasswordMinimumSymbols(ComponentName, int)}
4052      * and only applies when the password quality is
4053      * {@link #PASSWORD_QUALITY_COMPLEX}.
4054      *
4055      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4056      * password is always treated as empty.
4057      *
4058      * <p>This method can be called on the {@link DevicePolicyManager} instance
4059      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4060      * restrictions on the parent profile.
4061      *
4062      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4063      *
4064      * @param admin The name of the admin component to check, or {@code null} to
4065      *            aggregate all admins.
4066      * @return The minimum number of symbols required in the password.
4067      */
4068     @Deprecated
getPasswordMinimumSymbols(@ullable ComponentName admin)4069     public int getPasswordMinimumSymbols(@Nullable ComponentName admin) {
4070         return getPasswordMinimumSymbols(admin, myUserId());
4071     }
4072 
4073     /** @hide per-user version */
4074     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumSymbols(@ullable ComponentName admin, int userHandle)4075     public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) {
4076         if (mService != null) {
4077             try {
4078                 return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance);
4079             } catch (RemoteException e) {
4080                 throw e.rethrowFromSystemServer();
4081             }
4082         }
4083         return 0;
4084     }
4085 
4086     /**
4087      * Called by an application that is administering the device to set the minimum number of
4088      * non-letter characters (numerical digits or symbols) required in the password. After setting
4089      * this, the user will not be able to enter a new password that is not at least as restrictive
4090      * as what has been set. Note that the current password will remain until the user has set a new
4091      * one, so the change does not take place immediately. To prompt the user for a new password,
4092      * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
4093      * setting this value. This constraint is only imposed if the administrator has also requested
4094      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
4095      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
4096      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4097      * {@link IllegalStateException}. The default value is 0.
4098      * <p>
4099      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4100      * password is always treated as empty.
4101      * <p>
4102      * The calling device admin must have requested
4103      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4104      * not, a security exception will be thrown.
4105      * <p>
4106      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4107      * {@link DevicePolicyManager} instance returned by
4108      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4109      * profile.
4110      *
4111      * <p><string>Note:</strong> this method is ignored on
4112      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4113      *
4114      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4115      *
4116      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4117      * @param length The new desired minimum number of letters required in the password. A value of
4118      *            0 means there is no restriction.
4119      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4120      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4121      * @throws IllegalStateException if the calling app is targeting SDK level
4122      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4123      *     quality requirement prior to calling this method.
4124      */
4125     @Deprecated
setPasswordMinimumNonLetter(@onNull ComponentName admin, int length)4126     public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
4127         if (mService != null) {
4128             try {
4129                 mService.setPasswordMinimumNonLetter(admin, length, mParentInstance);
4130             } catch (RemoteException e) {
4131                 throw e.rethrowFromSystemServer();
4132             }
4133         }
4134     }
4135 
4136     /**
4137      * Retrieve the current number of non-letter characters required in the password
4138      * for a particular admin or all admins that set restrictions on this user
4139      * and its participating profiles. Restrictions on profiles that have
4140      * a separate challenge are not taken into account.
4141      * This is the same value as set by
4142      * {@link #setPasswordMinimumNonLetter(ComponentName, int)}
4143      * and only applies when the password quality is
4144      * {@link #PASSWORD_QUALITY_COMPLEX}.
4145      *
4146      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4147      * password is always treated as empty.
4148      *
4149      * <p>This method can be called on the {@link DevicePolicyManager} instance
4150      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4151      * restrictions on the parent profile.
4152      *
4153      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4154      *
4155      * @param admin The name of the admin component to check, or {@code null} to
4156      *            aggregate all admins.
4157      * @return The minimum number of letters required in the password.
4158      */
4159     @Deprecated
getPasswordMinimumNonLetter(@ullable ComponentName admin)4160     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) {
4161         return getPasswordMinimumNonLetter(admin, myUserId());
4162     }
4163 
4164     /** @hide per-user version */
4165     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumNonLetter(@ullable ComponentName admin, int userHandle)4166     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) {
4167         if (mService != null) {
4168             try {
4169                 return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance);
4170             } catch (RemoteException e) {
4171                 throw e.rethrowFromSystemServer();
4172             }
4173         }
4174         return 0;
4175     }
4176 
4177     /**
4178      * Returns minimum PasswordMetrics that satisfies all admin policies.
4179      *
4180      * @hide
4181      */
getPasswordMinimumMetrics(@serIdInt int userHandle)4182     public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle) {
4183         return getPasswordMinimumMetrics(userHandle, false);
4184     }
4185 
4186     /**
4187      * Returns minimum PasswordMetrics that satisfies all admin policies.
4188      * If requested, only consider device-wide admin policies and ignore policies set on the
4189      * managed profile instance (as if the managed profile had separate work challenge).
4190      *
4191      * @hide
4192      */
getPasswordMinimumMetrics(@serIdInt int userHandle, boolean deviceWideOnly)4193     public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle,
4194             boolean deviceWideOnly) {
4195         if (mService != null) {
4196             try {
4197                 return mService.getPasswordMinimumMetrics(userHandle, deviceWideOnly);
4198             } catch (RemoteException e) {
4199                 throw e.rethrowFromSystemServer();
4200             }
4201         }
4202         return null;
4203     }
4204 
4205     /**
4206      * Called by an application that is administering the device to set the length of the password
4207      * history. After setting this, the user will not be able to enter a new password that is the
4208      * same as any password in the history. Note that the current password will remain until the
4209      * user has set a new one, so the change does not take place immediately. To prompt the user for
4210      * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
4211      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value.
4212      * <p>
4213      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4214      * password history length is always 0.
4215      * <p>
4216      * The calling device admin must have requested
4217      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4218      * not, a security exception will be thrown.
4219      * <p>
4220      * This method can be called on the {@link DevicePolicyManager} instance returned by
4221      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4222      * profile.
4223      *
4224      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4225      * @param length The new desired length of password history. A value of 0 means there is no
4226      *            restriction.
4227      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4228      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4229      */
4230     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setPasswordHistoryLength(@onNull ComponentName admin, int length)4231     public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
4232         if (mService != null) {
4233             try {
4234                 mService.setPasswordHistoryLength(admin, length, mParentInstance);
4235             } catch (RemoteException e) {
4236                 throw e.rethrowFromSystemServer();
4237             }
4238         }
4239     }
4240 
4241     /**
4242      * Called by a device admin to set the password expiration timeout. Calling this method will
4243      * restart the countdown for password expiration for the given admin, as will changing the
4244      * device password (for all admins).
4245      * <p>
4246      * The provided timeout is the time delta in ms and will be added to the current time. For
4247      * example, to have the password expire 5 days from now, timeout would be 5 * 86400 * 1000 =
4248      * 432000000 ms for timeout.
4249      * <p>
4250      * To disable password expiration, a value of 0 may be used for timeout.
4251      * <p>
4252      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4253      * password expiration is always disabled.
4254      * <p>
4255      * The calling device admin must have requested
4256      * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this method; if it has
4257      * not, a security exception will be thrown.
4258      * <p>
4259      * Note that setting the password will automatically reset the expiration time for all active
4260      * admins. Active admins do not need to explicitly call this method in that case.
4261      * <p>
4262      * This method can be called on the {@link DevicePolicyManager} instance returned by
4263      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4264      * profile.
4265      *
4266      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4267      * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 means
4268      *            there is no restriction (unlimited).
4269      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4270      *             does not use {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD}
4271      */
4272     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setPasswordExpirationTimeout(@onNull ComponentName admin, long timeout)4273     public void setPasswordExpirationTimeout(@NonNull ComponentName admin, long timeout) {
4274         if (mService != null) {
4275             try {
4276                 mService.setPasswordExpirationTimeout(admin, timeout, mParentInstance);
4277             } catch (RemoteException e) {
4278                 throw e.rethrowFromSystemServer();
4279             }
4280         }
4281     }
4282 
4283     /**
4284      * Get the password expiration timeout for the given admin. The expiration timeout is the
4285      * recurring expiration timeout provided in the call to
4286      * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
4287      * aggregate of all participating policy administrators if {@code admin} is null. Admins that
4288      * have set restrictions on profiles that have a separate challenge are not taken into account.
4289      *
4290      * <p>This method can be called on the {@link DevicePolicyManager} instance
4291      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4292      * restrictions on the parent profile.
4293      *
4294      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4295      * password expiration is always disabled and this method always returns 0.
4296      *
4297      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
4298      * @return The timeout for the given admin or the minimum of all timeouts
4299      */
4300     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordExpirationTimeout(@ullable ComponentName admin)4301     public long getPasswordExpirationTimeout(@Nullable ComponentName admin) {
4302         if (mService != null) {
4303             try {
4304                 return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance);
4305             } catch (RemoteException e) {
4306                 throw e.rethrowFromSystemServer();
4307             }
4308         }
4309         return 0;
4310     }
4311 
4312     /**
4313      * Get the current password expiration time for a particular admin or all admins that set
4314      * restrictions on this user and its participating profiles. Restrictions on profiles that have
4315      * a separate challenge are not taken into account. If admin is {@code null}, then a composite
4316      * of all expiration times is returned - which will be the minimum of all of them.
4317      *
4318      * <p>This method can be called on the {@link DevicePolicyManager} instance
4319      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4320      * the password expiration for the parent profile.
4321      *
4322      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4323      * password expiration is always disabled and this method always returns 0.
4324      *
4325      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
4326      * @return The password expiration time, in milliseconds since epoch.
4327      */
4328     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordExpiration(@ullable ComponentName admin)4329     public long getPasswordExpiration(@Nullable ComponentName admin) {
4330         if (mService != null) {
4331             try {
4332                 return mService.getPasswordExpiration(admin, myUserId(), mParentInstance);
4333             } catch (RemoteException e) {
4334                 throw e.rethrowFromSystemServer();
4335             }
4336         }
4337         return 0;
4338     }
4339 
4340     /**
4341      * Retrieve the current password history length for a particular admin or all admins that
4342      * set restrictions on this user and its participating profiles. Restrictions on profiles that
4343      * have a separate challenge are not taken into account.
4344      *
4345      * <p>This method can be called on the {@link DevicePolicyManager} instance
4346      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4347      * restrictions on the parent profile.
4348      *
4349      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4350      * password history length is always 0.
4351      *
4352      * @param admin The name of the admin component to check, or {@code null} to aggregate
4353      * all admins.
4354      * @return The length of the password history
4355      */
4356     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordHistoryLength(@ullable ComponentName admin)4357     public int getPasswordHistoryLength(@Nullable ComponentName admin) {
4358         return getPasswordHistoryLength(admin, myUserId());
4359     }
4360 
4361     /** @hide per-user version */
4362     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
4363     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordHistoryLength(@ullable ComponentName admin, int userHandle)4364     public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) {
4365         if (mService != null) {
4366             try {
4367                 return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance);
4368             } catch (RemoteException e) {
4369                 throw e.rethrowFromSystemServer();
4370             }
4371         }
4372         return 0;
4373     }
4374 
4375     /**
4376      * Return the maximum password length that the device supports for a
4377      * particular password quality.
4378      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4379      * password is always empty and this method always returns 0.
4380      * @param quality The quality being interrogated.
4381      * @return Returns the maximum length that the user can enter.
4382      */
getPasswordMaximumLength(int quality)4383     public int getPasswordMaximumLength(int quality) {
4384         PackageManager pm = mContext.getPackageManager();
4385         if (!pm.hasSystemFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)) {
4386             return 0;
4387         }
4388         return MAX_PASSWORD_LENGTH;
4389     }
4390 
4391     /**
4392      * Determines whether the calling user's current password meets policy requirements
4393      * (e.g. quality, minimum length). The user must be unlocked to perform this check.
4394      *
4395      * <p>Policy requirements which affect this check can be set by admins of the user, but also
4396      * by the admin of a managed profile associated with the calling user (when the managed profile
4397      * doesn't have a separate work challenge). When a managed profile has a separate work
4398      * challenge, its policy requirements only affect the managed profile.
4399      *
4400      * <p>Depending on the user, this method checks the policy requirement against one of the
4401      * following passwords:
4402      * <ul>
4403      * <li>For the primary user or secondary users: the personal keyguard password.
4404      * <li>For managed profiles: a work challenge if set, otherwise the parent user's personal
4405      *     keyguard password.
4406      * <ul/>
4407      * In other words, it's always checking the requirement against the password that is protecting
4408      * the calling user.
4409      *
4410      * <p>Note that this method considers all policy requirements targeting the password in
4411      * question. For example a profile owner might set a requirement on the parent profile i.e.
4412      * personal keyguard but not on the profile itself. When the device has a weak personal keyguard
4413      * password and no separate work challenge, calling this method will return {@code false}
4414      * despite the profile owner not setting a policy on the profile itself. This is because the
4415      * profile's current password is the personal keyguard password, and it does not meet all policy
4416      * requirements.
4417      *
4418      * <p>Device admins must request {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} before
4419      * calling this method. Note, this policy type is deprecated for device admins in Android 9.0
4420      * (API level 28) or higher.
4421      *
4422      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
4423      * {@link #getParentProfileInstance(ComponentName)} in order to determine if the password set on
4424      * the parent profile is sufficient.
4425      *
4426      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4427      * password is always treated as empty - i.e. this method will always return false on such
4428      * devices, provided any password requirements were set.
4429      *
4430      * @return {@code true} if the password meets the policy requirements, {@code false} otherwise
4431      * @throws SecurityException if the calling application isn't an active admin that uses
4432      *     {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4433      * @throws IllegalStateException if the user isn't unlocked
4434      */
isActivePasswordSufficient()4435     public boolean isActivePasswordSufficient() {
4436         if (mService != null) {
4437             try {
4438                 return mService.isActivePasswordSufficient(myUserId(), mParentInstance);
4439             } catch (RemoteException e) {
4440                 throw e.rethrowFromSystemServer();
4441             }
4442         }
4443         return false;
4444     }
4445 
4446     /**
4447      * Called by profile owner of a managed profile to determine whether the current device password
4448      * meets policy requirements set explicitly device-wide.
4449      * <p> This API is similar to {@link #isActivePasswordSufficient()}, with two notable
4450      * differences:
4451      * <ul>
4452      * <li>this API always targets the device password. As a result it should always be called on
4453      *   the {@link #getParentProfileInstance(ComponentName)} instance.</li>
4454      * <li>password policy requirement set on the managed profile is not taken into consideration
4455      *   by this API, even if the device currently does not have a separate work challenge set.</li>
4456      * </ul>
4457      *
4458      * <p>This API is designed to facilite progressive password enrollment flows when the DPC
4459      * imposes both device and profile password policies. DPC applies profile password policy by
4460      * calling {@link #setPasswordQuality(ComponentName, int)} or
4461      * {@link #setRequiredPasswordComplexity} on the regular {@link DevicePolicyManager} instance,
4462      * while it applies device-wide policy by calling {@link #setRequiredPasswordComplexity} on the
4463      * {@link #getParentProfileInstance(ComponentName)} instance. The DPC can utilize this check to
4464      * guide the user to set a device password first taking into consideration the device-wide
4465      * policy only, and then prompt the user to either upgrade it to be fully compliant, or enroll a
4466      * separate work challenge to satisfy the profile password policy only.
4467      *
4468      * <p>The device user must be unlocked (@link {@link UserManager#isUserUnlocked(UserHandle)})
4469      * to perform this check.
4470      *
4471      * @return {@code true} if the device password meets explicit requirement set on it,
4472      *   {@code false} otherwise.
4473      * @throws SecurityException if the calling application is not a profile owner of a managed
4474      *   profile, or if this API is not called on the parent DevicePolicyManager instance.
4475      * @throws IllegalStateException if the user isn't unlocked
4476      * @see #EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY
4477      */
isActivePasswordSufficientForDeviceRequirement()4478     public boolean isActivePasswordSufficientForDeviceRequirement() {
4479         if (!mParentInstance) {
4480             throw new SecurityException("only callable on the parent instance");
4481         }
4482         if (mService != null) {
4483             try {
4484                 return mService.isActivePasswordSufficientForDeviceRequirement();
4485             } catch (RemoteException e) {
4486                 throw e.rethrowFromSystemServer();
4487             }
4488         }
4489         return false;
4490     }
4491 
4492     /**
4493      * Returns how complex the current user's screen lock is.
4494      *
4495      * <p>Note that when called from a profile which uses an unified challenge with its parent, the
4496      * screen lock complexity of the parent will be returned.
4497      *
4498      * <p>Apps need the {@link permission#REQUEST_PASSWORD_COMPLEXITY} permission to call this
4499      * method. On Android {@link android.os.Build.VERSION_CODES#S} and above, the calling
4500      * application does not need this permission if it is a device owner or a profile owner.
4501      *
4502      * <p>This method can be called on the {@link DevicePolicyManager} instance
4503      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4504      * restrictions on the parent profile.
4505      *
4506      * @throws IllegalStateException if the user is not unlocked.
4507      * @throws SecurityException     if the calling application does not have the permission
4508      *                               {@link permission#REQUEST_PASSWORD_COMPLEXITY}, and is not a
4509      *                               device owner or a profile owner.
4510      */
4511     @PasswordComplexity
4512     @RequiresPermission(android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY)
getPasswordComplexity()4513     public int getPasswordComplexity() {
4514         if (mService == null) {
4515             return PASSWORD_COMPLEXITY_NONE;
4516         }
4517 
4518         try {
4519             return mService.getPasswordComplexity(mParentInstance);
4520         } catch (RemoteException e) {
4521             throw e.rethrowFromSystemServer();
4522         }
4523     }
4524 
4525     /**
4526      * Sets a minimum password complexity requirement for the user's screen lock.
4527      * The complexity level is one of the pre-defined levels, and the user is unable to set a
4528      * password with a lower complexity level.
4529      *
4530      * <p>Note that when called on a profile which uses an unified challenge with its parent, the
4531      * complexity would apply to the unified challenge.
4532      *
4533      * <p>This method can be called on the {@link DevicePolicyManager} instance
4534      * returned by {@link #getParentProfileInstance(ComponentName)} in order to set
4535      * restrictions on the parent profile.
4536      *
4537      * <p><strong>Note:</strong> Specifying password requirements using this method clears any
4538      * password requirements set using the obsolete {@link #setPasswordQuality(ComponentName, int)}
4539      * and any of its associated methods.
4540      * Additionally, if there are password requirements set using the obsolete
4541      * {@link #setPasswordQuality(ComponentName, int)} on the parent {@code DevicePolicyManager}
4542      * instance, they must be cleared by calling {@link #setPasswordQuality(ComponentName, int)}
4543      * with {@link #PASSWORD_QUALITY_UNSPECIFIED} on that instance prior to setting complexity
4544      * requirement for the managed profile.
4545      *
4546      * @throws SecurityException if the calling application is not a device owner or a profile
4547      * owner.
4548      * @throws IllegalArgumentException if the complexity level is not one of the four above.
4549      * @throws IllegalStateException if the caller is trying to set password complexity while there
4550      * are password requirements specified using {@link #setPasswordQuality(ComponentName, int)}
4551      * on the parent {@code DevicePolicyManager} instance.
4552      */
setRequiredPasswordComplexity(@asswordComplexity int passwordComplexity)4553     public void setRequiredPasswordComplexity(@PasswordComplexity int passwordComplexity) {
4554         if (mService == null) {
4555             return;
4556         }
4557 
4558         try {
4559             mService.setRequiredPasswordComplexity(passwordComplexity, mParentInstance);
4560         } catch (RemoteException e) {
4561             throw e.rethrowFromSystemServer();
4562         }
4563     }
4564 
4565 
4566     /**
4567      * Gets the password complexity requirement set by {@link #setRequiredPasswordComplexity(int)},
4568      * for the current user.
4569      *
4570      * <p>The difference between this method and {@link #getPasswordComplexity()} is that this
4571      * method simply returns the value set by {@link #setRequiredPasswordComplexity(int)} while
4572      * {@link #getPasswordComplexity()} returns the complexity of the actual password.
4573      *
4574      * <p>This method can be called on the {@link DevicePolicyManager} instance
4575      * returned by {@link #getParentProfileInstance(ComponentName)} in order to get
4576      * restrictions on the parent profile.
4577      *
4578      * @throws SecurityException if the calling application is not a device owner or a profile
4579      * owner.
4580      */
4581     @PasswordComplexity
getRequiredPasswordComplexity()4582     public int getRequiredPasswordComplexity() {
4583         if (mService == null) {
4584             return PASSWORD_COMPLEXITY_NONE;
4585         }
4586 
4587         try {
4588             return mService.getRequiredPasswordComplexity(mParentInstance);
4589         } catch (RemoteException e) {
4590             throw e.rethrowFromSystemServer();
4591         }
4592     }
4593 
4594     /**
4595      * Returns the password complexity that applies to this user, aggregated from other users if
4596      * necessary (for example, if the DPC has set password complexity requirements on the parent
4597      * profile DPM instance of a managed profile user, they would apply to the primary user on the
4598      * device).
4599      * @hide
4600      */
4601     @PasswordComplexity
getAggregatedPasswordComplexityForUser(int userId)4602     public int getAggregatedPasswordComplexityForUser(int userId) {
4603         return getAggregatedPasswordComplexityForUser(userId, false);
4604     }
4605 
4606     /**
4607      * Returns the password complexity that applies to this user, aggregated from other users if
4608      * necessary (for example, if the DPC has set password complexity requirements on the parent
4609      * profile DPM instance of a managed profile user, they would apply to the primary user on the
4610      * device). If {@code deviceWideOnly} is {@code true}, ignore policies set on the
4611      * managed profile DPM instance (as if the managed profile had separate work challenge).
4612      * @hide
4613      */
4614     @PasswordComplexity
getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly)4615     public int getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly) {
4616         if (mService == null) {
4617             return PASSWORD_COMPLEXITY_NONE;
4618         }
4619 
4620         try {
4621             return mService.getAggregatedPasswordComplexityForUser(userId, deviceWideOnly);
4622         } catch (RemoteException e) {
4623             throw e.rethrowFromSystemServer();
4624         }
4625     }
4626 
4627 
4628     /**
4629      * When called by a profile owner of a managed profile returns true if the profile uses unified
4630      * challenge with its parent user.
4631      *
4632      * <strong>Note</strong>: This method is not concerned with password quality and will return
4633      * false if the profile has empty password as a separate challenge.
4634      *
4635      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4636      * @throws SecurityException if {@code admin} is not a profile owner of a managed profile.
4637      * @see UserManager#DISALLOW_UNIFIED_PASSWORD
4638      */
isUsingUnifiedPassword(@onNull ComponentName admin)4639     public boolean isUsingUnifiedPassword(@NonNull ComponentName admin) {
4640         throwIfParentInstance("isUsingUnifiedPassword");
4641         if (mService != null) {
4642             try {
4643                 return mService.isUsingUnifiedPassword(admin);
4644             } catch (RemoteException e) {
4645                 throw e.rethrowFromSystemServer();
4646             }
4647         }
4648         return true;
4649     }
4650 
4651     /**
4652      * Returns whether the given user's credential will be sufficient for all password policy
4653      * requirement, once the user's profile has switched to unified challenge.
4654      *
4655      * <p>This is different from {@link #isActivePasswordSufficient()} since once the profile
4656      * switches to unified challenge, policies set explicitly on the profile will start to affect
4657      * the parent user.
4658      * @param userHandle the user whose password requirement will be checked
4659      * @param profileUser the profile user whose lockscreen challenge will be unified.
4660      * @hide
4661      */
isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser)4662     public boolean isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser) {
4663         if (mService != null) {
4664             try {
4665                 return mService.isPasswordSufficientAfterProfileUnification(userHandle,
4666                         profileUser);
4667             } catch (RemoteException e) {
4668                 throw e.rethrowFromSystemServer();
4669             }
4670         }
4671         return false;
4672     }
4673     /**
4674      * Retrieve the number of times the user has failed at entering a password since that last
4675      * successful password entry.
4676      * <p>
4677      * This method can be called on the {@link DevicePolicyManager} instance returned by
4678      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the number of failed
4679      * password attemts for the parent user.
4680      * <p>
4681      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
4682      * to be able to call this method; if it has not, a security exception will be thrown.
4683      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4684      * password is always empty and this method always returns 0.
4685      *
4686      * @return The number of times user has entered an incorrect password since the last correct
4687      *         password entry.
4688      * @throws SecurityException if the calling application does not own an active administrator
4689      *             that uses {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
4690      */
4691     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getCurrentFailedPasswordAttempts()4692     public int getCurrentFailedPasswordAttempts() {
4693         return getCurrentFailedPasswordAttempts(myUserId());
4694     }
4695 
4696     /**
4697      * Retrieve the number of times the given user has failed at entering a
4698      * password since that last successful password entry.
4699      *
4700      * <p>The calling device admin must have requested
4701      * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call this method; if it has
4702      * not and it is not the system uid, a security exception will be thrown.
4703      *
4704      * @hide
4705      */
4706     @UnsupportedAppUsage
getCurrentFailedPasswordAttempts(int userHandle)4707     public int getCurrentFailedPasswordAttempts(int userHandle) {
4708         if (mService != null) {
4709             try {
4710                 return mService.getCurrentFailedPasswordAttempts(userHandle, mParentInstance);
4711             } catch (RemoteException e) {
4712                 throw e.rethrowFromSystemServer();
4713             }
4714         }
4715         return -1;
4716     }
4717 
4718     /**
4719      * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set.
4720      *
4721      * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set.
4722      * @hide
4723      */
getDoNotAskCredentialsOnBoot()4724     public boolean getDoNotAskCredentialsOnBoot() {
4725         if (mService != null) {
4726             try {
4727                 return mService.getDoNotAskCredentialsOnBoot();
4728             } catch (RemoteException e) {
4729                 throw e.rethrowFromSystemServer();
4730             }
4731         }
4732         return false;
4733     }
4734 
4735     /**
4736      * Setting this to a value greater than zero enables a built-in policy that will perform a
4737      * device or profile wipe after too many incorrect device-unlock passwords have been entered.
4738      * This built-in policy combines watching for failed passwords and wiping the device, and
4739      * requires that you request both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
4740      * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
4741      * <p>
4742      * When this policy is set by a device owner, profile owner of an organization-owned device or
4743      * an admin on the primary user, the device will be factory reset after too many incorrect
4744      * password attempts. When set by a profile owner or an admin on a secondary user or a managed
4745      * profile, only the corresponding user or profile will be wiped.
4746      * <p>
4747      * To implement any other policy (e.g. wiping data for a particular application only, erasing or
4748      * revoking credentials, or reporting the failure to a server), you should implement
4749      * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)} instead. Do not
4750      * use this API, because if the maximum count is reached, the device or profile will be wiped
4751      * immediately, and your callback will not be invoked.
4752      * <p>
4753      * This method can be called on the {@link DevicePolicyManager} instance returned by
4754      * {@link #getParentProfileInstance(ComponentName)} in order to set a value on the parent
4755      * profile.
4756      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4757      * password is always empty and this method has no effect - i.e. the policy is not set.
4758      *
4759      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4760      * @param num The number of failed password attempts at which point the device or profile will
4761      *            be wiped.
4762      * @throws SecurityException if {@code admin} is not an active administrator or does not use
4763      *             both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
4764      *             {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}.
4765      */
4766     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setMaximumFailedPasswordsForWipe(@onNull ComponentName admin, int num)4767     public void setMaximumFailedPasswordsForWipe(@NonNull ComponentName admin, int num) {
4768         if (mService != null) {
4769             try {
4770                 mService.setMaximumFailedPasswordsForWipe(admin, num, mParentInstance);
4771             } catch (RemoteException e) {
4772                 throw e.rethrowFromSystemServer();
4773             }
4774         }
4775     }
4776 
4777     /**
4778      * Retrieve the current maximum number of login attempts that are allowed before the device
4779      * or profile is wiped, for a particular admin or all admins that set restrictions on this user
4780      * and its participating profiles. Restrictions on profiles that have a separate challenge are
4781      * not taken into account.
4782      *
4783      * <p>This method can be called on the {@link DevicePolicyManager} instance
4784      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4785      * the value for the parent profile.
4786      *
4787      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4788      * password is always empty and this method returns a default value (0) indicating that the
4789      * policy is not set.
4790      *
4791      * @param admin The name of the admin component to check, or {@code null} to aggregate
4792      * all admins.
4793      */
4794     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin)4795     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) {
4796         return getMaximumFailedPasswordsForWipe(admin, myUserId());
4797     }
4798 
4799     /** @hide per-user version */
4800     @UnsupportedAppUsage
4801     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin, int userHandle)4802     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) {
4803         if (mService != null) {
4804             try {
4805                 return mService.getMaximumFailedPasswordsForWipe(
4806                         admin, userHandle, mParentInstance);
4807             } catch (RemoteException e) {
4808                 throw e.rethrowFromSystemServer();
4809             }
4810         }
4811         return 0;
4812     }
4813 
4814     /**
4815      * Returns the user that will be wiped first when too many failed attempts are made to unlock
4816      * user {@code userHandle}. That user is either the same as {@code userHandle} or belongs to the
4817      * same profile group. When there is no such policy, returns {@code UserHandle.USER_NULL}.
4818      * E.g. managed profile user may be wiped as a result of failed primary profile password
4819      * attempts when using unified challenge. Primary user may be wiped as a result of failed
4820      * password attempts on the managed profile on an organization-owned device.
4821      * @hide Used only by Keyguard
4822      */
4823     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getProfileWithMinimumFailedPasswordsForWipe(int userHandle)4824     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
4825         if (mService != null) {
4826             try {
4827                 return mService.getProfileWithMinimumFailedPasswordsForWipe(
4828                         userHandle, mParentInstance);
4829             } catch (RemoteException e) {
4830                 throw e.rethrowFromSystemServer();
4831             }
4832         }
4833         return UserHandle.USER_NULL;
4834     }
4835 
4836     /**
4837      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't allow other admins
4838      * to change the password again until the user has entered it.
4839      */
4840     public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
4841 
4842     /**
4843      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't ask for user
4844      * credentials on device boot.
4845      * If the flag is set, the device can be booted without asking for user password.
4846      * The absence of this flag does not change the current boot requirements. This flag
4847      * can be set by the device owner only. If the app is not the device owner, the flag
4848      * is ignored. Once the flag is set, it cannot be reverted back without resetting the
4849      * device to factory defaults.
4850      */
4851     public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
4852 
4853     /**
4854      * Force a new password for device unlock (the password needed to access the entire device) or
4855      * the work profile challenge on the current user. This takes effect immediately.
4856      *
4857      * <p> Before {@link android.os.Build.VERSION_CODES#N}, this API is available to device admin,
4858      * profile owner and device owner. Starting from {@link android.os.Build.VERSION_CODES#N},
4859      * legacy device admin (who is not also profile owner or device owner) can only call this
4860      * API to set a new password if there is currently no password set. Profile owner and device
4861      * owner can continue to force change an existing password as long as the target user is
4862      * unlocked, although device owner will not be able to call this API at all if there is also a
4863      * managed profile on the device.
4864      *
4865      * <p> Between {@link android.os.Build.VERSION_CODES#O},
4866      * {@link android.os.Build.VERSION_CODES#P} and {@link android.os.Build.VERSION_CODES#Q},
4867      * profile owner and devices owner targeting SDK level {@link android.os.Build.VERSION_CODES#O}
4868      * or above who attempt to call this API will receive {@link SecurityException}; they are
4869      * encouraged to migrate to the new {@link #resetPasswordWithToken} API instead.
4870      * Profile owner and device owner targeting older SDK levels are not affected: they continue
4871      * to experience the existing behaviour described in the previous paragraph.
4872      *
4873      * <p><em>Starting from {@link android.os.Build.VERSION_CODES#R}, this API is no longer
4874      * supported in most cases.</em> Device owner and profile owner calling
4875      * this API will receive {@link SecurityException} if they target SDK level
4876      * {@link android.os.Build.VERSION_CODES#O} or above, or they will receive a silent failure
4877      * (API returning {@code false}) if they target lower SDK level.
4878      * For legacy device admins, this API throws {@link SecurityException} if they target SDK level
4879      * {@link android.os.Build.VERSION_CODES#N} or above, and returns {@code false} otherwise. Only
4880      * privileged apps holding RESET_PASSWORD permission which are part of
4881      * the system factory image can still call this API to set a new password if there is currently
4882      * no password set. In this case, if the device already has a password, this API will throw
4883      * {@link SecurityException}.
4884      *
4885      * <p>
4886      * The given password must be sufficient for the current password quality and length constraints
4887      * as returned by {@link #getPasswordQuality(ComponentName)} and
4888      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
4889      * it will be rejected and false returned. Note that the password may be a stronger quality
4890      * (containing alphanumeric characters when the requested quality is only numeric), in which
4891      * case the currently active quality will be increased to match.
4892      *
4893      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
4894      * methods does nothing.
4895      * <p>
4896      * The calling device admin must have requested
4897      * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call this method; if it has
4898      * not, a security exception will be thrown.
4899      *
4900      * @param password The new password for the user. Null or empty clears the password.
4901      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
4902      *            {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
4903      * @return Returns true if the password was applied, or false if it is not acceptable for the
4904      *         current constraints.
4905      * @throws SecurityException if the calling application does not own an active administrator
4906      *             that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
4907      * @throws IllegalStateException if the calling user is locked or has a managed profile.
4908      * @deprecated Please use {@link #resetPasswordWithToken} instead.
4909      */
4910     @Deprecated
4911     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
resetPassword(String password, int flags)4912     public boolean resetPassword(String password, int flags) {
4913         throwIfParentInstance("resetPassword");
4914         if (mService != null) {
4915             try {
4916                 return mService.resetPassword(password, flags);
4917             } catch (RemoteException e) {
4918                 throw e.rethrowFromSystemServer();
4919             }
4920         }
4921         return false;
4922     }
4923 
4924     /**
4925      * Called by a profile or device owner to provision a token which can later be used to reset the
4926      * device lockscreen password (if called by device owner), or managed profile challenge (if
4927      * called by profile owner), via {@link #resetPasswordWithToken}.
4928      * <p>
4929      * If the user currently has a lockscreen password, the provisioned token will not be
4930      * immediately usable; it only becomes active after the user performs a confirm credential
4931      * operation, which can be triggered by {@link KeyguardManager#createConfirmDeviceCredentialIntent}.
4932      * If the user has no lockscreen password, the token is activated immediately. In all cases,
4933      * the active state of the current token can be checked by {@link #isResetPasswordTokenActive}.
4934      * For security reasons, un-activated tokens are only stored in memory and will be lost once
4935      * the device reboots. In this case a new token needs to be provisioned again.
4936      * <p>
4937      * Once provisioned and activated, the token will remain effective even if the user changes
4938      * or clears the lockscreen password.
4939      * <p>
4940      * <em>This token is highly sensitive and should be treated at the same level as user
4941      * credentials. In particular, NEVER store this token on device in plaintext. Do not store
4942      * the plaintext token in device-encrypted storage if it will be needed to reset password on
4943      * file-based encryption devices before user unlocks. Consider carefully how any password token
4944      * will be stored on your server and who will need access to them. Tokens may be the subject of
4945      * legal access requests.
4946      * </em>
4947      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4948      * reset token is not set and this method returns false.
4949      *
4950      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4951      * @param token a secure token a least 32-byte long, which must be generated by a
4952      *        cryptographically strong random number generator.
4953      * @return true if the operation is successful, false otherwise.
4954      * @throws SecurityException if admin is not a device or profile owner.
4955      * @throws IllegalArgumentException if the supplied token is invalid.
4956      */
4957     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setResetPasswordToken(ComponentName admin, byte[] token)4958     public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
4959         throwIfParentInstance("setResetPasswordToken");
4960         if (mService != null) {
4961             try {
4962                 return mService.setResetPasswordToken(admin, token);
4963             } catch (RemoteException e) {
4964                 throw e.rethrowFromSystemServer();
4965             }
4966         }
4967         return false;
4968     }
4969 
4970     /**
4971      * Called by a profile or device owner to revoke the current password reset token.
4972      *
4973      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
4974      * method has no effect - the reset token should not have been set in the first place - and
4975      * false is returned.
4976      *
4977      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4978      * @return true if the operation is successful, false otherwise.
4979      * @throws SecurityException if admin is not a device or profile owner.
4980      */
4981     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
clearResetPasswordToken(ComponentName admin)4982     public boolean clearResetPasswordToken(ComponentName admin) {
4983         throwIfParentInstance("clearResetPasswordToken");
4984         if (mService != null) {
4985             try {
4986                 return mService.clearResetPasswordToken(admin);
4987             } catch (RemoteException e) {
4988                 throw e.rethrowFromSystemServer();
4989             }
4990         }
4991         return false;
4992     }
4993 
4994     /**
4995      * Called by a profile or device owner to check if the current reset password token is active.
4996      *
4997      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
4998      * false is always returned.
4999      *
5000      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5001      * @return true if the token is active, false otherwise.
5002      * @throws SecurityException if admin is not a device or profile owner.
5003      * @throws IllegalStateException if no token has been set.
5004      */
5005     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
isResetPasswordTokenActive(ComponentName admin)5006     public boolean isResetPasswordTokenActive(ComponentName admin) {
5007         throwIfParentInstance("isResetPasswordTokenActive");
5008         if (mService != null) {
5009             try {
5010                 return mService.isResetPasswordTokenActive(admin);
5011             } catch (RemoteException e) {
5012                 throw e.rethrowFromSystemServer();
5013             }
5014         }
5015         return false;
5016     }
5017 
5018     /**
5019      * Called by device or profile owner to force set a new device unlock password or a managed
5020      * profile challenge on current user. This takes effect immediately.
5021      * <p>
5022      * Unlike {@link #resetPassword}, this API can change the password even before the user or
5023      * device is unlocked or decrypted. The supplied token must have been previously provisioned via
5024      * {@link #setResetPasswordToken}, and in active state {@link #isResetPasswordTokenActive}.
5025      * <p>
5026      * The given password must be sufficient for the current password quality and length constraints
5027      * as returned by {@link #getPasswordQuality(ComponentName)} and
5028      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
5029      * it will be rejected and false returned. Note that the password may be a stronger quality, for
5030      * example, a password containing alphanumeric characters when the requested quality is only
5031      * numeric.
5032      * <p>
5033      * Calling with a {@code null} or empty password will clear any existing PIN, pattern or
5034      * password if the current password constraints allow it.
5035      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
5036      * calling this methods has no effect - the password is always empty - and false is returned.
5037      *
5038      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5039      * @param password The new password for the user. {@code null} or empty clears the password.
5040      * @param token the password reset token previously provisioned by
5041      *        {@link #setResetPasswordToken}.
5042      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
5043      *        {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
5044      * @return Returns true if the password was applied, or false if it is not acceptable for the
5045      *         current constraints.
5046      * @throws SecurityException if admin is not a device or profile owner.
5047      * @throws IllegalStateException if the provided token is not valid.
5048      */
5049     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
resetPasswordWithToken(@onNull ComponentName admin, String password, byte[] token, int flags)5050     public boolean resetPasswordWithToken(@NonNull ComponentName admin, String password,
5051             byte[] token, int flags) {
5052         throwIfParentInstance("resetPassword");
5053         if (mService != null) {
5054             try {
5055                 return mService.resetPasswordWithToken(admin, password, token, flags);
5056             } catch (RemoteException e) {
5057                 throw e.rethrowFromSystemServer();
5058             }
5059         }
5060         return false;
5061     }
5062 
5063     /**
5064      * Called by an application that is administering the device to set the maximum time for user
5065      * activity until the device will lock. This limits the length that the user can set. It takes
5066      * effect immediately.
5067      * <p>
5068      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
5069      * to be able to call this method; if it has not, a security exception will be thrown.
5070      * <p>
5071      * This method can be called on the {@link DevicePolicyManager} instance returned by
5072      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5073      * profile.
5074      *
5075      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5076      * @param timeMs The new desired maximum time to lock in milliseconds. A value of 0 means there
5077      *            is no restriction.
5078      * @throws SecurityException if {@code admin} is not an active administrator or it does not use
5079      *             {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
5080      */
setMaximumTimeToLock(@onNull ComponentName admin, long timeMs)5081     public void setMaximumTimeToLock(@NonNull ComponentName admin, long timeMs) {
5082         if (mService != null) {
5083             try {
5084                 mService.setMaximumTimeToLock(admin, timeMs, mParentInstance);
5085             } catch (RemoteException e) {
5086                 throw e.rethrowFromSystemServer();
5087             }
5088         }
5089     }
5090 
5091     /**
5092      * Retrieve the current maximum time to unlock for a particular admin or all admins that set
5093      * restrictions on this user and its participating profiles. Restrictions on profiles that have
5094      * a separate challenge are not taken into account.
5095      *
5096      * <p>This method can be called on the {@link DevicePolicyManager} instance
5097      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5098      * restrictions on the parent profile.
5099      *
5100      * @param admin The name of the admin component to check, or {@code null} to aggregate
5101      * all admins.
5102      * @return time in milliseconds for the given admin or the minimum value (strictest) of
5103      * all admins if admin is null. Returns 0 if there are no restrictions.
5104      */
getMaximumTimeToLock(@ullable ComponentName admin)5105     public long getMaximumTimeToLock(@Nullable ComponentName admin) {
5106         return getMaximumTimeToLock(admin, myUserId());
5107     }
5108 
5109     /** @hide per-user version */
5110     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getMaximumTimeToLock(@ullable ComponentName admin, int userHandle)5111     public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) {
5112         if (mService != null) {
5113             try {
5114                 return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance);
5115             } catch (RemoteException e) {
5116                 throw e.rethrowFromSystemServer();
5117             }
5118         }
5119         return 0;
5120     }
5121 
5122     /**
5123      * Called by a device/profile owner to set the timeout after which unlocking with secondary, non
5124      * strong auth (e.g. fingerprint, face, trust agents) times out, i.e. the user has to use a
5125      * strong authentication method like password, pin or pattern.
5126      *
5127      * <p>This timeout is used internally to reset the timer to require strong auth again after
5128      * specified timeout each time it has been successfully used.
5129      *
5130      * <p>Fingerprint can also be disabled altogether using {@link #KEYGUARD_DISABLE_FINGERPRINT}.
5131      *
5132      * <p>Trust agents can also be disabled altogether using {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
5133      *
5134      * <p>The calling device admin must be a device or profile owner. If it is not,
5135      * a {@link SecurityException} will be thrown.
5136      *
5137      * <p>The calling device admin can verify the value it has set by calling
5138      * {@link #getRequiredStrongAuthTimeout(ComponentName)} and passing in its instance.
5139      *
5140      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
5141      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5142      * profile.
5143      *
5144      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
5145      * calling this methods has no effect - i.e. the timeout is not set.
5146      *
5147      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5148      * @param timeoutMs The new timeout in milliseconds, after which the user will have to unlock
5149      *         with strong authentication method. A value of 0 means the admin is not participating
5150      *         in controlling the timeout.
5151      *         The minimum and maximum timeouts are platform-defined and are typically 1 hour and
5152      *         72 hours, respectively. Though discouraged, the admin may choose to require strong
5153      *         auth at all times using {@link #KEYGUARD_DISABLE_FINGERPRINT} and/or
5154      *         {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
5155      *
5156      * @throws SecurityException if {@code admin} is not a device or profile owner.
5157      */
5158     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setRequiredStrongAuthTimeout(@onNull ComponentName admin, long timeoutMs)5159     public void setRequiredStrongAuthTimeout(@NonNull ComponentName admin,
5160             long timeoutMs) {
5161         if (mService != null) {
5162             try {
5163                 mService.setRequiredStrongAuthTimeout(admin, timeoutMs, mParentInstance);
5164             } catch (RemoteException e) {
5165                 throw e.rethrowFromSystemServer();
5166             }
5167         }
5168     }
5169 
5170     /**
5171      * Determine for how long the user will be able to use secondary, non strong auth for
5172      * authentication, since last strong method authentication (password, pin or pattern) was used.
5173      * After the returned timeout the user is required to use strong authentication method.
5174      *
5175      * <p>This method can be called on the {@link DevicePolicyManager} instance
5176      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5177      * restrictions on the parent profile.
5178      *
5179      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
5180      * 0 is returned to indicate that no timeout is configured.
5181      *
5182      * @param admin The name of the admin component to check, or {@code null} to aggregate
5183      *         across all participating admins.
5184      * @return The timeout in milliseconds or 0 if not configured for the provided admin.
5185      */
5186     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getRequiredStrongAuthTimeout(@ullable ComponentName admin)5187     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin) {
5188         return getRequiredStrongAuthTimeout(admin, myUserId());
5189     }
5190 
5191     /** @hide per-user version */
5192     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5193     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getRequiredStrongAuthTimeout(@ullable ComponentName admin, @UserIdInt int userId)5194     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin, @UserIdInt int userId) {
5195         if (mService != null) {
5196             try {
5197                 return mService.getRequiredStrongAuthTimeout(admin, userId, mParentInstance);
5198             } catch (RemoteException e) {
5199                 throw e.rethrowFromSystemServer();
5200             }
5201         }
5202         return DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5203     }
5204 
5205     /**
5206      * Flag for {@link #lockNow(int)}: also evict the user's credential encryption key from the
5207      * keyring. The user's credential will need to be entered again in order to derive the
5208      * credential encryption key that will be stored back in the keyring for future use.
5209      * <p>
5210      * This flag can only be used by a profile owner when locking a managed profile when
5211      * {@link #getStorageEncryptionStatus} returns {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
5212      * <p>
5213      * In order to secure user data, the user will be stopped and restarted so apps should wait
5214      * until they are next run to perform further actions.
5215      */
5216     public static final int FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY = 1;
5217 
5218     /** @hide */
5219     @Retention(RetentionPolicy.SOURCE)
5220     @IntDef(flag = true, prefix = { "FLAG_EVICT_" }, value = {
5221             FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY
5222     })
5223     public @interface LockNowFlag {}
5224 
5225     /**
5226      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
5227      * this call.
5228      * <p>
5229      * This method secures the device in response to an urgent situation, such as a lost or stolen
5230      * device. After this method is called, the device must be unlocked using strong authentication
5231      * (PIN, pattern, or password). This API is intended for use only by device admins.
5232      * <p>
5233      * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have
5234      * the LOCK_DEVICE permission or the device must have the device admin feature; if neither is
5235      * true, then the method will return without completing any action. Before version
5236      * {@link android.os.Build.VERSION_CODES#R}, the device needed the device admin feature,
5237      * regardless of the caller's permissions.
5238      * <p>
5239      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
5240      * to be able to call this method; if it has not, a security exception will be thrown.
5241      * <p>
5242      * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
5243      * the device. Device admins who find the device in this state can lock an otherwise-insecure
5244      * device by first calling {@link #resetPassword} to set the password and then lock the device.
5245      * <p>
5246      * This method can be called on the {@link DevicePolicyManager} instance returned by
5247      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
5248      * <p>
5249      * NOTE: on {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, this
5250      * method doesn't turn off the screen as it would be a driving safety distraction.
5251      * <p>
5252      * Equivalent to calling {@link #lockNow(int)} with no flags.
5253      *
5254      * @throws SecurityException if the calling application does not own an active administrator
5255      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
5256      */
lockNow()5257     public void lockNow() {
5258         lockNow(0);
5259     }
5260 
5261     /**
5262      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
5263      * this call.
5264      * <p>
5265      * This method secures the device in response to an urgent situation, such as a lost or stolen
5266      * device. After this method is called, the device must be unlocked using strong authentication
5267      * (PIN, pattern, or password). This API is intended for use only by device admins.
5268      * <p>
5269      * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have
5270      * the LOCK_DEVICE permission or the device must have the device admin feature; if neither is
5271      * true, then the method will return without completing any action. Before version
5272      * {@link android.os.Build.VERSION_CODES#R}, the device needed the device admin feature,
5273      * regardless of the caller's permissions.
5274      * <p>
5275      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
5276      * to be able to call this method; if it has not, a security exception will be thrown.
5277      * <p>
5278      * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
5279      * the device. Device admins who find the device in this state can lock an otherwise-insecure
5280      * device by first calling {@link #resetPassword} to set the password and then lock the device.
5281      * <p>
5282      * This method can be called on the {@link DevicePolicyManager} instance returned by
5283      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile as
5284      * well as the managed profile.
5285      * <p>
5286      * NOTE: In order to lock the parent profile and evict the encryption key of the managed
5287      * profile, {@link #lockNow()} must be called twice: First, {@link #lockNow()} should be called
5288      * on the {@link DevicePolicyManager} instance returned by
5289      * {@link #getParentProfileInstance(ComponentName)}, then {@link #lockNow(int)} should be
5290      * called on the {@link DevicePolicyManager} instance associated with the managed profile,
5291      * with the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag.
5292      * Calling the method twice in this order ensures that all users are locked and does not
5293      * stop the device admin on the managed profile from issuing a second call to lock its own
5294      * profile.
5295      * <p>
5296      * NOTE: on {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, this
5297      * method doesn't turn off the screen as it would be a driving safety distraction.
5298      *
5299      * @param flags May be 0 or {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}.
5300      * @throws SecurityException if the calling application does not own an active administrator
5301      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} or the
5302      *             {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is passed by an application
5303      *             that is not a profile
5304      *             owner of a managed profile.
5305      * @throws IllegalArgumentException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is
5306      *             passed when locking the parent profile.
5307      * @throws UnsupportedOperationException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}
5308      *             flag is passed when {@link #getStorageEncryptionStatus} does not return
5309      *             {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
5310      */
lockNow(@ockNowFlag int flags)5311     public void lockNow(@LockNowFlag int flags) {
5312         if (mService != null) {
5313             try {
5314                 mService.lockNow(flags, mParentInstance);
5315             } catch (RemoteException e) {
5316                 throw e.rethrowFromSystemServer();
5317             }
5318         }
5319     }
5320 
5321     /**
5322      * Flag for {@link #wipeData(int)}: also erase the device's external
5323      * storage (such as SD cards).
5324      */
5325     public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
5326 
5327     /**
5328      * Flag for {@link #wipeData(int)}: also erase the factory reset protection
5329      * data.
5330      *
5331      * <p>This flag may only be set by device owner admins; if it is set by
5332      * other admins a {@link SecurityException} will be thrown.
5333      */
5334     public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
5335 
5336     /**
5337      * Flag for {@link #wipeData(int)}: also erase the device's eUICC data.
5338      */
5339     public static final int WIPE_EUICC = 0x0004;
5340 
5341     /**
5342      * Flag for {@link #wipeData(int)}: won't show reason for wiping to the user.
5343      */
5344     public static final int WIPE_SILENTLY = 0x0008;
5345 
5346     /**
5347      * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
5348      * other users will remain unaffected. Calling from the primary user will cause the device to
5349      * reboot, erasing all device data - including all the secondary users and their data - while
5350      * booting up.
5351      * <p>
5352      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
5353      * be able to call this method; if it has not, a security exception will be thrown.
5354      *
5355      * If the caller is a profile owner of an organization-owned managed profile, it may
5356      * additionally call this method on the parent instance.
5357      * Calling this method on the parent {@link DevicePolicyManager} instance would wipe the
5358      * entire device, while calling it on the current profile instance would relinquish the device
5359      * for personal use, removing the managed profile and all policies set by the profile owner.
5360      *
5361      * @param flags Bit mask of additional options: currently supported flags are
5362      *            {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA},
5363      *            {@link #WIPE_EUICC} and {@link #WIPE_SILENTLY}.
5364      * @throws SecurityException if the calling application does not own an active administrator
5365      *            that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} or is not granted the
5366      *            {@link android.Manifest.permission#MASTER_CLEAR} permission.
5367      */
wipeData(int flags)5368     public void wipeData(int flags) {
5369         wipeDataInternal(flags, "");
5370     }
5371 
5372     /**
5373      * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
5374      * other users will remain unaffected, the provided reason for wiping data can be shown to
5375      * user. Calling from the primary user will cause the device to reboot, erasing all device data
5376      * - including all the secondary users and their data - while booting up. In this case, we don't
5377      * show the reason to the user since the device would be factory reset.
5378      * <p>
5379      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
5380      * be able to call this method; if it has not, a security exception will be thrown.
5381      *
5382      * If the caller is a profile owner of an organization-owned managed profile, it may
5383      * additionally call this method on the parent instance.
5384      * Calling this method on the parent {@link DevicePolicyManager} instance would wipe the
5385      * entire device, while calling it on the current profile instance would relinquish the device
5386      * for personal use, removing the managed profile and all policies set by the profile owner.
5387      *
5388      * @param flags Bit mask of additional options: currently supported flags are
5389      *            {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA} and
5390      *            {@link #WIPE_EUICC}.
5391      * @param reason a string that contains the reason for wiping data, which can be
5392      *            presented to the user.
5393      * @throws SecurityException if the calling application does not own an active administrator
5394      *            that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} or is not granted the
5395      *            {@link android.Manifest.permission#MASTER_CLEAR} permission.
5396      * @throws IllegalArgumentException if the input reason string is null or empty, or if
5397      *            {@link #WIPE_SILENTLY} is set.
5398      */
wipeData(int flags, @NonNull CharSequence reason)5399     public void wipeData(int flags, @NonNull CharSequence reason) {
5400         Objects.requireNonNull(reason, "reason string is null");
5401         Preconditions.checkStringNotEmpty(reason, "reason string is empty");
5402         Preconditions.checkArgument((flags & WIPE_SILENTLY) == 0, "WIPE_SILENTLY cannot be set");
5403         wipeDataInternal(flags, reason.toString());
5404     }
5405 
5406     /**
5407      * Internal function for both {@link #wipeData(int)} and
5408      * {@link #wipeData(int, CharSequence)} to call.
5409      *
5410      * @see #wipeData(int)
5411      * @see #wipeData(int, CharSequence)
5412      * @hide
5413      */
wipeDataInternal(int flags, @NonNull String wipeReasonForUser)5414     private void wipeDataInternal(int flags, @NonNull String wipeReasonForUser) {
5415         if (mService != null) {
5416             try {
5417                 mService.wipeDataWithReason(flags, wipeReasonForUser, mParentInstance);
5418             } catch (RemoteException e) {
5419                 throw e.rethrowFromSystemServer();
5420             }
5421         }
5422     }
5423 
5424     /**
5425      * Callable by device owner or profile owner of an organization-owned device, to set a
5426      * factory reset protection (FRP) policy. When a new policy is set, the system
5427      * notifies the FRP management agent of a policy change by broadcasting
5428      * {@code ACTION_RESET_PROTECTION_POLICY_CHANGED}.
5429      *
5430      * @param admin  Which {@link DeviceAdminReceiver} this request is associated with.
5431      * @param policy the new FRP policy, or {@code null} to clear the current policy.
5432      * @throws SecurityException if {@code admin} is not a device owner or a profile owner of
5433      *                           an organization-owned device.
5434      * @throws UnsupportedOperationException if factory reset protection is not
5435      *                           supported on the device.
5436      */
setFactoryResetProtectionPolicy(@onNull ComponentName admin, @Nullable FactoryResetProtectionPolicy policy)5437     public void setFactoryResetProtectionPolicy(@NonNull ComponentName admin,
5438             @Nullable FactoryResetProtectionPolicy policy) {
5439         throwIfParentInstance("setFactoryResetProtectionPolicy");
5440         if (mService != null) {
5441             try {
5442                 mService.setFactoryResetProtectionPolicy(admin, policy);
5443             } catch (RemoteException e) {
5444                 throw e.rethrowFromSystemServer();
5445             }
5446         }
5447     }
5448 
5449     /**
5450      * Callable by device owner or profile owner of an organization-owned device, to retrieve
5451      * the current factory reset protection (FRP) policy set previously by
5452      * {@link #setFactoryResetProtectionPolicy}.
5453      * <p>
5454      * This method can also be called by the FRP management agent on device or with the permission
5455      * {@link android.Manifest.permission#MASTER_CLEAR}, in which case, it can pass {@code null}
5456      * as the ComponentName.
5457      *
5458      * @param admin Which {@link DeviceAdminReceiver} this request is associated with or
5459      *              {@code null} if called by the FRP management agent on device or with the
5460      *              permission {@link android.Manifest.permission#MASTER_CLEAR}.
5461      * @return The current FRP policy object or {@code null} if no policy is set.
5462      * @throws SecurityException if {@code admin} is not a device owner, a profile owner of
5463      *                           an organization-owned device or the FRP management agent.
5464      * @throws UnsupportedOperationException if factory reset protection is not
5465      *                           supported on the device.
5466      */
getFactoryResetProtectionPolicy( @ullable ComponentName admin)5467     public @Nullable FactoryResetProtectionPolicy getFactoryResetProtectionPolicy(
5468             @Nullable ComponentName admin) {
5469         throwIfParentInstance("getFactoryResetProtectionPolicy");
5470         if (mService != null) {
5471             try {
5472                 return mService.getFactoryResetProtectionPolicy(admin);
5473             } catch (RemoteException e) {
5474                 throw e.rethrowFromSystemServer();
5475             }
5476         }
5477         return null;
5478     }
5479 
5480     /**
5481      * Called by an application that is administering the device to set the
5482      * global proxy and exclusion list.
5483      * <p>
5484      * The calling device admin must have requested
5485      * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
5486      * this method; if it has not, a security exception will be thrown.
5487      * Only the first device admin can set the proxy. If a second admin attempts
5488      * to set the proxy, the {@link ComponentName} of the admin originally setting the
5489      * proxy will be returned. If successful in setting the proxy, {@code null} will
5490      * be returned.
5491      * The method can be called repeatedly by the device admin alrady setting the
5492      * proxy to update the proxy and exclusion list.
5493      *
5494      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5495      * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
5496      *            Pass Proxy.NO_PROXY to reset the proxy.
5497      * @param exclusionList a list of domains to be excluded from the global proxy.
5498      * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
5499      *            of the device admin that sets the proxy.
5500      * @hide
5501      */
5502     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setGlobalProxy(@onNull ComponentName admin, Proxy proxySpec, List<String> exclusionList )5503     public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
5504             List<String> exclusionList ) {
5505         throwIfParentInstance("setGlobalProxy");
5506         if (proxySpec == null) {
5507             throw new NullPointerException();
5508         }
5509         if (mService != null) {
5510             try {
5511                 String hostSpec;
5512                 String exclSpec;
5513                 if (proxySpec.equals(Proxy.NO_PROXY)) {
5514                     hostSpec = null;
5515                     exclSpec = null;
5516                 } else {
5517                     if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
5518                         throw new IllegalArgumentException();
5519                     }
5520                     final Pair<String, String> proxyParams =
5521                             getProxyParameters(proxySpec, exclusionList);
5522                     hostSpec = proxyParams.first;
5523                     exclSpec = proxyParams.second;
5524                 }
5525                 return mService.setGlobalProxy(admin, hostSpec, exclSpec);
5526             } catch (RemoteException e) {
5527                 throw e.rethrowFromSystemServer();
5528             }
5529         }
5530         return null;
5531     }
5532 
5533     /**
5534      * Build HTTP proxy parameters for {@link IDevicePolicyManager#setGlobalProxy}.
5535      * @throws IllegalArgumentException Invalid proxySpec
5536      * @hide
5537      */
5538     @VisibleForTesting
getProxyParameters(Proxy proxySpec, List<String> exclusionList)5539     public Pair<String, String> getProxyParameters(Proxy proxySpec, List<String> exclusionList) {
5540         InetSocketAddress sa = (InetSocketAddress) proxySpec.address();
5541         String hostName = sa.getHostName();
5542         int port = sa.getPort();
5543         final List<String> trimmedExclList;
5544         if (exclusionList == null) {
5545             trimmedExclList = Collections.emptyList();
5546         } else {
5547             trimmedExclList = new ArrayList<>(exclusionList.size());
5548             for (String exclDomain : exclusionList) {
5549                 trimmedExclList.add(exclDomain.trim());
5550             }
5551         }
5552         final ProxyInfo info = ProxyInfo.buildDirectProxy(hostName, port, trimmedExclList);
5553         // The hostSpec is built assuming that there is a specified port and hostname,
5554         // but ProxyInfo.isValid() accepts 0 / empty as unspecified: also reject them.
5555         if (port == 0 || TextUtils.isEmpty(hostName) || !info.isValid()) {
5556             throw new IllegalArgumentException();
5557         }
5558 
5559         return new Pair<>(hostName + ":" + port, TextUtils.join(",", trimmedExclList));
5560     }
5561 
5562     /**
5563      * Set a network-independent global HTTP proxy. This is not normally what you want for typical
5564      * HTTP proxies - they are generally network dependent. However if you're doing something
5565      * unusual like general internal filtering this may be useful. On a private network where the
5566      * proxy is not accessible, you may break HTTP using this.
5567      * <p>
5568      * This method requires the caller to be the device owner.
5569      * <p>
5570      * This proxy is only a recommendation and it is possible that some apps will ignore it.
5571      * <p>
5572      * Note: The device owner won't be able to set a global HTTP proxy if there are unaffiliated
5573      * secondary users or profiles on the device. It's recommended that affiliation ids are set for
5574      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
5575      *
5576      * @see ProxyInfo
5577      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5578      * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A
5579      *            {@code null} value will clear the global HTTP proxy.
5580      * @throws SecurityException if {@code admin} is not the device owner.
5581      */
setRecommendedGlobalProxy(@onNull ComponentName admin, @Nullable ProxyInfo proxyInfo)5582     public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
5583             proxyInfo) {
5584         throwIfParentInstance("setRecommendedGlobalProxy");
5585         if (mService != null) {
5586             try {
5587                 mService.setRecommendedGlobalProxy(admin, proxyInfo);
5588             } catch (RemoteException e) {
5589                 throw e.rethrowFromSystemServer();
5590             }
5591         }
5592     }
5593 
5594     /**
5595      * Returns the component name setting the global proxy.
5596      * @return ComponentName object of the device admin that set the global proxy, or {@code null}
5597      *         if no admin has set the proxy.
5598      * @hide
5599      */
getGlobalProxyAdmin()5600     public @Nullable ComponentName getGlobalProxyAdmin() {
5601         if (mService != null) {
5602             try {
5603                 return mService.getGlobalProxyAdmin(myUserId());
5604             } catch (RemoteException e) {
5605                 throw e.rethrowFromSystemServer();
5606             }
5607         }
5608         return null;
5609     }
5610 
5611     /**
5612      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
5613      * indicating that encryption is not supported.
5614      */
5615     public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
5616 
5617     /**
5618      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
5619      * indicating that encryption is supported, but is not currently active.
5620      */
5621     public static final int ENCRYPTION_STATUS_INACTIVE = 1;
5622 
5623     /**
5624      * Result code for {@link #getStorageEncryptionStatus}:
5625      * indicating that encryption is not currently active, but is currently
5626      * being activated.  This is only reported by devices that support
5627      * encryption of data and only when the storage is currently
5628      * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
5629      * to become encrypted will never return this value.
5630      */
5631     public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
5632 
5633     /**
5634      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
5635      * indicating that encryption is active.
5636      * <p>
5637      * Also see {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
5638      */
5639     public static final int ENCRYPTION_STATUS_ACTIVE = 3;
5640 
5641     /**
5642      * Result code for {@link #getStorageEncryptionStatus}:
5643      * indicating that encryption is active, but an encryption key has not
5644      * been set by the user.
5645      */
5646     public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
5647 
5648     /**
5649      * Result code for {@link #getStorageEncryptionStatus}:
5650      * indicating that encryption is active and the encryption key is tied to the user or profile.
5651      * <p>
5652      * This value is only returned to apps targeting API level 24 and above. For apps targeting
5653      * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the
5654      * encryption key is specific to the user or profile.
5655      */
5656     public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5;
5657 
5658     /**
5659      * Activity action: begin the process of encrypting data on the device.  This activity should
5660      * be launched after using {@link #setStorageEncryption} to request encryption be activated.
5661      * After resuming from this activity, use {@link #getStorageEncryption}
5662      * to check encryption status.  However, on some devices this activity may never return, as
5663      * it may trigger a reboot and in some cases a complete data wipe of the device.
5664      */
5665     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
5666     public static final String ACTION_START_ENCRYPTION
5667             = "android.app.action.START_ENCRYPTION";
5668 
5669     /**
5670      * Activity action: launch the DPC to check policy compliance. This intent is launched when
5671      * the user taps on the notification about personal apps suspension. When handling this intent
5672      * the DPC must check if personal apps should still be suspended and either unsuspend them or
5673      * instruct the user on how to resolve the noncompliance causing the suspension.
5674      *
5675      * @see #setPersonalAppsSuspended
5676      */
5677     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
5678     public static final String ACTION_CHECK_POLICY_COMPLIANCE =
5679             "android.app.action.CHECK_POLICY_COMPLIANCE";
5680 
5681     /**
5682      * Broadcast action: notify managed provisioning that new managed user is created.
5683      *
5684      * @hide
5685      */
5686     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5687     public static final String ACTION_MANAGED_USER_CREATED =
5688             "android.app.action.MANAGED_USER_CREATED";
5689 
5690     /**
5691      * Broadcast action: notify system that a new (Android) user was added when the device is
5692      * managed by a device owner, so receivers can show the proper disclaimer to the (human) user.
5693      *
5694      * @hide
5695      */
5696     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5697     public static final String ACTION_SHOW_NEW_USER_DISCLAIMER =
5698             "android.app.action.ACTION_SHOW_NEW_USER_DISCLAIMER";
5699 
5700     /**
5701      * Widgets are enabled in keyguard
5702      */
5703     public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
5704 
5705     /**
5706      * Disable all keyguard widgets. Has no effect starting from
5707      * {@link android.os.Build.VERSION_CODES#LOLLIPOP} since keyguard widget is only supported
5708      * on Android versions lower than 5.0.
5709      */
5710     public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
5711 
5712     /**
5713      * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
5714      */
5715     public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
5716 
5717     /**
5718      * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
5719      */
5720     public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
5721 
5722     /**
5723      * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
5724      */
5725     public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
5726 
5727     /**
5728      * Disable trust agents on secure keyguard screens (e.g. PIN/Pattern/Password).
5729      * By setting this flag alone, all trust agents are disabled. If the admin then wants to
5730      * allowlist specific features of some trust agent, {@link #setTrustAgentConfiguration} can be
5731      * used in conjuction to set trust-agent-specific configurations.
5732      */
5733     public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
5734 
5735     /**
5736      * Disable fingerprint authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
5737      */
5738     public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
5739 
5740     /**
5741      * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
5742      * This flag has no effect starting from version {@link android.os.Build.VERSION_CODES#N}
5743      */
5744     public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
5745 
5746     /**
5747      * Disable face authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
5748      */
5749     public static final int KEYGUARD_DISABLE_FACE = 1 << 7;
5750 
5751     /**
5752      * Disable iris authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
5753      */
5754     public static final int KEYGUARD_DISABLE_IRIS = 1 << 8;
5755 
5756     /**
5757      * NOTE: Please remember to update the DevicePolicyManagerTest's testKeyguardDisabledFeatures
5758      * CTS test when adding to the list above.
5759      */
5760 
5761     /**
5762      * Disable all biometric authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
5763      */
5764     public static final int KEYGUARD_DISABLE_BIOMETRICS =
5765             DevicePolicyManager.KEYGUARD_DISABLE_FACE
5766             | DevicePolicyManager.KEYGUARD_DISABLE_IRIS
5767             | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
5768 
5769     /**
5770      * Disable all current and future keyguard customizations.
5771      */
5772     public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
5773 
5774     /**
5775      * Keyguard features that when set on a non-organization-owned managed profile that doesn't
5776      * have its own challenge will affect the profile's parent user. These can also be set on the
5777      * managed profile's parent {@link DevicePolicyManager} instance to explicitly control the
5778      * parent user.
5779      *
5780      * <p>
5781      * Organization-owned managed profile supports disabling additional keyguard features on the
5782      * parent user as defined in {@link #ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY}.
5783      *
5784      * @hide
5785      */
5786     public static final int NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
5787             DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
5788             | DevicePolicyManager.KEYGUARD_DISABLE_BIOMETRICS;
5789 
5790     /**
5791      * Keyguard features that when set by the profile owner of an organization-owned managed
5792      * profile will affect the profile's parent user if set on the managed profile's parent
5793      * {@link DevicePolicyManager} instance.
5794      *
5795      * @hide
5796      */
5797     public static final int ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY =
5798             DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA
5799                     | DevicePolicyManager.KEYGUARD_DISABLE_SECURE_NOTIFICATIONS;
5800 
5801     /**
5802      * Keyguard features that when set on a normal or organization-owned managed profile, have
5803      * the potential to affect the profile's parent user.
5804      *
5805      * @hide
5806      */
5807     public static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
5808             DevicePolicyManager.NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER
5809                     | DevicePolicyManager.ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY;
5810 
5811     /**
5812      * @deprecated This method does not actually modify the storage encryption of the device.
5813      * It has never affected the encryption status of a device.
5814      *
5815      * Called by an application that is administering the device to request that the storage system
5816      * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
5817      * <p>
5818      * When multiple device administrators attempt to control device encryption, the most secure,
5819      * supported setting will always be used. If any device administrator requests device
5820      * encryption, it will be enabled; Conversely, if a device administrator attempts to disable
5821      * device encryption while another device administrator has enabled it, the call to disable will
5822      * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
5823      * <p>
5824      * This policy controls encryption of the secure (application data) storage area. Data written
5825      * to other storage areas may or may not be encrypted, and this policy does not require or
5826      * control the encryption of any other storage areas. There is one exception: If
5827      * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the
5828      * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be
5829      * written to disk within the encrypted storage area.
5830      * <p>
5831      * Important Note: On some devices, it is possible to encrypt storage without requiring the user
5832      * to create a device PIN or Password. In this case, the storage is encrypted, but the
5833      * encryption key may not be fully secured. For maximum security, the administrator should also
5834      * require (and check for) a pattern, PIN, or password.
5835      *
5836      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5837      * @param encrypt true to request encryption, false to release any previous request
5838      * @return the new total request status (for all active admins), or {@link
5839      *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user.
5840      *         Will be one of {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link
5841      *         #ENCRYPTION_STATUS_INACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value
5842      *         of the requests; use {@link #getStorageEncryptionStatus()} to query the actual device
5843      *         state.
5844      *
5845      * @throws SecurityException if {@code admin} is not an active administrator or does not use
5846      *             {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE}
5847      */
5848     @Deprecated
setStorageEncryption(@onNull ComponentName admin, boolean encrypt)5849     public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
5850         throwIfParentInstance("setStorageEncryption");
5851         if (mService != null) {
5852             try {
5853                 return mService.setStorageEncryption(admin, encrypt);
5854             } catch (RemoteException e) {
5855                 throw e.rethrowFromSystemServer();
5856             }
5857         }
5858         return ENCRYPTION_STATUS_UNSUPPORTED;
5859     }
5860 
5861     /**
5862      * @deprecated This method only returns the value set by {@link #setStorageEncryption}.
5863      * It does not actually reflect the storage encryption status.
5864      * Use {@link #getStorageEncryptionStatus} for that.
5865      *
5866      * Called by an application that is administering the device to
5867      * determine the requested setting for secure storage.
5868      *
5869      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
5870      * this will return the requested encryption setting as an aggregate of all active
5871      * administrators.
5872      * @return true if the admin(s) are requesting encryption, false if not.
5873      */
5874     @Deprecated
getStorageEncryption(@ullable ComponentName admin)5875     public boolean getStorageEncryption(@Nullable ComponentName admin) {
5876         throwIfParentInstance("getStorageEncryption");
5877         if (mService != null) {
5878             try {
5879                 return mService.getStorageEncryption(admin, myUserId());
5880             } catch (RemoteException e) {
5881                 throw e.rethrowFromSystemServer();
5882             }
5883         }
5884         return false;
5885     }
5886 
5887     /**
5888      * Called by an application that is administering the device to
5889      * determine the current encryption status of the device.
5890      * <p>
5891      * Depending on the returned status code, the caller may proceed in different
5892      * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
5893      * storage system does not support encryption.  If the
5894      * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
5895      * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
5896      * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
5897      * storage system has enabled encryption but no password is set so further action
5898      * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING},
5899      * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER},
5900      * no further action is required.
5901      *
5902      * @return current status of encryption. The value will be one of
5903      * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
5904      * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5905      * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
5906      */
getStorageEncryptionStatus()5907     public int getStorageEncryptionStatus() {
5908         throwIfParentInstance("getStorageEncryptionStatus");
5909         return getStorageEncryptionStatus(myUserId());
5910     }
5911 
5912     /** @hide per-user version */
5913     @UnsupportedAppUsage
getStorageEncryptionStatus(int userHandle)5914     public int getStorageEncryptionStatus(int userHandle) {
5915         if (mService != null) {
5916             try {
5917                 return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle);
5918             } catch (RemoteException e) {
5919                 throw e.rethrowFromSystemServer();
5920             }
5921         }
5922         return ENCRYPTION_STATUS_UNSUPPORTED;
5923     }
5924 
5925     /**
5926      * Mark a CA certificate as approved by the device user. This means that they have been notified
5927      * of the installation, were made aware of the risks, viewed the certificate and still wanted to
5928      * keep the certificate on the device.
5929      *
5930      * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to
5931      * this certificate.
5932      *
5933      * @hide
5934      */
approveCaCert(String alias, int userHandle, boolean approval)5935     public boolean approveCaCert(String alias, int userHandle, boolean approval) {
5936         if (mService != null) {
5937             try {
5938                 return mService.approveCaCert(alias, userHandle, approval);
5939             } catch (RemoteException e) {
5940                 throw e.rethrowFromSystemServer();
5941             }
5942         }
5943         return false;
5944     }
5945 
5946     /**
5947      * Check whether a CA certificate has been approved by the device user.
5948      *
5949      * @hide
5950      */
isCaCertApproved(String alias, int userHandle)5951     public boolean isCaCertApproved(String alias, int userHandle) {
5952         if (mService != null) {
5953             try {
5954                 return mService.isCaCertApproved(alias, userHandle);
5955             } catch (RemoteException e) {
5956                 throw e.rethrowFromSystemServer();
5957             }
5958         }
5959         return false;
5960     }
5961 
5962     /**
5963      * Installs the given certificate as a user CA.
5964      * <p>
5965      * Inserted user CAs aren't automatically trusted by apps in Android 7.0 (API level 24) and
5966      * higher. App developers can change the default behavior for an app by adding a
5967      * <a href="{@docRoot}training/articles/security-config.html">Security Configuration
5968      * File</a> to the app manifest file.
5969      *
5970      * The caller must be a profile or device owner on that user, or a delegate package given the
5971      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
5972      * security exception will be thrown.
5973      *
5974      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5975      *              {@code null} if calling from a delegated certificate installer.
5976      * @param certBuffer encoded form of the certificate to install.
5977      *
5978      * @return false if the certBuffer cannot be parsed or installation is
5979      *         interrupted, true otherwise.
5980      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5981      *         owner.
5982      * @see #setDelegatedScopes
5983      * @see #DELEGATION_CERT_INSTALL
5984      */
installCaCert(@ullable ComponentName admin, byte[] certBuffer)5985     public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
5986         throwIfParentInstance("installCaCert");
5987         if (mService != null) {
5988             try {
5989                 return mService.installCaCert(admin, mContext.getPackageName(), certBuffer);
5990             } catch (RemoteException e) {
5991                 throw e.rethrowFromSystemServer();
5992             }
5993         }
5994         return false;
5995     }
5996 
5997     /**
5998      * Uninstalls the given certificate from trusted user CAs, if present.
5999      *
6000      * The caller must be a profile or device owner on that user, or a delegate package given the
6001      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
6002      * security exception will be thrown.
6003      *
6004      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6005      *              {@code null} if calling from a delegated certificate installer.
6006      * @param certBuffer encoded form of the certificate to remove.
6007      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6008      *         owner.
6009      * @see #setDelegatedScopes
6010      * @see #DELEGATION_CERT_INSTALL
6011      */
uninstallCaCert(@ullable ComponentName admin, byte[] certBuffer)6012     public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
6013         throwIfParentInstance("uninstallCaCert");
6014         if (mService != null) {
6015             try {
6016                 final String alias = getCaCertAlias(certBuffer);
6017                 mService.uninstallCaCerts(admin, mContext.getPackageName(), new String[] {alias});
6018             } catch (CertificateException e) {
6019                 Log.w(TAG, "Unable to parse certificate", e);
6020             } catch (RemoteException e) {
6021                 throw e.rethrowFromSystemServer();
6022             }
6023         }
6024     }
6025 
6026     /**
6027      * Returns all CA certificates that are currently trusted, excluding system CA certificates.
6028      * If a user has installed any certificates by other means than device policy these will be
6029      * included too.
6030      *
6031      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6032      *              {@code null} if calling from a delegated certificate installer.
6033      * @return a List of byte[] arrays, each encoding one user CA certificate.
6034      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6035      *         owner.
6036      */
getInstalledCaCerts(@ullable ComponentName admin)6037     public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
6038         final List<byte[]> certs = new ArrayList<byte[]>();
6039         throwIfParentInstance("getInstalledCaCerts");
6040         if (mService != null) {
6041             try {
6042                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
6043                 final TrustedCertificateStore certStore = new TrustedCertificateStore();
6044                 for (String alias : certStore.userAliases()) {
6045                     try {
6046                         certs.add(certStore.getCertificate(alias).getEncoded());
6047                     } catch (CertificateException ce) {
6048                         Log.w(TAG, "Could not encode certificate: " + alias, ce);
6049                     }
6050                 }
6051             } catch (RemoteException re) {
6052                 throw re.rethrowFromSystemServer();
6053             }
6054         }
6055         return certs;
6056     }
6057 
6058     /**
6059      * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
6060      * means other than device policy will also be removed, except for system CA certificates.
6061      *
6062      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6063      *              {@code null} if calling from a delegated certificate installer.
6064      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6065      *         owner.
6066      */
uninstallAllUserCaCerts(@ullable ComponentName admin)6067     public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
6068         throwIfParentInstance("uninstallAllUserCaCerts");
6069         if (mService != null) {
6070             try {
6071                 mService.uninstallCaCerts(admin, mContext.getPackageName(),
6072                         new TrustedCertificateStore().userAliases() .toArray(new String[0]));
6073             } catch (RemoteException re) {
6074                 throw re.rethrowFromSystemServer();
6075             }
6076         }
6077     }
6078 
6079     /**
6080      * Returns whether this certificate is installed as a trusted CA.
6081      *
6082      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6083      *              {@code null} if calling from a delegated certificate installer.
6084      * @param certBuffer encoded form of the certificate to look up.
6085      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6086      *         owner.
6087      */
hasCaCertInstalled(@ullable ComponentName admin, byte[] certBuffer)6088     public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
6089         throwIfParentInstance("hasCaCertInstalled");
6090         if (mService != null) {
6091             try {
6092                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
6093                 return getCaCertAlias(certBuffer) != null;
6094             } catch (RemoteException re) {
6095                 throw re.rethrowFromSystemServer();
6096             } catch (CertificateException ce) {
6097                 Log.w(TAG, "Could not parse certificate", ce);
6098             }
6099         }
6100         return false;
6101     }
6102 
6103     /**
6104      * This API can be called by the following to install a certificate and corresponding
6105      * private key:
6106      * <ul>
6107      *    <li>Device owner</li>
6108      *    <li>Profile owner</li>
6109      *    <li>Delegated certificate installer</li>
6110      *    <li>Credential management app</li>
6111      * </ul>
6112      * All apps within the profile will be able to access the certificate and use the private key,
6113      * given direct user approval.
6114      *
6115      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
6116      * can call this API. However, this API sets the key pair as user selectable by default,
6117      * which is not permitted when called by the credential management app. Instead,
6118      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)} should be
6119      * called with {@link #INSTALLKEY_SET_USER_SELECTABLE} not set as a flag.
6120      *
6121      * <p>Access to the installed credentials will not be granted to the caller of this API without
6122      * direct user approval. This is for security - should a certificate installer become
6123      * compromised, certificates it had already installed will be protected.
6124      *
6125      * <p>If the installer must have access to the credentials, call
6126      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead.
6127      *
6128      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
6129      * have been given to access the key and certificates associated with this alias will be
6130      * revoked.
6131      *
6132      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6133      *            {@code null} if calling from a delegated certificate installer.
6134      * @param privKey The private key to install.
6135      * @param cert The certificate to install.
6136      * @param alias The private key alias under which to install the certificate. If a certificate
6137      * with that alias already exists, it will be overwritten.
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 #setDelegatedScopes
6142      * @see #DELEGATION_CERT_INSTALL
6143      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate cert, @NonNull String alias)6144     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
6145             @NonNull Certificate cert, @NonNull String alias) {
6146         return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false);
6147     }
6148 
6149     /**
6150      * This API can be called by the following to install a certificate chain and corresponding
6151      * private key for the leaf certificate:
6152      * <ul>
6153      *    <li>Device owner</li>
6154      *    <li>Profile owner</li>
6155      *    <li>Delegated certificate installer</li>
6156      *    <li>Credential management app</li>
6157      * </ul>
6158      * All apps within the profile will be able to access the certificate chain and use the private
6159      * key, given direct user approval.
6160      *
6161      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
6162      * can call this API. However, this API sets the key pair as user selectable by default,
6163      * which is not permitted when called by the credential management app. Instead,
6164      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)} should be
6165      * called with {@link #INSTALLKEY_SET_USER_SELECTABLE} not set as a flag.
6166      * Note, there can only be a credential management app on an unmanaged device.
6167      *
6168      * <p>The caller of this API may grant itself access to the certificate and private key
6169      * immediately, without user approval. It is a best practice not to request this unless strictly
6170      * necessary since it opens up additional security vulnerabilities.
6171      *
6172      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
6173      * have been given to access the key and certificates associated with this alias will be
6174      * revoked.
6175      *
6176      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6177      *        {@code null} if calling from a delegated certificate installer.
6178      * @param privKey The private key to install.
6179      * @param certs The certificate chain to install. The chain should start with the leaf
6180      *        certificate and include the chain of trust in order. This will be returned by
6181      *        {@link android.security.KeyChain#getCertificateChain}.
6182      * @param alias The private key alias under which to install the certificate. If a certificate
6183      *        with that alias already exists, it will be overwritten.
6184      * @param requestAccess {@code true} to request that the calling app be granted access to the
6185      *        credentials immediately. Otherwise, access to the credentials will be gated by user
6186      *        approval.
6187      * @return {@code true} if the keys were installed, {@code false} otherwise.
6188      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6189      *         owner.
6190      * @see android.security.KeyChain#getCertificateChain
6191      * @see #setDelegatedScopes
6192      * @see #DELEGATION_CERT_INSTALL
6193      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess)6194     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
6195             @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) {
6196         int flags = INSTALLKEY_SET_USER_SELECTABLE;
6197         if (requestAccess) {
6198             flags |= INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
6199         }
6200         return installKeyPair(admin, privKey, certs, alias, flags);
6201     }
6202 
6203     /**
6204      * This API can be called by the following to install a certificate chain and corresponding
6205      * private key for the leaf certificate:
6206      * <ul>
6207      *    <li>Device owner</li>
6208      *    <li>Profile owner</li>
6209      *    <li>Delegated certificate installer</li>
6210      *    <li>Credential management app</li>
6211      * </ul>
6212      * All apps within the profile will be able to access the certificate chain and use the
6213      * private key, given direct user approval (if the user is allowed to select the private key).
6214      *
6215      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
6216      * can call this API. If called by the credential management app:
6217      * <ul>
6218      *    <li>The componentName must be {@code null}r</li>
6219      *    <li>The alias must exist in the credential management app's
6220      *    {@link android.security.AppUriAuthenticationPolicy}</li>
6221      *    <li>The key pair must not be user selectable</li>
6222      * </ul>
6223      * Note, there can only be a credential management app on an unmanaged device.
6224      *
6225      * <p>The caller of this API may grant itself access to the certificate and private key
6226      * immediately, without user approval. It is a best practice not to request this unless strictly
6227      * necessary since it opens up additional security vulnerabilities.
6228      *
6229      * <p>Include {@link #INSTALLKEY_SET_USER_SELECTABLE} in the {@code flags} argument to allow
6230      * the user to select the key from a dialog.
6231      *
6232      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
6233      * have been given to access the key and certificates associated with this alias will be
6234      * revoked.
6235      *
6236      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6237      *        {@code null} if calling from a delegated certificate installer.
6238      * @param privKey The private key to install.
6239      * @param certs The certificate chain to install. The chain should start with the leaf
6240      *        certificate and include the chain of trust in order. This will be returned by
6241      *        {@link android.security.KeyChain#getCertificateChain}.
6242      * @param alias The private key alias under which to install the certificate. If a certificate
6243      *        with that alias already exists, it will be overwritten.
6244      * @param flags Flags to request that the calling app be granted access to the credentials
6245      *        and set the key to be user-selectable. See {@link #INSTALLKEY_SET_USER_SELECTABLE} and
6246      *        {@link #INSTALLKEY_REQUEST_CREDENTIALS_ACCESS}.
6247      * @return {@code true} if the keys were installed, {@code false} otherwise.
6248      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6249      *         owner, or {@code admin} is null but the calling application is not a delegated
6250      *         certificate installer or credential management app.
6251      * @see android.security.KeyChain#getCertificateChain
6252      * @see #setDelegatedScopes
6253      * @see #DELEGATION_CERT_INSTALL
6254      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, int flags)6255     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
6256             @NonNull Certificate[] certs, @NonNull String alias, int flags) {
6257         throwIfParentInstance("installKeyPair");
6258         boolean requestAccess = (flags & INSTALLKEY_REQUEST_CREDENTIALS_ACCESS)
6259                 == INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
6260         boolean isUserSelectable = (flags & INSTALLKEY_SET_USER_SELECTABLE)
6261                 == INSTALLKEY_SET_USER_SELECTABLE;
6262         try {
6263             final byte[] pemCert = Credentials.convertToPem(certs[0]);
6264             byte[] pemChain = null;
6265             if (certs.length > 1) {
6266                 pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length));
6267             }
6268             final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
6269                     .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
6270             return mService.installKeyPair(admin, mContext.getPackageName(), pkcs8Key, pemCert,
6271                     pemChain, alias, requestAccess, isUserSelectable);
6272         } catch (RemoteException e) {
6273             throw e.rethrowFromSystemServer();
6274         } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
6275             Log.w(TAG, "Failed to obtain private key material", e);
6276         } catch (CertificateException | IOException e) {
6277             Log.w(TAG, "Could not pem-encode certificate", e);
6278         }
6279         return false;
6280     }
6281 
6282     /**
6283      * This API can be called by the following to remove a certificate and private key pair
6284      * installed under a given alias:
6285      * <ul>
6286      *    <li>Device owner</li>
6287      *    <li>Profile owner</li>
6288      *    <li>Delegated certificate installer</li>
6289      *    <li>Credential management app</li>
6290      * </ul>
6291      *
6292      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
6293      * can call this API. If called by the credential management app, the componentName must be
6294      * {@code null}. Note, there can only be a credential management app on an unmanaged device.
6295      *
6296      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6297      *        {@code null} if calling from a delegated certificate installer.
6298      * @param alias The private key alias under which the certificate is installed.
6299      * @return {@code true} if the private key alias no longer exists, {@code false} otherwise.
6300      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6301      *         owner, or {@code admin} is null but the calling application is not a delegated
6302      *         certificate installer or credential management app.
6303      * @see #setDelegatedScopes
6304      * @see #DELEGATION_CERT_INSTALL
6305      */
removeKeyPair(@ullable ComponentName admin, @NonNull String alias)6306     public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
6307         throwIfParentInstance("removeKeyPair");
6308         try {
6309             return mService.removeKeyPair(admin, mContext.getPackageName(), alias);
6310         } catch (RemoteException e) {
6311             throw e.rethrowFromSystemServer();
6312         }
6313     }
6314 
6315     // STOPSHIP(b/174298501): clarify the expected return value following generateKeyPair call.
6316     /**
6317      * This API can be called by the following to query whether a certificate and private key are
6318      * installed under a given alias:
6319      * <ul>
6320      *    <li>Device owner</li>
6321      *    <li>Profile owner</li>
6322      *    <li>Delegated certificate installer</li>
6323      *    <li>Credential management app</li>
6324      * </ul>
6325      *
6326      * If called by the credential management app, the alias must exist in the credential
6327      * management app's {@link android.security.AppUriAuthenticationPolicy}.
6328      *
6329      * @param alias The alias under which the key pair is installed.
6330      * @return {@code true} if a key pair with this alias exists, {@code false} otherwise.
6331      * @throws SecurityException if the caller is not a device or profile owner, a delegated
6332      *         certificate installer or the credential management app.
6333      * @see #setDelegatedScopes
6334      * @see #DELEGATION_CERT_INSTALL
6335      */
hasKeyPair(@onNull String alias)6336     public boolean hasKeyPair(@NonNull String alias) {
6337         throwIfParentInstance("hasKeyPair");
6338         try {
6339             return mService.hasKeyPair(mContext.getPackageName(), alias);
6340         } catch (RemoteException e) {
6341             throw e.rethrowFromSystemServer();
6342         }
6343     }
6344 
6345     /**
6346      * This API can be called by the following to generate a new private/public key pair:
6347      * <ul>
6348      *    <li>Device owner</li>
6349      *    <li>Profile owner</li>
6350      *    <li>Delegated certificate installer</li>
6351      *    <li>Credential management app</li>
6352      * </ul>
6353      * If the device supports key generation via secure hardware, this method is useful for
6354      * creating a key in KeyChain that never left the secure hardware. Access to the key is
6355      * controlled the same way as in {@link #installKeyPair}.
6356      *
6357      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
6358      * can call this API. If called by the credential management app, the componentName must be
6359      * {@code null}. Note, there can only be a credential management app on an unmanaged device.
6360      *
6361      * <p>Because this method might take several seconds to complete, it should only be called from
6362      * a worker thread. This method returns {@code null} when called from the main thread.
6363      *
6364      * <p>This method is not thread-safe, calling it from multiple threads at the same time will
6365      * result in undefined behavior. If the calling thread is interrupted while the invocation is
6366      * in-flight, it will eventually terminate and return {@code null}.
6367      *
6368      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
6369      * have been given to access the key and certificates associated with this alias will be
6370      * revoked.
6371      *
6372      * <p>Attestation: to enable attestation, set an attestation challenge in {@code keySpec} via
6373      * {@link KeyGenParameterSpec.Builder#setAttestationChallenge}. By specifying flags to the
6374      * {@code idAttestationFlags} parameter, it is possible to request the device's unique
6375      * identity to be included in the attestation record.
6376      *
6377      * <p>Specific identifiers can be included in the attestation record, and an individual
6378      * attestation certificate can be used to sign the attestation record. To find out if the device
6379      * supports these features, refer to {@link #isDeviceIdAttestationSupported()} and
6380      * {@link #isUniqueDeviceAttestationSupported()}.
6381      *
6382      * <p>Device owner, profile owner, their delegated certificate installer and the credential
6383      * management app can use {@link #ID_TYPE_BASE_INFO} to request inclusion of the general device
6384      * information including manufacturer, model, brand, device and product in the attestation
6385      * record.
6386      * Only device owner, profile owner on an organization-owned device and their delegated
6387      * certificate installers can use {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and
6388      * {@link #ID_TYPE_MEID} to request unique device identifiers to be attested (the serial number,
6389      * IMEI and MEID correspondingly), if supported by the device
6390      * (see {@link #isDeviceIdAttestationSupported()}).
6391      * Additionally, device owner, profile owner on an organization-owned device and their delegated
6392      * certificate installers can also request the attestation record to be signed using an
6393      * individual attestation certificate by specifying the {@link #ID_TYPE_INDIVIDUAL_ATTESTATION}
6394      * flag (if supported by the device, see {@link #isUniqueDeviceAttestationSupported()}).
6395      * <p>
6396      * If any of {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID}
6397      * is set, it is implicitly assumed that {@link #ID_TYPE_BASE_INFO} is also set.
6398      * <p>
6399      * Attestation using {@link #ID_TYPE_INDIVIDUAL_ATTESTATION} can only be requested if
6400      * key generation is done in StrongBox.
6401      *
6402      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6403      *            {@code null} if calling from a delegated certificate installer.
6404      * @param algorithm The key generation algorithm, see {@link java.security.KeyPairGenerator}.
6405      * @param keySpec Specification of the key to generate, see
6406      * {@link java.security.KeyPairGenerator}.
6407      * @param idAttestationFlags A bitmask of the identifiers that should be included in the
6408      *        attestation record ({@code ID_TYPE_BASE_INFO}, {@code ID_TYPE_SERIAL},
6409      *        {@code ID_TYPE_IMEI} and {@code ID_TYPE_MEID}), and
6410      *        {@code ID_TYPE_INDIVIDUAL_ATTESTATION} if the attestation record should be signed
6411      *        using an individual attestation certificate.
6412      *        <p>
6413      *        {@code 0} should be passed in if no device identification is required in the
6414      *        attestation record and the batch attestation certificate should be used.
6415      *        <p>
6416      *        If any flag is specified, then an attestation challenge must be included in the
6417      *        {@code keySpec}.
6418      * @return A non-null {@code AttestedKeyPair} if the key generation succeeded, null otherwise.
6419      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6420      *         owner, or {@code admin} is null but the calling application is not a delegated
6421      *         certificate installer or credential management app. If Device ID attestation is
6422      *         requested (using {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} or
6423      *         {@link #ID_TYPE_MEID}), the caller must be the Device Owner or the Certificate
6424      *         Installer delegate.
6425      * @throws IllegalArgumentException in the following cases:
6426      *         <p>
6427      *         <ul>
6428      *         <li>The alias in {@code keySpec} is empty.</li>
6429      *         <li>The algorithm specification in {@code keySpec} is not
6430      *         {@code RSAKeyGenParameterSpec} or {@code ECGenParameterSpec}.</li>
6431      *         <li>Device ID attestation was requested but the {@code keySpec} does not contain an
6432      *         attestation challenge.</li>
6433      *         </ul>
6434      * @throws UnsupportedOperationException if Device ID attestation or individual attestation
6435      *         was requested but the underlying hardware does not support it.
6436      * @throws StrongBoxUnavailableException if the use of StrongBox for key generation was
6437      *         specified in {@code keySpec} but the device does not have one.
6438      * @see KeyGenParameterSpec.Builder#setAttestationChallenge(byte[])
6439      */
generateKeyPair(@ullable ComponentName admin, @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec, @AttestationIdType int idAttestationFlags)6440     public AttestedKeyPair generateKeyPair(@Nullable ComponentName admin,
6441             @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec,
6442             @AttestationIdType int idAttestationFlags) {
6443         throwIfParentInstance("generateKeyPair");
6444         try {
6445             final ParcelableKeyGenParameterSpec parcelableSpec =
6446                     new ParcelableKeyGenParameterSpec(keySpec);
6447             KeymasterCertificateChain attestationChain = new KeymasterCertificateChain();
6448 
6449             // Translate ID attestation flags to values used by AttestationUtils
6450             final boolean success = mService.generateKeyPair(
6451                     admin, mContext.getPackageName(), algorithm, parcelableSpec,
6452                     idAttestationFlags, attestationChain);
6453             if (!success) {
6454                 Log.e(TAG, "Error generating key via DevicePolicyManagerService.");
6455                 return null;
6456             }
6457 
6458             final String alias = keySpec.getKeystoreAlias();
6459             final KeyPair keyPair = KeyChain.getKeyPair(mContext, alias);
6460             Certificate[] outputChain = null;
6461             try {
6462                 if (AttestationUtils.isChainValid(attestationChain)) {
6463                     outputChain = AttestationUtils.parseCertificateChain(attestationChain);
6464                 }
6465             } catch (KeyAttestationException e) {
6466                 Log.e(TAG, "Error parsing attestation chain for alias " + alias, e);
6467                 mService.removeKeyPair(admin, mContext.getPackageName(), alias);
6468                 return null;
6469             }
6470             return new AttestedKeyPair(keyPair, outputChain);
6471         } catch (RemoteException e) {
6472             throw e.rethrowFromSystemServer();
6473         } catch (KeyChainException e) {
6474             Log.w(TAG, "Failed to generate key", e);
6475         } catch (InterruptedException e) {
6476             Log.w(TAG, "Interrupted while generating key", e);
6477             Thread.currentThread().interrupt();
6478         } catch (ServiceSpecificException e) {
6479             Log.w(TAG, String.format("Key Generation failure: %d", e.errorCode));
6480             switch (e.errorCode) {
6481                 case KEY_GEN_STRONGBOX_UNAVAILABLE:
6482                     throw new StrongBoxUnavailableException("No StrongBox for key generation.");
6483                 default:
6484                     throw new RuntimeException(
6485                             String.format("Unknown error while generating key: %d", e.errorCode));
6486             }
6487         }
6488         return null;
6489     }
6490 
6491     /**
6492      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
6493      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to grant an application access
6494      * to an already-installed (or generated) KeyChain key.
6495      * This is useful (in combination with {@link #installKeyPair} or {@link #generateKeyPair}) to
6496      * let an application call {@link android.security.KeyChain#getPrivateKey} without having to
6497      * call {@link android.security.KeyChain#choosePrivateKeyAlias} first.
6498      *
6499      * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED}
6500      * broadcast when access to a key is granted.
6501      *
6502      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6503      *        {@code null} if calling from a delegated certificate chooser.
6504      * @param alias The alias of the key to grant access to.
6505      * @param packageName The name of the (already installed) package to grant access to.
6506      * @return {@code true} if the grant was set successfully, {@code false} otherwise.
6507      *
6508      * @throws SecurityException if the caller is not a device owner, a profile owner or
6509      *         delegated certificate chooser.
6510      * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if
6511      *         {@code packageName} is not a name of an installed package.
6512      * @see #revokeKeyPairFromApp
6513      */
grantKeyPairToApp(@ullable ComponentName admin, @NonNull String alias, @NonNull String packageName)6514     public boolean grantKeyPairToApp(@Nullable ComponentName admin, @NonNull String alias,
6515             @NonNull String packageName) {
6516         throwIfParentInstance("grantKeyPairToApp");
6517         try {
6518             return mService.setKeyGrantForApp(
6519                     admin, mContext.getPackageName(), alias, packageName, true);
6520         } catch (RemoteException e) {
6521             e.rethrowFromSystemServer();
6522         }
6523         return false;
6524     }
6525 
6526     /**
6527      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
6528      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to query which apps have access
6529      * to a given KeyChain key.
6530      *
6531      * Key are granted on a per-UID basis, so if several apps share the same UID, granting access to
6532      * one of them automatically grants it to others. This method returns a map containing one entry
6533      * per grantee UID. Entries have UIDs as keys and sets of corresponding package names as values.
6534      * In particular, grantee packages that don't share UID with other packages are represented by
6535      * entries having singleton sets as values.
6536      *
6537      * @param alias The alias of the key to grant access to.
6538      * @return apps that have access to a given key, arranged in a map from UID to sets of
6539      *       package names.
6540      *
6541      * @throws SecurityException if the caller is not a device owner, a profile owner or
6542      *         delegated certificate chooser.
6543      * @throws IllegalArgumentException if {@code alias} doesn't correspond to an existing key.
6544      *
6545      * @see #grantKeyPairToApp(ComponentName, String, String)
6546      */
getKeyPairGrants(@onNull String alias)6547     public @NonNull Map<Integer, Set<String>> getKeyPairGrants(@NonNull String alias) {
6548         throwIfParentInstance("getKeyPairGrants");
6549         try {
6550             // The result is wrapped into intermediate parcelable representation.
6551             return mService.getKeyPairGrants(mContext.getPackageName(), alias).getPackagesByUid();
6552         } catch (RemoteException e) {
6553             e.rethrowFromSystemServer();
6554         }
6555         return null;
6556     }
6557 
6558     /**
6559      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
6560      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to revoke an application's
6561      * grant to a KeyChain key pair.
6562      * Calls by the application to {@link android.security.KeyChain#getPrivateKey}
6563      * will fail after the grant is revoked.
6564      *
6565      * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED}
6566      * broadcast when access to a key is revoked.
6567      *
6568      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6569      *        {@code null} if calling from a delegated certificate chooser.
6570      * @param alias The alias of the key to revoke access from.
6571      * @param packageName The name of the (already installed) package to revoke access from.
6572      * @return {@code true} if the grant was revoked successfully, {@code false} otherwise.
6573      *
6574      * @throws SecurityException if the caller is not a device owner, a profile owner or
6575      *         delegated certificate chooser.
6576      * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if
6577      *         {@code packageName} is not a name of an installed package.
6578      * @see #grantKeyPairToApp
6579      */
revokeKeyPairFromApp(@ullable ComponentName admin, @NonNull String alias, @NonNull String packageName)6580     public boolean revokeKeyPairFromApp(@Nullable ComponentName admin, @NonNull String alias,
6581             @NonNull String packageName) {
6582         throwIfParentInstance("revokeKeyPairFromApp");
6583         try {
6584             return mService.setKeyGrantForApp(
6585                     admin, mContext.getPackageName(), alias, packageName, false);
6586         } catch (RemoteException e) {
6587             e.rethrowFromSystemServer();
6588         }
6589         return false;
6590     }
6591 
6592     /**
6593      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
6594      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to allow using a KeyChain key
6595      * pair for authentication to Wifi networks. The key can then be used in configurations passed
6596      * to {@link android.net.wifi.WifiManager#addNetwork}.
6597      *
6598      * @param alias The alias of the key pair.
6599      * @return {@code true} if the operation was set successfully, {@code false} otherwise.
6600      *
6601      * @throws SecurityException if the caller is not a device owner, a profile owner or
6602      *         delegated certificate chooser.
6603      * @see #revokeKeyPairFromWifiAuth
6604      */
grantKeyPairToWifiAuth(@onNull String alias)6605     public boolean grantKeyPairToWifiAuth(@NonNull String alias) {
6606         throwIfParentInstance("grantKeyPairToWifiAuth");
6607         try {
6608             return mService.setKeyGrantToWifiAuth(mContext.getPackageName(), alias, true);
6609         } catch (RemoteException e) {
6610             e.rethrowFromSystemServer();
6611         }
6612         return false;
6613     }
6614 
6615     /**
6616      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
6617      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to deny using a KeyChain key
6618      * pair for authentication to Wifi networks. Configured networks using this key won't be able to
6619      * authenticate.
6620      *
6621      * @param alias The alias of the key pair.
6622      * @return {@code true} if the operation was set successfully, {@code false} otherwise.
6623      *
6624      * @throws SecurityException if the caller is not a device owner, a profile owner or
6625      *         delegated certificate chooser.
6626      * @see #grantKeyPairToWifiAuth
6627      */
revokeKeyPairFromWifiAuth(@onNull String alias)6628     public boolean revokeKeyPairFromWifiAuth(@NonNull String alias) {
6629         throwIfParentInstance("revokeKeyPairFromWifiAuth");
6630         try {
6631             return mService.setKeyGrantToWifiAuth(mContext.getPackageName(), alias, false);
6632         } catch (RemoteException e) {
6633             e.rethrowFromSystemServer();
6634         }
6635         return false;
6636     }
6637 
6638     /**
6639      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
6640      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to query whether a KeyChain key
6641      * pair can be used for authentication to Wifi networks.
6642      *
6643      * @param alias The alias of the key pair.
6644      * @return {@code true} if the key pair can be used, {@code false} otherwise.
6645      *
6646      * @throws SecurityException if the caller is not a device owner, a profile owner or
6647      *         delegated certificate chooser.
6648      * @see #grantKeyPairToWifiAuth
6649      */
isKeyPairGrantedToWifiAuth(@onNull String alias)6650     public boolean isKeyPairGrantedToWifiAuth(@NonNull String alias) {
6651         throwIfParentInstance("isKeyPairGrantedToWifiAuth");
6652         try {
6653             return mService.isKeyPairGrantedToWifiAuth(mContext.getPackageName(), alias);
6654         } catch (RemoteException e) {
6655             e.rethrowFromSystemServer();
6656         }
6657         return false;
6658     }
6659 
6660     /**
6661      * Returns {@code true} if the device supports attestation of device identifiers in addition
6662      * to key attestation. See
6663      * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}
6664      * @return {@code true} if Device ID attestation is supported.
6665      */
isDeviceIdAttestationSupported()6666     public boolean isDeviceIdAttestationSupported() {
6667         PackageManager pm = mContext.getPackageManager();
6668         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ID_ATTESTATION);
6669     }
6670 
6671     /**
6672      * Returns {@code true} if the StrongBox Keymaster implementation on the device was provisioned
6673      * with an individual attestation certificate and can sign attestation records using it (as
6674      * attestation using an individual attestation certificate is a feature only Keymaster
6675      * implementations with StrongBox security level can implement).
6676      * For use prior to calling
6677      * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}.
6678      * @return {@code true} if individual attestation is supported.
6679      */
isUniqueDeviceAttestationSupported()6680     public boolean isUniqueDeviceAttestationSupported() {
6681         PackageManager pm = mContext.getPackageManager();
6682         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_UNIQUE_ATTESTATION);
6683     }
6684 
6685     /**
6686      * This API can be called by the following to associate certificates with a key pair that was
6687      * generated using {@link #generateKeyPair}, and set whether the key is available for the user
6688      * to choose in the certificate selection prompt:
6689      * <ul>
6690      *    <li>Device owner</li>
6691      *    <li>Profile owner</li>
6692      *    <li>Delegated certificate installer</li>
6693      *    <li>Credential management app</li>
6694      * </ul>
6695      *
6696      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
6697      * can call this API. If called by the credential management app, the componentName must be
6698      * {@code null}. Note, there can only be a credential management app on an unmanaged device.
6699      *
6700      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6701      *            {@code null} if calling from a delegated certificate installer.
6702      * @param alias The private key alias under which to install the certificate. The {@code alias}
6703      *        should denote an existing private key. If a certificate with that alias already
6704      *        exists, it will be overwritten.
6705      * @param certs The certificate chain to install. The chain should start with the leaf
6706      *        certificate and include the chain of trust in order. This will be returned by
6707      *        {@link android.security.KeyChain#getCertificateChain}.
6708      * @param isUserSelectable {@code true} to indicate that a user can select this key via the
6709      *        certificate selection prompt, {@code false} to indicate that this key can only be
6710      *        granted access by implementing
6711      *        {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
6712      * @return {@code true} if the provided {@code alias} exists and the certificates has been
6713      *        successfully associated with it, {@code false} otherwise.
6714      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6715      *         owner, or {@code admin} is null but the calling application is not a delegated
6716      *         certificate installer or credential management app.
6717      */
setKeyPairCertificate(@ullable ComponentName admin, @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable)6718     public boolean setKeyPairCertificate(@Nullable ComponentName admin,
6719             @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable) {
6720         throwIfParentInstance("setKeyPairCertificate");
6721         try {
6722             final byte[] pemCert = Credentials.convertToPem(certs.get(0));
6723             byte[] pemChain = null;
6724             if (certs.size() > 1) {
6725                 pemChain = Credentials.convertToPem(
6726                         certs.subList(1, certs.size()).toArray(new Certificate[0]));
6727             }
6728             return mService.setKeyPairCertificate(admin, mContext.getPackageName(), alias, pemCert,
6729                     pemChain, isUserSelectable);
6730         } catch (RemoteException e) {
6731             throw e.rethrowFromSystemServer();
6732         } catch (CertificateException | IOException e) {
6733             Log.w(TAG, "Could not pem-encode certificate", e);
6734         }
6735         return false;
6736     }
6737 
6738 
6739     /**
6740      * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
6741      * doesn't exist.
6742      */
getCaCertAlias(byte[] certBuffer)6743     private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
6744         final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
6745         final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
6746                               new ByteArrayInputStream(certBuffer));
6747         return new TrustedCertificateStore().getCertificateAlias(cert);
6748     }
6749 
6750     /**
6751      * Called by a profile owner or device owner to grant access to privileged certificate
6752      * manipulation APIs to a third-party certificate installer app. Granted APIs include
6753      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
6754      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
6755      * <p>
6756      * Delegated certificate installer is a per-user state. The delegated access is persistent until
6757      * it is later cleared by calling this method with a null value or uninstallling the certificate
6758      * installer.
6759      * <p>
6760      * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
6761      * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
6762      * supplied certificate installer package must be installed when calling this API, otherwise an
6763      * {@link IllegalArgumentException} will be thrown.
6764      *
6765      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6766      * @param installerPackage The package name of the certificate installer which will be given
6767      *            access. If {@code null} is given the current package will be cleared.
6768      * @throws SecurityException if {@code admin} is not a device or a profile owner.
6769      *
6770      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
6771      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
6772      */
6773     @Deprecated
setCertInstallerPackage(@onNull ComponentName admin, @Nullable String installerPackage)6774     public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
6775             installerPackage) throws SecurityException {
6776         throwIfParentInstance("setCertInstallerPackage");
6777         if (mService != null) {
6778             try {
6779                 mService.setCertInstallerPackage(admin, installerPackage);
6780             } catch (RemoteException e) {
6781                 throw e.rethrowFromSystemServer();
6782             }
6783         }
6784     }
6785 
6786     /**
6787      * Called by a profile owner or device owner to retrieve the certificate installer for the user,
6788      * or {@code null} if none is set. If there are multiple delegates this function will return one
6789      * of them.
6790      *
6791      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6792      * @return The package name of the current delegated certificate installer, or {@code null} if
6793      *         none is set.
6794      * @throws SecurityException if {@code admin} is not a device or a profile owner.
6795      *
6796      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
6797      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
6798      */
6799     @Deprecated
getCertInstallerPackage(@onNull ComponentName admin)6800     public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
6801             throws SecurityException {
6802         throwIfParentInstance("getCertInstallerPackage");
6803         if (mService != null) {
6804             try {
6805                 return mService.getCertInstallerPackage(admin);
6806             } catch (RemoteException e) {
6807                 throw e.rethrowFromSystemServer();
6808             }
6809         }
6810         return null;
6811     }
6812 
6813     /**
6814      * Called by a profile owner or device owner to grant access to privileged APIs to another app.
6815      * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*}
6816      * constants.
6817      * <p>
6818      * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be
6819      * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra
6820      * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the
6821      * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag.
6822      * <p>
6823      * Delegated scopes are a per-user state. The delegated access is persistent until it is later
6824      * cleared by calling this method with an empty {@code scopes} list or uninstalling the
6825      * {@code delegatePackage}.
6826      *
6827      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6828      * @param delegatePackage The package name of the app which will be given access.
6829      * @param scopes The groups of privileged APIs whose access should be granted to
6830      *            {@code delegatedPackage}.
6831      * @throws SecurityException if {@code admin} is not a device or a profile owner.
6832      */
setDelegatedScopes(@onNull ComponentName admin, @NonNull String delegatePackage, @NonNull List<String> scopes)6833      public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage,
6834             @NonNull List<String> scopes) {
6835         throwIfParentInstance("setDelegatedScopes");
6836         if (mService != null) {
6837             try {
6838                 mService.setDelegatedScopes(admin, delegatePackage, scopes);
6839             } catch (RemoteException e) {
6840                 throw e.rethrowFromSystemServer();
6841             }
6842         }
6843     }
6844 
6845     /**
6846      * Called by a profile owner or device owner to retrieve a list of the scopes given to a
6847      * delegate package. Other apps can use this method to retrieve their own delegated scopes by
6848      * passing {@code null} for {@code admin} and their own package name as
6849      * {@code delegatedPackage}.
6850      *
6851      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6852      *            {@code null} if the caller is {@code delegatedPackage}.
6853      * @param delegatedPackage The package name of the app whose scopes should be retrieved.
6854      * @return A list containing the scopes given to {@code delegatedPackage}.
6855      * @throws SecurityException if {@code admin} is not a device or a profile owner.
6856      */
6857      @NonNull
getDelegatedScopes(@ullable ComponentName admin, @NonNull String delegatedPackage)6858      public List<String> getDelegatedScopes(@Nullable ComponentName admin,
6859              @NonNull String delegatedPackage) {
6860          throwIfParentInstance("getDelegatedScopes");
6861          if (mService != null) {
6862              try {
6863                  return mService.getDelegatedScopes(admin, delegatedPackage);
6864              } catch (RemoteException e) {
6865                  throw e.rethrowFromSystemServer();
6866              }
6867          }
6868          return null;
6869     }
6870 
6871     /**
6872      * Called by a profile owner or device owner to retrieve a list of delegate packages that were
6873      * granted a delegation scope.
6874      *
6875      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6876      * @param delegationScope The scope whose delegates should be retrieved.
6877      * @return A list of package names of the current delegated packages for
6878                {@code delegationScope}.
6879      * @throws SecurityException if {@code admin} is not a device or a profile owner.
6880      */
6881      @Nullable
getDelegatePackages(@onNull ComponentName admin, @NonNull String delegationScope)6882      public List<String> getDelegatePackages(@NonNull ComponentName admin,
6883              @NonNull String delegationScope) {
6884         throwIfParentInstance("getDelegatePackages");
6885         if (mService != null) {
6886             try {
6887                 return mService.getDelegatePackages(admin, delegationScope);
6888             } catch (RemoteException e) {
6889                 throw e.rethrowFromSystemServer();
6890             }
6891         }
6892         return null;
6893     }
6894 
6895     /**
6896      * Service-specific error code used in implementation of {@code setAlwaysOnVpnPackage} methods.
6897      * @hide
6898      */
6899     public static final int ERROR_VPN_PACKAGE_NOT_FOUND = 1;
6900 
6901     /**
6902      * Called by a device or profile owner to configure an always-on VPN connection through a
6903      * specific application for the current user. This connection is automatically granted and
6904      * persisted after a reboot.
6905      * <p> To support the always-on feature, an app must
6906      * <ul>
6907      *     <li>declare a {@link android.net.VpnService} in its manifest, guarded by
6908      *         {@link android.Manifest.permission#BIND_VPN_SERVICE};</li>
6909      *     <li>target {@link android.os.Build.VERSION_CODES#N API 24} or above; and</li>
6910      *     <li><i>not</i> explicitly opt out of the feature through
6911      *         {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}.</li>
6912      * </ul>
6913      * The call will fail if called with the package name of an unsupported VPN app.
6914      * <p> Enabling lockdown via {@code lockdownEnabled} argument carries the risk that any failure
6915      * of the VPN provider could break networking for all apps. This method clears any lockdown
6916      * allowlist set by {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)}.
6917      * <p> Starting from {@link android.os.Build.VERSION_CODES#S API 31} calling this method with
6918      * {@code vpnPackage} set to {@code null} only removes the existing configuration if it was
6919      * previously created by this admin. To remove VPN configuration created by the user use
6920      * {@link UserManager#DISALLOW_CONFIG_VPN}.
6921      *
6922      * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
6923      *        remove an existing always-on VPN configuration.
6924      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
6925      *        {@code false} otherwise. This has no effect when clearing.
6926      * @throws SecurityException if {@code admin} is not a device or a profile owner.
6927      * @throws NameNotFoundException if {@code vpnPackage} is not installed.
6928      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
6929      *         set as always-on, or if always-on VPN is not available.
6930      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
6931      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled)6932     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
6933             boolean lockdownEnabled) throws NameNotFoundException {
6934         setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled, Collections.emptySet());
6935     }
6936 
6937     /**
6938      * A version of {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} that allows the
6939      * admin to specify a set of apps that should be able to access the network directly when VPN
6940      * is not connected. When VPN connects these apps switch over to VPN if allowed to use that VPN.
6941      * System apps can always bypass VPN.
6942      * <p> Note that the system doesn't update the allowlist when packages are installed or
6943      * uninstalled, the admin app must call this method to keep the list up to date.
6944      * <p> When {@code lockdownEnabled} is false {@code lockdownAllowlist} is ignored . When
6945      * {@code lockdownEnabled} is {@code true} and {@code lockdownAllowlist} is {@code null} or
6946      * empty, only system apps can bypass VPN.
6947      * <p> Setting always-on VPN package to {@code null} or using
6948      * {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} clears lockdown allowlist.
6949      *
6950      * @param vpnPackage package name for an installed VPN app on the device, or {@code null}
6951      *         to remove an existing always-on VPN configuration
6952      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
6953      *         {@code false} otherwise. This has no effect when clearing.
6954      * @param lockdownAllowlist Packages that will be able to access the network directly when VPN
6955      *         is in lockdown mode but not connected. Has no effect when clearing.
6956      * @throws SecurityException if {@code admin} is not a device or a profile
6957      *         owner.
6958      * @throws NameNotFoundException if {@code vpnPackage} or one of
6959      *         {@code lockdownAllowlist} is not installed.
6960      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does
6961      *         not support being set as always-on, or if always-on VPN is not
6962      *         available.
6963      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled, @Nullable Set<String> lockdownAllowlist)6964     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
6965             boolean lockdownEnabled, @Nullable Set<String> lockdownAllowlist)
6966             throws NameNotFoundException {
6967         throwIfParentInstance("setAlwaysOnVpnPackage");
6968         if (mService != null) {
6969             try {
6970                 mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled,
6971                         lockdownAllowlist == null ? null : new ArrayList<>(lockdownAllowlist));
6972             } catch (ServiceSpecificException e) {
6973                 switch (e.errorCode) {
6974                     case ERROR_VPN_PACKAGE_NOT_FOUND:
6975                         throw new NameNotFoundException(e.getMessage());
6976                     default:
6977                         throw new RuntimeException(
6978                                 "Unknown error setting always-on VPN: " + e.errorCode, e);
6979                 }
6980             } catch (RemoteException e) {
6981                 throw e.rethrowFromSystemServer();
6982             }
6983         }
6984     }
6985 
6986     /**
6987      * Called by device or profile owner to query whether current always-on VPN is configured in
6988      * lockdown mode. Returns {@code false} when no always-on configuration is set.
6989      *
6990      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6991      *
6992      * @throws SecurityException if {@code admin} is not a device or a profile owner.
6993      *
6994      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean)
6995      */
isAlwaysOnVpnLockdownEnabled(@onNull ComponentName admin)6996     public boolean isAlwaysOnVpnLockdownEnabled(@NonNull ComponentName admin) {
6997         throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
6998         if (mService != null) {
6999             try {
7000                 // Starting from Android R, the caller can pass the permission check in
7001                 // DevicePolicyManagerService if it holds android.permission.MAINLINE_NETWORK_STACK.
7002                 // Note that the android.permission.MAINLINE_NETWORK_STACK is a signature permission
7003                 // which is used by the NetworkStack mainline module.
7004                 return mService.isAlwaysOnVpnLockdownEnabled(admin);
7005             } catch (RemoteException e) {
7006                 throw e.rethrowFromSystemServer();
7007             }
7008         }
7009         return false;
7010     }
7011 
7012     /**
7013      * Returns whether the admin has enabled always-on VPN lockdown for the current user.
7014      *
7015      * Only callable by the system.
7016     * @hide
7017     */
7018     @UserHandleAware
isAlwaysOnVpnLockdownEnabled()7019     public boolean isAlwaysOnVpnLockdownEnabled() {
7020         throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
7021         if (mService != null) {
7022             try {
7023                 return mService.isAlwaysOnVpnLockdownEnabledForUser(myUserId());
7024             } catch (RemoteException e) {
7025                 throw e.rethrowFromSystemServer();
7026             }
7027         }
7028         return false;
7029     }
7030 
7031     /**
7032      * Called by device or profile owner to query the set of packages that are allowed to access
7033      * the network directly when always-on VPN is in lockdown mode but not connected. Returns
7034      * {@code null} when always-on VPN is not active or not in lockdown mode.
7035      *
7036      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7037      *
7038      * @throws SecurityException if {@code admin} is not a device or a profile owner.
7039      *
7040      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
7041      */
getAlwaysOnVpnLockdownWhitelist(@onNull ComponentName admin)7042     public @Nullable Set<String> getAlwaysOnVpnLockdownWhitelist(@NonNull ComponentName admin) {
7043         throwIfParentInstance("getAlwaysOnVpnLockdownWhitelist");
7044         if (mService != null) {
7045             try {
7046                 final List<String> allowlist =
7047                         mService.getAlwaysOnVpnLockdownAllowlist(admin);
7048                 return allowlist == null ? null : new HashSet<>(allowlist);
7049             } catch (RemoteException e) {
7050                 throw e.rethrowFromSystemServer();
7051             }
7052         }
7053         return null;
7054     }
7055 
7056     /**
7057      * Called by a device or profile owner to read the name of the package administering an
7058      * always-on VPN connection for the current user. If there is no such package, or the always-on
7059      * VPN is provided by the system instead of by an application, {@code null} will be returned.
7060      *
7061      * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
7062      *         is set.
7063      * @throws SecurityException if {@code admin} is not a device or a profile owner.
7064      */
getAlwaysOnVpnPackage(@onNull ComponentName admin)7065     public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
7066         throwIfParentInstance("getAlwaysOnVpnPackage");
7067         if (mService != null) {
7068             try {
7069                 return mService.getAlwaysOnVpnPackage(admin);
7070             } catch (RemoteException e) {
7071                 throw e.rethrowFromSystemServer();
7072             }
7073         }
7074         return null;
7075     }
7076 
7077     /**
7078      * Returns the VPN package name if the admin has enabled always-on VPN on the current user,
7079      * or {@code null} if none is set.
7080      *
7081      * Only callable by the system.
7082      * @hide
7083      */
7084     @UserHandleAware
getAlwaysOnVpnPackage()7085     public @Nullable String getAlwaysOnVpnPackage() {
7086         throwIfParentInstance("getAlwaysOnVpnPackage");
7087         if (mService != null) {
7088             try {
7089                 return mService.getAlwaysOnVpnPackageForUser(myUserId());
7090             } catch (RemoteException e) {
7091                 throw e.rethrowFromSystemServer();
7092             }
7093         }
7094         return null;
7095     }
7096 
7097     /**
7098      * Called by an application that is administering the device to disable all cameras on the
7099      * device, for this user. After setting this, no applications running as this user will be able
7100      * to access any cameras on the device.
7101      * <p>
7102      * This method can be called on the {@link DevicePolicyManager} instance,
7103      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
7104      * the profile owner of an organization-owned managed profile.
7105      * <p>
7106      * If the caller is device owner, then the restriction will be applied to all users. If
7107      * called on the parent instance, then the restriction will be applied on the personal profile.
7108      * <p>
7109      * The calling device admin must have requested
7110      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
7111      * not, a security exception will be thrown.
7112      * <p>
7113      * <b>Note</b>, this policy type is deprecated for legacy device admins since
7114      * {@link android.os.Build.VERSION_CODES#Q}. On Android
7115      * {@link android.os.Build.VERSION_CODES#Q} devices, legacy device admins targeting SDK
7116      * version {@link android.os.Build.VERSION_CODES#P} or below can still call this API to
7117      * disable camera, while legacy device admins targeting SDK version
7118      * {@link android.os.Build.VERSION_CODES#Q} will receive a SecurityException. Starting
7119      * from Android {@link android.os.Build.VERSION_CODES#R}, requests to disable camera from
7120      * legacy device admins targeting SDK version {@link android.os.Build.VERSION_CODES#P} or
7121      * below will be silently ignored.
7122      *
7123      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7124      * @param disabled Whether or not the camera should be disabled.
7125      * @throws SecurityException if {@code admin} is not an active administrator or does not use
7126      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
7127      */
setCameraDisabled(@onNull ComponentName admin, boolean disabled)7128     public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
7129         if (mService != null) {
7130             try {
7131                 mService.setCameraDisabled(admin, disabled, mParentInstance);
7132             } catch (RemoteException e) {
7133                 throw e.rethrowFromSystemServer();
7134             }
7135         }
7136     }
7137 
7138     /**
7139      * Determine whether or not the device's cameras have been disabled for this user,
7140      * either by the calling admin, if specified, or all admins.
7141      * <p>
7142      * This method can be called on the {@link DevicePolicyManager} instance,
7143      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
7144      * the profile owner of an organization-owned managed profile.
7145      *
7146      * @param admin The name of the admin component to check, or {@code null} to check whether any admins
7147      * have disabled the camera
7148      */
getCameraDisabled(@ullable ComponentName admin)7149     public boolean getCameraDisabled(@Nullable ComponentName admin) {
7150         return getCameraDisabled(admin, myUserId());
7151     }
7152 
7153     /** @hide per-user version */
7154     @UnsupportedAppUsage
getCameraDisabled(@ullable ComponentName admin, int userHandle)7155     public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
7156         if (mService != null) {
7157             try {
7158                 return mService.getCameraDisabled(admin, userHandle, mParentInstance);
7159             } catch (RemoteException e) {
7160                 throw e.rethrowFromSystemServer();
7161             }
7162         }
7163         return false;
7164     }
7165 
7166     /**
7167      * Called by a device owner to request a bugreport.
7168      * <p>
7169      * If the device contains secondary users or profiles, they must be affiliated with the device.
7170      * Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
7171      *
7172      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7173      * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
7174      *         wasn't triggered because a previous bugreport operation is still active (either the
7175      *         bugreport is still running or waiting for the user to share or decline)
7176      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
7177      *         profile or secondary user that is not affiliated with the device.
7178      * @see #isAffiliatedUser
7179      */
requestBugreport(@onNull ComponentName admin)7180     public boolean requestBugreport(@NonNull ComponentName admin) {
7181         throwIfParentInstance("requestBugreport");
7182         if (mService != null) {
7183             try {
7184                 return mService.requestBugreport(admin);
7185             } catch (RemoteException e) {
7186                 throw e.rethrowFromSystemServer();
7187             }
7188         }
7189         return false;
7190     }
7191 
7192     /**
7193      * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
7194      * screen capture also prevents the content from being shown on display devices that do not have
7195      * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
7196      * secure surfaces and secure displays.
7197      * <p>
7198      * This method can be called on the {@link DevicePolicyManager} instance, returned by
7199      * {@link #getParentProfileInstance(ComponentName)}, where the calling device admin must be
7200      * the profile owner of an organization-owned managed profile. If it is not, a security
7201      * exception will be thrown.
7202      * <p>
7203      * If the caller is device owner or called on the parent instance by a profile owner of an
7204      * organization-owned managed profile, then the restriction will be applied to all users.
7205      * <p>
7206      * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
7207      * assist requests for all activities of the relevant user.
7208      *
7209      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7210      * @param disabled Whether screen capture is disabled or not.
7211      * @throws SecurityException if {@code admin} is not a device or profile owner or if
7212      *                           called on the parent profile and the {@code admin} is not a
7213      *                           profile owner of an organization-owned managed profile.
7214      */
setScreenCaptureDisabled(@onNull ComponentName admin, boolean disabled)7215     public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
7216         if (mService != null) {
7217             try {
7218                 mService.setScreenCaptureDisabled(admin, disabled, mParentInstance);
7219             } catch (RemoteException e) {
7220                 throw e.rethrowFromSystemServer();
7221             }
7222         }
7223     }
7224 
7225     /**
7226      * Determine whether or not screen capture has been disabled by the calling
7227      * admin, if specified, or all admins.
7228      * <p>
7229      * This method can be called on the {@link DevicePolicyManager} instance,
7230      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
7231      * the profile owner of an organization-owned managed profile (the calling admin must be
7232      * specified).
7233      *
7234      * @param admin The name of the admin component to check, or {@code null} to check whether any
7235      *              admins have disabled screen capture.
7236      */
getScreenCaptureDisabled(@ullable ComponentName admin)7237     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
7238         return getScreenCaptureDisabled(admin, myUserId());
7239     }
7240 
7241     /** @hide per-user version */
getScreenCaptureDisabled(@ullable ComponentName admin, int userHandle)7242     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
7243         if (mService != null) {
7244             try {
7245                 return mService.getScreenCaptureDisabled(admin, userHandle, mParentInstance);
7246             } catch (RemoteException e) {
7247                 throw e.rethrowFromSystemServer();
7248             }
7249         }
7250         return false;
7251     }
7252 
7253     /**
7254      * Called by a device/profile owner to set nearby notification streaming policy. Notification
7255      * streaming is sending notification data from pre-installed apps to nearby devices.
7256      *
7257      * @param policy One of the {@code NearbyStreamingPolicy} constants.
7258      * @throws SecurityException if caller is not a device or profile owner
7259      */
setNearbyNotificationStreamingPolicy(@earbyStreamingPolicy int policy)7260     public void setNearbyNotificationStreamingPolicy(@NearbyStreamingPolicy int policy) {
7261         throwIfParentInstance("setNearbyNotificationStreamingPolicy");
7262         if (mService == null) {
7263             return;
7264         }
7265         try {
7266             mService.setNearbyNotificationStreamingPolicy(policy);
7267         } catch (RemoteException e) {
7268             throw e.rethrowFromSystemServer();
7269         }
7270     }
7271 
7272     /**
7273      * Returns the current runtime nearby notification streaming policy set by the device or profile
7274      * owner.
7275      */
getNearbyNotificationStreamingPolicy()7276     public @NearbyStreamingPolicy int getNearbyNotificationStreamingPolicy() {
7277         return getNearbyNotificationStreamingPolicy(myUserId());
7278     }
7279 
7280     /** @hide per-user version */
getNearbyNotificationStreamingPolicy(int userId)7281     public @NearbyStreamingPolicy int getNearbyNotificationStreamingPolicy(int userId) {
7282         throwIfParentInstance("getNearbyNotificationStreamingPolicy");
7283         if (mService == null) {
7284             return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
7285         }
7286         try {
7287             return mService.getNearbyNotificationStreamingPolicy(userId);
7288         } catch (RemoteException re) {
7289             throw re.rethrowFromSystemServer();
7290         }
7291     }
7292 
7293     /**
7294      * Called by a device/profile owner to set nearby app streaming policy. App streaming is when
7295      * the device starts an app on a virtual display and sends a video stream of the app to nearby
7296      * devices.
7297      *
7298      * @param policy One of the {@code NearbyStreamingPolicy} constants.
7299      * @throws SecurityException if caller is not a device or profile owner.
7300      */
setNearbyAppStreamingPolicy(@earbyStreamingPolicy int policy)7301     public void setNearbyAppStreamingPolicy(@NearbyStreamingPolicy int policy) {
7302         throwIfParentInstance("setNearbyAppStreamingPolicy");
7303         if (mService == null) {
7304             return;
7305         }
7306         try {
7307             mService.setNearbyAppStreamingPolicy(policy);
7308         } catch (RemoteException e) {
7309             throw e.rethrowFromSystemServer();
7310         }
7311     }
7312 
7313     /**
7314      * Returns the current runtime nearby app streaming policy set by the device or profile owner.
7315      */
getNearbyAppStreamingPolicy()7316     public @NearbyStreamingPolicy int getNearbyAppStreamingPolicy() {
7317         return getNearbyAppStreamingPolicy(myUserId());
7318     }
7319 
7320     /** @hide per-user version */
getNearbyAppStreamingPolicy(int userId)7321     public @NearbyStreamingPolicy int getNearbyAppStreamingPolicy(int userId) {
7322         throwIfParentInstance("getNearbyAppStreamingPolicy");
7323         if (mService == null) {
7324             return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
7325         }
7326         try {
7327             return mService.getNearbyAppStreamingPolicy(userId);
7328         } catch (RemoteException re) {
7329             throw re.rethrowFromSystemServer();
7330         }
7331     }
7332 
7333     /**
7334      * Called by a device owner, or alternatively a profile owner from Android 8.0 (API level 26) or
7335      * higher, to set whether auto time is required. If auto time is required, no user will be able
7336      * set the date and time and network date and time will be used.
7337      * <p>
7338      * Note: if auto time is required the user can still manually set the time zone.
7339      * <p>
7340      * The calling device admin must be a device owner, or alternatively a profile owner from
7341      * Android 8.0 (API level 26) or higher. If it is not, a security exception will be thrown.
7342      * <p>
7343      * Staring from Android 11, this API switches to use
7344      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} to enforce the auto time settings. Calling
7345      * this API to enforce auto time will result in
7346      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being set, while calling this API to lift
7347      * the requirement will result in {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being cleared.
7348      * From Android 11, this API can also no longer be called on a managed profile.
7349      *
7350      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7351      * @param required Whether auto time is set required or not.
7352      * @throws SecurityException if {@code admin} is not a device owner, not a profile owner or
7353      * if this API is called on a managed profile.
7354      * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #setAutoTimeEnabled}
7355      * to turn auto time on or off and use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
7356      * to prevent the user from changing this setting.
7357      */
7358     @Deprecated
setAutoTimeRequired(@onNull ComponentName admin, boolean required)7359     public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
7360         throwIfParentInstance("setAutoTimeRequired");
7361         if (mService != null) {
7362             try {
7363                 mService.setAutoTimeRequired(admin, required);
7364             } catch (RemoteException e) {
7365                 throw e.rethrowFromSystemServer();
7366             }
7367         }
7368     }
7369 
7370     /**
7371      * @return true if auto time is required.
7372      * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #getAutoTimeEnabled}
7373      */
7374     @Deprecated
getAutoTimeRequired()7375     public boolean getAutoTimeRequired() {
7376         throwIfParentInstance("getAutoTimeRequired");
7377         if (mService != null) {
7378             try {
7379                 return mService.getAutoTimeRequired();
7380             } catch (RemoteException e) {
7381                 throw e.rethrowFromSystemServer();
7382             }
7383         }
7384         return false;
7385     }
7386 
7387     /**
7388      * Called by a device owner, a profile owner for the primary user or a profile
7389      * owner of an organization-owned managed profile to turn auto time on and off.
7390      * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
7391      * to prevent the user from changing this setting.
7392      * <p>
7393      * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
7394      * no user will be able set the date and time. Instead, the network date
7395      * and time will be used.
7396      *
7397      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7398      * @param enabled Whether time should be obtained automatically from the network or not.
7399      * @throws SecurityException if caller is not a device owner, a profile owner for the
7400      * primary user, or a profile owner of an organization-owned managed profile.
7401      */
setAutoTimeEnabled(@onNull ComponentName admin, boolean enabled)7402     public void setAutoTimeEnabled(@NonNull ComponentName admin, boolean enabled) {
7403         if (mService != null) {
7404             try {
7405                 mService.setAutoTimeEnabled(admin, enabled);
7406             } catch (RemoteException e) {
7407                 throw e.rethrowFromSystemServer();
7408             }
7409         }
7410     }
7411 
7412     /**
7413      * @return true if auto time is enabled on the device.
7414      * @throws SecurityException if caller is not a device owner, a profile owner for the
7415      * primary user, or a profile owner of an organization-owned managed profile.
7416      */
getAutoTimeEnabled(@onNull ComponentName admin)7417     public boolean getAutoTimeEnabled(@NonNull ComponentName admin) {
7418         if (mService != null) {
7419             try {
7420                 return mService.getAutoTimeEnabled(admin);
7421             } catch (RemoteException e) {
7422                 throw e.rethrowFromSystemServer();
7423             }
7424         }
7425         return false;
7426     }
7427 
7428     /**
7429      * Called by a device owner, a profile owner for the primary user or a profile
7430      * owner of an organization-owned managed profile to turn auto time zone on and off.
7431      * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
7432      * to prevent the user from changing this setting.
7433      * <p>
7434      * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
7435      * no user will be able set the date and time zone. Instead, the network date
7436      * and time zone will be used.
7437      *
7438      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7439      * @param enabled Whether time zone should be obtained automatically from the network or not.
7440      * @throws SecurityException if caller is not a device owner, a profile owner for the
7441      * primary user, or a profile owner of an organization-owned managed profile.
7442      */
setAutoTimeZoneEnabled(@onNull ComponentName admin, boolean enabled)7443     public void setAutoTimeZoneEnabled(@NonNull ComponentName admin, boolean enabled) {
7444         throwIfParentInstance("setAutoTimeZone");
7445         if (mService != null) {
7446             try {
7447                 mService.setAutoTimeZoneEnabled(admin, enabled);
7448             } catch (RemoteException e) {
7449                 throw e.rethrowFromSystemServer();
7450             }
7451         }
7452     }
7453 
7454     /**
7455      * @return true if auto time zone is enabled on the device.
7456      * @throws SecurityException if caller is not a device owner, a profile owner for the
7457      * primary user, or a profile owner of an organization-owned managed profile.
7458      */
getAutoTimeZoneEnabled(@onNull ComponentName admin)7459     public boolean getAutoTimeZoneEnabled(@NonNull ComponentName admin) {
7460         throwIfParentInstance("getAutoTimeZone");
7461         if (mService != null) {
7462             try {
7463                 return mService.getAutoTimeZoneEnabled(admin);
7464             } catch (RemoteException e) {
7465                 throw e.rethrowFromSystemServer();
7466             }
7467         }
7468         return false;
7469     }
7470 
7471     /**
7472      * TODO (b/137101239): remove this method in follow-up CL
7473      * since it's only used for split system user.
7474      * Called by a device owner to set whether all users created on the device should be ephemeral.
7475      * @hide
7476      */
setForceEphemeralUsers( @onNull ComponentName admin, boolean forceEphemeralUsers)7477     public void setForceEphemeralUsers(
7478             @NonNull ComponentName admin, boolean forceEphemeralUsers) {
7479         throwIfParentInstance("setForceEphemeralUsers");
7480         if (mService != null) {
7481             try {
7482                 mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
7483             } catch (RemoteException e) {
7484                 throw e.rethrowFromSystemServer();
7485             }
7486         }
7487     }
7488 
7489     /**
7490      * TODO (b/137101239): remove this method in follow-up CL
7491      * since it's only used for split system user.
7492      * @return true if all users are created ephemeral.
7493      * @throws SecurityException if {@code admin} is not a device owner.
7494      * @hide
7495      */
getForceEphemeralUsers(@onNull ComponentName admin)7496     public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
7497         throwIfParentInstance("getForceEphemeralUsers");
7498         if (mService != null) {
7499             try {
7500                 return mService.getForceEphemeralUsers(admin);
7501             } catch (RemoteException e) {
7502                 throw e.rethrowFromSystemServer();
7503             }
7504         }
7505         return false;
7506     }
7507 
7508     /**
7509      * Called by an application that is administering the device to disable keyguard customizations,
7510      * such as widgets. After setting this, keyguard features will be disabled according to the
7511      * provided feature list.
7512      * <p>
7513      * The calling device admin must have requested
7514      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
7515      * if it has not, a security exception will be thrown.
7516      * <p>
7517      * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
7518      * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
7519      * profile owner of a managed profile can set:
7520      * <ul>
7521      * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
7522      * is no separate challenge set on the managed profile.
7523      * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FACE} or
7524      * {@link #KEYGUARD_DISABLE_IRIS} which affects the managed profile challenge if
7525      * there is one, or the parent user otherwise.
7526      * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
7527      * by applications in the managed profile.
7528      * </ul>
7529      * <p>
7530      * From version {@link android.os.Build.VERSION_CODES#R} the profile owner of an
7531      * organization-owned managed profile can set:
7532      * <ul>
7533      * <li>{@link #KEYGUARD_DISABLE_SECURE_CAMERA} which affects the parent user when called on the
7534      * parent profile.
7535      * <li>{@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS} which affects the parent user when called
7536      * on the parent profile.
7537      * </ul>
7538      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, {@link #KEYGUARD_DISABLE_FINGERPRINT},
7539      * {@link #KEYGUARD_DISABLE_FACE}, {@link #KEYGUARD_DISABLE_IRIS},
7540      * {@link #KEYGUARD_DISABLE_SECURE_CAMERA} and {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS}
7541      * can also be set on the {@link DevicePolicyManager} instance returned by
7542      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
7543      * profile. {@link #KEYGUARD_DISABLE_SECURE_CAMERA} can only be set on the parent profile
7544      * instance if the calling device admin is the profile owner of an organization-owned
7545      * managed profile.
7546      * <p>
7547      * Requests to disable other features on a managed profile will be ignored.
7548      * <p>
7549      * The admin can check which features have been disabled by calling
7550      * {@link #getKeyguardDisabledFeatures(ComponentName)}
7551      *
7552      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7553      * @param which The disabled features flag which can be either
7554      *            {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
7555      *            {@link #KEYGUARD_DISABLE_FEATURES_ALL}, or a combination of
7556      *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
7557      *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
7558      *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
7559      *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
7560      *            {@link #KEYGUARD_DISABLE_FINGERPRINT},
7561      *            {@link #KEYGUARD_DISABLE_FACE},
7562      *            {@link #KEYGUARD_DISABLE_IRIS}.
7563      * @throws SecurityException if {@code admin} is not an active administrator or does not user
7564      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
7565      */
setKeyguardDisabledFeatures(@onNull ComponentName admin, int which)7566     public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
7567         if (mService != null) {
7568             try {
7569                 mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
7570             } catch (RemoteException e) {
7571                 throw e.rethrowFromSystemServer();
7572             }
7573         }
7574     }
7575 
7576     /**
7577      * Determine whether or not features have been disabled in keyguard either by the calling
7578      * admin, if specified, or all admins that set restrictions on this user and its participating
7579      * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
7580      *
7581      * <p>This method can be called on the {@link DevicePolicyManager} instance
7582      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
7583      * restrictions on the parent profile.
7584      *
7585      * @param admin The name of the admin component to check, or {@code null} to check whether any
7586      * admins have disabled features in keyguard.
7587      * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
7588      * for a list.
7589      */
getKeyguardDisabledFeatures(@ullable ComponentName admin)7590     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
7591         return getKeyguardDisabledFeatures(admin, myUserId());
7592     }
7593 
7594     /** @hide per-user version */
7595     @UnsupportedAppUsage
getKeyguardDisabledFeatures(@ullable ComponentName admin, int userHandle)7596     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
7597         if (mService != null) {
7598             try {
7599                 return mService.getKeyguardDisabledFeatures(admin, userHandle, mParentInstance);
7600             } catch (RemoteException e) {
7601                 throw e.rethrowFromSystemServer();
7602             }
7603         }
7604         return KEYGUARD_DISABLE_FEATURES_NONE;
7605     }
7606 
7607     /**
7608      * @hide
7609      */
7610     @TestApi
7611     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
7612     @RequiresPermission(allOf = {
7613             android.Manifest.permission.MANAGE_DEVICE_ADMINS,
7614             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL
7615     })
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing, int userHandle)7616     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
7617             int userHandle) {
7618         if (mService != null) {
7619             try {
7620                 mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
7621             } catch (RemoteException e) {
7622                 throw e.rethrowFromSystemServer();
7623             }
7624         }
7625     }
7626 
7627     /**
7628      * @hide
7629      */
7630     @UnsupportedAppUsage
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing)7631     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
7632         setActiveAdmin(policyReceiver, refreshing, myUserId());
7633     }
7634 
7635     /**
7636      * Called by a privileged caller holding {@code BIND_DEVICE_ADMIN} permission to retrieve
7637      * the remove warning for the given device admin.
7638      * @hide
7639      */
getRemoveWarning(@ullable ComponentName admin, RemoteCallback result)7640     public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
7641         if (mService != null) {
7642             try {
7643                 mService.getRemoveWarning(admin, result, myUserId());
7644             } catch (RemoteException e) {
7645                 throw e.rethrowFromSystemServer();
7646             }
7647         }
7648     }
7649 
7650     /**
7651      * @hide
7652      */
7653     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportPasswordChanged(@serIdInt int userId)7654     public void reportPasswordChanged(@UserIdInt int userId) {
7655         if (mService != null) {
7656             try {
7657                 mService.reportPasswordChanged(userId);
7658             } catch (RemoteException e) {
7659                 throw e.rethrowFromSystemServer();
7660             }
7661         }
7662     }
7663 
7664     /**
7665      * @hide
7666      */
7667     @UnsupportedAppUsage
7668     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedPasswordAttempt(int userHandle)7669     public void reportFailedPasswordAttempt(int userHandle) {
7670         if (mService != null) {
7671             try {
7672                 mService.reportFailedPasswordAttempt(userHandle);
7673             } catch (RemoteException e) {
7674                 throw e.rethrowFromSystemServer();
7675             }
7676         }
7677     }
7678 
7679     /**
7680      * @hide
7681      */
7682     @UnsupportedAppUsage
7683     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulPasswordAttempt(int userHandle)7684     public void reportSuccessfulPasswordAttempt(int userHandle) {
7685         if (mService != null) {
7686             try {
7687                 mService.reportSuccessfulPasswordAttempt(userHandle);
7688             } catch (RemoteException e) {
7689                 throw e.rethrowFromSystemServer();
7690             }
7691         }
7692     }
7693 
7694     /**
7695      * @hide
7696      */
7697     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedBiometricAttempt(int userHandle)7698     public void reportFailedBiometricAttempt(int userHandle) {
7699         if (mService != null) {
7700             try {
7701                 mService.reportFailedBiometricAttempt(userHandle);
7702             } catch (RemoteException e) {
7703                 throw e.rethrowFromSystemServer();
7704             }
7705         }
7706     }
7707 
7708     /**
7709      * @hide
7710      */
7711     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulBiometricAttempt(int userHandle)7712     public void reportSuccessfulBiometricAttempt(int userHandle) {
7713         if (mService != null) {
7714             try {
7715                 mService.reportSuccessfulBiometricAttempt(userHandle);
7716             } catch (RemoteException e) {
7717                 throw e.rethrowFromSystemServer();
7718             }
7719         }
7720     }
7721 
7722     /**
7723      * Should be called when keyguard has been dismissed.
7724      * @hide
7725      */
reportKeyguardDismissed(int userHandle)7726     public void reportKeyguardDismissed(int userHandle) {
7727         if (mService != null) {
7728             try {
7729                 mService.reportKeyguardDismissed(userHandle);
7730             } catch (RemoteException e) {
7731                 throw e.rethrowFromSystemServer();
7732             }
7733         }
7734     }
7735 
7736     /**
7737      * Should be called when keyguard view has been shown to the user.
7738      * @hide
7739      */
reportKeyguardSecured(int userHandle)7740     public void reportKeyguardSecured(int userHandle) {
7741         if (mService != null) {
7742             try {
7743                 mService.reportKeyguardSecured(userHandle);
7744             } catch (RemoteException e) {
7745                 throw e.rethrowFromSystemServer();
7746             }
7747         }
7748     }
7749 
7750     /**
7751      * @hide
7752      * Sets the given package as the device owner.
7753      * Same as {@link #setDeviceOwner(ComponentName, String)} but without setting a device owner name.
7754      * @param who the component name to be registered as device owner.
7755      * @return whether the package was successfully registered as the device owner.
7756      * @throws IllegalArgumentException if the package name is null or invalid
7757      * @throws IllegalStateException If the preconditions mentioned are not met.
7758      */
setDeviceOwner(ComponentName who)7759     public boolean setDeviceOwner(ComponentName who) {
7760         return setDeviceOwner(who, null);
7761     }
7762 
7763     /**
7764      * @hide
7765      */
setDeviceOwner(ComponentName who, int userId)7766     public boolean setDeviceOwner(ComponentName who, int userId)  {
7767         return setDeviceOwner(who, null, userId);
7768     }
7769 
7770     /**
7771      * @hide
7772      */
setDeviceOwner(ComponentName who, String ownerName)7773     public boolean setDeviceOwner(ComponentName who, String ownerName) {
7774         return setDeviceOwner(who, ownerName, UserHandle.USER_SYSTEM);
7775     }
7776 
7777     /**
7778      * Sets the given package as the device owner.
7779      *
7780      * <p>Preconditions:
7781      * <ul>
7782      *   <li>The package must already be installed.
7783      *   <li>There must not already be a device owner.
7784      *   <li>Only apps with the {@code MANAGE_PROFILE_AND_DEVICE_OWNERS} permission or the
7785      *       {@link Process#SHELL_UID Shell UID} can call this method.
7786      * </ul>
7787      *
7788      * <p>Calling this after the setup phase of the device owner user has completed is allowed only
7789      * if the caller is the {@link Process#SHELL_UID Shell UID}, and there are no additional users
7790      * (except when the device runs on headless system user mode, in which case it could have exact
7791      * one extra user, which is the current user - the device owner will be set in the
7792      * {@link UserHandle#SYSTEM system} user and a profile owner will be set in the current user)
7793      * and no accounts.
7794      *
7795      * @param who the component name to be registered as device owner.
7796      * @param ownerName the human readable name of the institution that owns this device.
7797      * @param userId ID of the user on which the device owner runs.
7798      *
7799      * @return whether the package was successfully registered as the device owner.
7800      *
7801      * @throws IllegalArgumentException if the package name is {@code null} or invalid.
7802      * @throws IllegalStateException If the preconditions mentioned are not met.
7803      *
7804      * @hide
7805      */
7806     @TestApi
7807     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setDeviceOwner(@onNull ComponentName who, @Nullable String ownerName, @UserIdInt int userId)7808     public boolean setDeviceOwner(@NonNull ComponentName who, @Nullable String ownerName,
7809             @UserIdInt int userId) {
7810         if (mService != null) {
7811             try {
7812                 return mService.setDeviceOwner(who, ownerName, userId,
7813                         /* setProfileOwnerOnCurrentUserIfNecessary= */ true);
7814             } catch (RemoteException re) {
7815                 throw re.rethrowFromSystemServer();
7816             }
7817         }
7818         return false;
7819     }
7820 
7821     /**
7822      * Same as {@link #setDeviceOwner(ComponentName, String, int)}, but without setting the profile
7823      * owner on current user when running on headless system user mode - should be used only by
7824      * testing infra.
7825      *
7826      * @hide
7827      */
7828     @TestApi
7829     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setDeviceOwnerOnly( @onNull ComponentName who, @Nullable String ownerName, @UserIdInt int userId)7830     public boolean setDeviceOwnerOnly(
7831             @NonNull ComponentName who, @Nullable String ownerName, @UserIdInt int userId) {
7832         if (mService != null) {
7833             try {
7834                 return mService.setDeviceOwner(who, ownerName, userId,
7835                         /* setProfileOwnerOnCurrentUserIfNecessary= */ false);
7836             } catch (RemoteException re) {
7837                 throw re.rethrowFromSystemServer();
7838             }
7839         }
7840         return false;
7841     }
7842 
7843     /**
7844      * Used to determine if a particular package has been registered as a Device Owner app.
7845      * A device owner app is a special device admin that cannot be deactivated by the user, once
7846      * activated as a device admin. It also cannot be uninstalled. To check whether a particular
7847      * package is currently registered as the device owner app, pass in the package name from
7848      * {@link Context#getPackageName()} to this method.<p/>This is useful for device
7849      * admin apps that want to check whether they are also registered as the device owner app. The
7850      * exact mechanism by which a device admin app is registered as a device owner app is defined by
7851      * the setup process.
7852      * @param packageName the package name of the app, to compare with the registered device owner
7853      * app, if any.
7854      * @return whether or not the package is registered as the device owner app.
7855      */
isDeviceOwnerApp(String packageName)7856     public boolean isDeviceOwnerApp(String packageName) {
7857         throwIfParentInstance("isDeviceOwnerApp");
7858         return isDeviceOwnerAppOnCallingUser(packageName);
7859     }
7860 
7861     /**
7862      * @return true if a package is registered as device owner, only when it's running on the
7863      * calling user.
7864      *
7865      * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
7866      * @hide
7867      */
isDeviceOwnerAppOnCallingUser(String packageName)7868     public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
7869         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
7870     }
7871 
7872     /**
7873      * @return true if a package is registered as device owner, even if it's running on a different
7874      * user.
7875      *
7876      * <p>Requires the MANAGE_USERS permission.
7877      *
7878      * @hide
7879      */
isDeviceOwnerAppOnAnyUser(String packageName)7880     public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
7881         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
7882     }
7883 
7884     /**
7885      * @return device owner component name, only when it's running on the calling user.
7886      *
7887      * @hide
7888      */
getDeviceOwnerComponentOnCallingUser()7889     public ComponentName getDeviceOwnerComponentOnCallingUser() {
7890         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
7891     }
7892 
7893     /**
7894      * @return device owner component name, even if it's running on a different user.
7895      *
7896      * @hide
7897      */
7898     @SystemApi
7899     @RequiresPermission(anyOf = {
7900             android.Manifest.permission.MANAGE_USERS,
7901             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
7902     })
getDeviceOwnerComponentOnAnyUser()7903     public ComponentName getDeviceOwnerComponentOnAnyUser() {
7904         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
7905     }
7906 
isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly)7907     private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
7908         if (packageName == null) {
7909             return false;
7910         }
7911         final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
7912         if (deviceOwner == null) {
7913             return false;
7914         }
7915         return packageName.equals(deviceOwner.getPackageName());
7916     }
7917 
getDeviceOwnerComponentInner(boolean callingUserOnly)7918     private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
7919         if (mService != null) {
7920             try {
7921                 return mService.getDeviceOwnerComponent(callingUserOnly);
7922             } catch (RemoteException re) {
7923                 throw re.rethrowFromSystemServer();
7924             }
7925         }
7926         return null;
7927     }
7928 
7929     /**
7930      * @return Handle of the user who runs device owner, or {@code null} if there's no device owner.
7931      *
7932      * @hide
7933      */
7934     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
7935     @SystemApi
getDeviceOwnerUser()7936     public @Nullable UserHandle getDeviceOwnerUser() {
7937         if (mService != null) {
7938             try {
7939                 int userId = mService.getDeviceOwnerUserId();
7940 
7941                 if (userId != UserHandle.USER_NULL) {
7942                     return UserHandle.of(userId);
7943                 }
7944             } catch (RemoteException re) {
7945                 throw re.rethrowFromSystemServer();
7946             }
7947         }
7948         return null;
7949     }
7950 
7951     /**
7952      * @hide
7953      */
getDeviceOwnerUserId()7954     public int getDeviceOwnerUserId() {
7955         if (mService != null) {
7956             try {
7957                 return mService.getDeviceOwnerUserId();
7958             } catch (RemoteException re) {
7959                 throw re.rethrowFromSystemServer();
7960             }
7961         }
7962         return UserHandle.USER_NULL;
7963     }
7964 
7965     /**
7966      * Clears the current device owner. The caller must be the device owner. This function should be
7967      * used cautiously as once it is called it cannot be undone. The device owner can only be set as
7968      * a part of device setup, before it completes.
7969      * <p>
7970      * While some policies previously set by the device owner will be cleared by this method, it is
7971      * a best-effort process and some other policies will still remain in place after the device
7972      * owner is cleared.
7973      *
7974      * @param packageName The package name of the device owner.
7975      * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
7976      *             does not own the current device owner component.
7977      *
7978      * @deprecated This method is expected to be used for testing purposes only. The device owner
7979      * will lose control of the device and its data after calling it. In order to protect any
7980      * sensitive data that remains on the device, it is advised that the device owner factory resets
7981      * the device instead of calling this method. See {@link #wipeData(int)}.
7982      */
7983     @Deprecated
clearDeviceOwnerApp(String packageName)7984     public void clearDeviceOwnerApp(String packageName) {
7985         throwIfParentInstance("clearDeviceOwnerApp");
7986         if (mService != null) {
7987             try {
7988                 mService.clearDeviceOwner(packageName);
7989             } catch (RemoteException re) {
7990                 throw re.rethrowFromSystemServer();
7991             }
7992         }
7993     }
7994 
7995     /**
7996      * Returns the device owner package name, only if it's running on the calling user.
7997      *
7998      * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
7999      *
8000      * @hide
8001      */
8002     @SystemApi
8003     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwner()8004     public @Nullable String getDeviceOwner() {
8005         throwIfParentInstance("getDeviceOwner");
8006         final ComponentName name = getDeviceOwnerComponentOnCallingUser();
8007         return name != null ? name.getPackageName() : null;
8008     }
8009 
8010     /**
8011      * Called by the system to find out whether the device is managed by a Device Owner.
8012      *
8013      * @return whether the device is managed by a Device Owner.
8014      * @throws SecurityException if the caller is not the device owner, does not hold the
8015      *         MANAGE_USERS permission and is not the system.
8016      *
8017      * @hide
8018      */
8019     @SystemApi
8020     @SuppressLint("RequiresPermission")
isDeviceManaged()8021     public boolean isDeviceManaged() {
8022         try {
8023             return mService.hasDeviceOwner();
8024         } catch (RemoteException re) {
8025             throw re.rethrowFromSystemServer();
8026         }
8027     }
8028 
8029     /**
8030      * Returns the device owner name.  Note this method *will* return the device owner
8031      * name when it's running on a different user.
8032      *
8033      * @hide
8034      */
8035     @SystemApi
8036     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwnerNameOnAnyUser()8037     public String getDeviceOwnerNameOnAnyUser() {
8038         throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
8039         if (mService != null) {
8040             try {
8041                 return mService.getDeviceOwnerName();
8042             } catch (RemoteException re) {
8043                 throw re.rethrowFromSystemServer();
8044             }
8045         }
8046         return null;
8047     }
8048 
8049     /**
8050      * @hide
8051      * @deprecated Use #ACTION_SET_PROFILE_OWNER
8052      * Sets the given component as an active admin and registers the package as the profile
8053      * owner for this user. The package must already be installed and there shouldn't be
8054      * an existing profile owner registered for this user. Also, this method must be called
8055      * before the user setup has been completed.
8056      * <p>
8057      * This method can only be called by system apps that hold MANAGE_USERS permission and
8058      * MANAGE_DEVICE_ADMINS permission.
8059      * @param admin The component to register as an active admin and profile owner.
8060      * @param ownerName The user-visible name of the entity that is managing this user.
8061      * @return whether the admin was successfully registered as the profile owner.
8062      * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
8063      *         the user has already been set up.
8064      */
8065     @Deprecated
8066     @SystemApi
8067     @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
setActiveProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName)8068     public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
8069             throws IllegalArgumentException {
8070         throwIfParentInstance("setActiveProfileOwner");
8071         if (mService != null) {
8072             try {
8073                 final int myUserId = myUserId();
8074                 mService.setActiveAdmin(admin, false, myUserId);
8075                 return mService.setProfileOwner(admin, ownerName, myUserId);
8076             } catch (RemoteException re) {
8077                 throw re.rethrowFromSystemServer();
8078             }
8079         }
8080         return false;
8081     }
8082 
8083     /**
8084      * Clears the active profile owner. The caller must be the profile owner of this user, otherwise
8085      * a SecurityException will be thrown. This method is not available to managed profile owners.
8086      * <p>
8087      * While some policies previously set by the profile owner will be cleared by this method, it is
8088      * a best-effort process and some other policies will still remain in place after the profile
8089      * owner is cleared.
8090      *
8091      * @param admin The component to remove as the profile owner.
8092      * @throws SecurityException if {@code admin} is not an active profile owner, or the method is
8093      * being called from a managed profile.
8094      *
8095      * @deprecated This method is expected to be used for testing purposes only. The profile owner
8096      * will lose control of the user and its data after calling it. In order to protect any
8097      * sensitive data that remains on this user, it is advised that the profile owner deletes it
8098      * instead of calling this method. See {@link #wipeData(int)}.
8099      */
8100     @Deprecated
clearProfileOwner(@onNull ComponentName admin)8101     public void clearProfileOwner(@NonNull ComponentName admin) {
8102         throwIfParentInstance("clearProfileOwner");
8103         if (mService != null) {
8104             try {
8105                 mService.clearProfileOwner(admin);
8106             } catch (RemoteException re) {
8107                 throw re.rethrowFromSystemServer();
8108             }
8109         }
8110     }
8111 
8112     /**
8113      * @hide
8114      * Checks whether the user was already setup.
8115      */
hasUserSetupCompleted()8116     public boolean hasUserSetupCompleted() {
8117         if (mService != null) {
8118             try {
8119                 return mService.hasUserSetupCompleted();
8120             } catch (RemoteException re) {
8121                 throw re.rethrowFromSystemServer();
8122             }
8123         }
8124         return true;
8125     }
8126 
8127     /**
8128      * @hide
8129      * Sets the given component as the profile owner of the given user profile. The package must
8130      * already be installed. There must not already be a profile owner for this user.
8131      * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
8132      * this method.
8133      * Calling this after the setup phase of the specified user has completed is allowed only if:
8134      * - the caller is SYSTEM_UID.
8135      * - or the caller is the shell uid, and there are no accounts on the specified user.
8136      * @param admin the component name to be registered as profile owner.
8137      * @param ownerName the human readable name of the organisation associated with this DPM.
8138      * @param userHandle the userId to set the profile owner for.
8139      * @return whether the component was successfully registered as the profile owner.
8140      * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
8141      * preconditions mentioned are not met.
8142      */
setProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName, int userHandle)8143     public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
8144             int userHandle) throws IllegalArgumentException {
8145         if (mService != null) {
8146             try {
8147                 if (ownerName == null) {
8148                     ownerName = "";
8149                 }
8150                 return mService.setProfileOwner(admin, ownerName, userHandle);
8151             } catch (RemoteException re) {
8152                 throw re.rethrowFromSystemServer();
8153             }
8154         }
8155         return false;
8156     }
8157 
8158     /**
8159      * Sets the device owner information to be shown on the lock screen.
8160      * <p>
8161      * Device owner information set using this method overrides any owner information manually set
8162      * by the user and prevents the user from further changing it.
8163      * <p>
8164      * If the device owner information is {@code null} or empty then the device owner info is
8165      * cleared and the user owner info is shown on the lock screen if it is set.
8166      * <p>
8167      * If the device owner information contains only whitespaces then the message on the lock screen
8168      * will be blank and the user will not be allowed to change it.
8169      * <p>
8170      * If the device owner information needs to be localized, it is the responsibility of the
8171      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
8172      * and set a new version of this string accordingly.
8173      * <p>
8174      * May be called by the device owner or the profile owner of an organization-owned device.
8175      *
8176      * @param admin The name of the admin component to check.
8177      * @param info Device owner information which will be displayed instead of the user owner info.
8178      * @throws SecurityException if {@code admin} is not a device owner.
8179      */
setDeviceOwnerLockScreenInfo(@onNull ComponentName admin, CharSequence info)8180     public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
8181         throwIfParentInstance("setDeviceOwnerLockScreenInfo");
8182         if (mService != null) {
8183             try {
8184                 mService.setDeviceOwnerLockScreenInfo(admin, info);
8185             } catch (RemoteException re) {
8186                 throw re.rethrowFromSystemServer();
8187             }
8188         }
8189     }
8190 
8191     /**
8192      * @return The device owner information. If it is not set returns {@code null}.
8193      */
getDeviceOwnerLockScreenInfo()8194     public CharSequence getDeviceOwnerLockScreenInfo() {
8195         throwIfParentInstance("getDeviceOwnerLockScreenInfo");
8196         if (mService != null) {
8197             try {
8198                 return mService.getDeviceOwnerLockScreenInfo();
8199             } catch (RemoteException re) {
8200                 throw re.rethrowFromSystemServer();
8201             }
8202         }
8203         return null;
8204     }
8205 
8206     /**
8207      * Called by device or profile owners to suspend packages for this user. This function can be
8208      * called by a device owner, profile owner, or by a delegate given the
8209      * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}.
8210      * <p>
8211      * A suspended package will not be able to start activities. Its notifications will be hidden,
8212      * it will not show up in recents, will not be able to show toasts or dialogs or ring the
8213      * device.
8214      * <p>
8215      * The package must already be installed. If the package is uninstalled while suspended the
8216      * package will no longer be suspended. The admin can block this by using
8217      * {@link #setUninstallBlocked}.
8218      *
8219      * <p>Some apps cannot be suspended, such as device admins, the active launcher, the required
8220      * package installer, the required package uninstaller, the required package verifier, the
8221      * default dialer, and the permission controller.
8222      *
8223      * @param admin The name of the admin component to check, or {@code null} if the caller is a
8224      *            package access delegate.
8225      * @param packageNames The package names to suspend or unsuspend.
8226      * @param suspended If set to {@code true} than the packages will be suspended, if set to
8227      *            {@code false} the packages will be unsuspended.
8228      * @return an array of package names for which the suspended status is not set as requested in
8229      *         this method.
8230      * @throws SecurityException if {@code admin} is not a device or profile owner.
8231      * @see #setDelegatedScopes
8232      * @see #DELEGATION_PACKAGE_ACCESS
8233      */
setPackagesSuspended(@onNull ComponentName admin, @NonNull String[] packageNames, boolean suspended)8234     public @NonNull String[] setPackagesSuspended(@NonNull ComponentName admin,
8235             @NonNull String[] packageNames, boolean suspended) {
8236         throwIfParentInstance("setPackagesSuspended");
8237         if (mService != null) {
8238             try {
8239                 return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames,
8240                         suspended);
8241             } catch (RemoteException re) {
8242                 throw re.rethrowFromSystemServer();
8243             }
8244         }
8245         return packageNames;
8246     }
8247 
8248     /**
8249      * Determine if a package is suspended. This function can be called by a device owner, profile
8250      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
8251      * {@link #setDelegatedScopes}.
8252      *
8253      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8254      *            {@code null} if the caller is a package access delegate.
8255      * @param packageName The name of the package to retrieve the suspended status of.
8256      * @return {@code true} if the package is suspended or {@code false} if the package is not
8257      *         suspended, could not be found or an error occurred.
8258      * @throws SecurityException if {@code admin} is not a device or profile owner.
8259      * @throws NameNotFoundException if the package could not be found.
8260      * @see #setDelegatedScopes
8261      * @see #DELEGATION_PACKAGE_ACCESS
8262      */
isPackageSuspended(@onNull ComponentName admin, String packageName)8263     public boolean isPackageSuspended(@NonNull ComponentName admin, String packageName)
8264             throws NameNotFoundException {
8265         throwIfParentInstance("isPackageSuspended");
8266         if (mService != null) {
8267             try {
8268                 return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName);
8269             } catch (RemoteException e) {
8270                 throw e.rethrowFromSystemServer();
8271             } catch (IllegalArgumentException ex) {
8272                 throw new NameNotFoundException(packageName);
8273             }
8274         }
8275         return false;
8276     }
8277 
8278     /**
8279      * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
8280      * be used. Only the profile owner can call this.
8281      *
8282      * @see #isProfileOwnerApp
8283      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8284      * @throws SecurityException if {@code admin} is not a profile owner.
8285      */
setProfileEnabled(@onNull ComponentName admin)8286     public void setProfileEnabled(@NonNull ComponentName admin) {
8287         throwIfParentInstance("setProfileEnabled");
8288         if (mService != null) {
8289             try {
8290                 mService.setProfileEnabled(admin);
8291             } catch (RemoteException e) {
8292                 throw e.rethrowFromSystemServer();
8293             }
8294         }
8295     }
8296 
8297     /**
8298      * Sets the name of the profile. In the device owner case it sets the name of the user which it
8299      * is called from. Only a profile owner or device owner can call this. If this is never called
8300      * by the profile or device owner, the name will be set to default values.
8301      *
8302      * @see #isProfileOwnerApp
8303      * @see #isDeviceOwnerApp
8304      * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
8305      * @param profileName The name of the profile.
8306      * @throws SecurityException if {@code admin} is not a device or profile owner.
8307      */
setProfileName(@onNull ComponentName admin, String profileName)8308     public void setProfileName(@NonNull ComponentName admin, String profileName) {
8309         throwIfParentInstance("setProfileName");
8310         if (mService != null) {
8311             try {
8312                 mService.setProfileName(admin, profileName);
8313             } catch (RemoteException e) {
8314                 throw e.rethrowFromSystemServer();
8315             }
8316         }
8317     }
8318 
8319     /**
8320      * Used to determine if a particular package is registered as the profile owner for the
8321      * user. A profile owner is a special device admin that has additional privileges
8322      * within the profile.
8323      *
8324      * @param packageName The package name of the app to compare with the registered profile owner.
8325      * @return Whether or not the package is registered as the profile owner.
8326      */
isProfileOwnerApp(String packageName)8327     public boolean isProfileOwnerApp(String packageName) {
8328         throwIfParentInstance("isProfileOwnerApp");
8329         if (mService != null) {
8330             try {
8331                 ComponentName profileOwner = mService.getProfileOwnerAsUser(myUserId());
8332                 return profileOwner != null
8333                         && profileOwner.getPackageName().equals(packageName);
8334             } catch (RemoteException re) {
8335                 throw re.rethrowFromSystemServer();
8336             }
8337         }
8338         return false;
8339     }
8340 
8341     /**
8342      * @hide
8343      * @return the packageName of the owner of the given user profile or {@code null} if no profile
8344      * owner has been set for that user.
8345      * @throws IllegalArgumentException if the userId is invalid.
8346      */
8347     @SystemApi
getProfileOwner()8348     public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
8349         throwIfParentInstance("getProfileOwner");
8350         return getProfileOwnerAsUser(mContext.getUserId());
8351     }
8352 
8353     /**
8354      * @see #getProfileOwner()
8355      * @hide
8356      */
8357     @RequiresPermission(value = android.Manifest.permission.INTERACT_ACROSS_USERS,
8358             conditional = true)
getProfileOwnerAsUser(@onNull UserHandle user)8359     public @Nullable ComponentName getProfileOwnerAsUser(@NonNull UserHandle user) {
8360         if (mService != null) {
8361             try {
8362                 return mService.getProfileOwnerAsUser(user.getIdentifier());
8363             } catch (RemoteException re) {
8364                 throw re.rethrowFromSystemServer();
8365             }
8366         }
8367         return null;
8368     }
8369 
8370     /**
8371      * @hide
8372      */
8373     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getProfileOwnerAsUser(final int userId)8374     public @Nullable ComponentName getProfileOwnerAsUser(final int userId) {
8375         if (mService != null) {
8376             try {
8377                 return mService.getProfileOwnerAsUser(userId);
8378             } catch (RemoteException re) {
8379                 throw re.rethrowFromSystemServer();
8380             }
8381         }
8382         return null;
8383     }
8384 
8385     /**
8386      * Returns the configured supervision app if it exists and is the device owner or policy owner.
8387      * @hide
8388      */
getProfileOwnerOrDeviceOwnerSupervisionComponent( @onNull UserHandle user)8389     public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent(
8390             @NonNull UserHandle user) {
8391         if (mService != null) {
8392             try {
8393                 return mService.getProfileOwnerOrDeviceOwnerSupervisionComponent(user);
8394             } catch (RemoteException re) {
8395                 throw re.rethrowFromSystemServer();
8396             }
8397         }
8398         return null;
8399     }
8400 
8401     /**
8402      * @hide
8403      * @return the human readable name of the organisation associated with this DPM or {@code null}
8404      *         if one is not set.
8405      * @throws IllegalArgumentException if the userId is invalid.
8406      */
getProfileOwnerName()8407     public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
8408         if (mService != null) {
8409             try {
8410                 return mService.getProfileOwnerName(mContext.getUserId());
8411             } catch (RemoteException re) {
8412                 throw re.rethrowFromSystemServer();
8413             }
8414         }
8415         return null;
8416     }
8417 
8418     /**
8419      * @hide
8420      * @param userId The user for whom to fetch the profile owner name, if any.
8421      * @return the human readable name of the organisation associated with this profile owner or
8422      *         null if one is not set.
8423      * @throws IllegalArgumentException if the userId is invalid.
8424      */
8425     @SystemApi
8426     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getProfileOwnerNameAsUser(int userId)8427     public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
8428         throwIfParentInstance("getProfileOwnerNameAsUser");
8429         if (mService != null) {
8430             try {
8431                 return mService.getProfileOwnerName(userId);
8432             } catch (RemoteException re) {
8433                 throw re.rethrowFromSystemServer();
8434             }
8435         }
8436         return null;
8437     }
8438 
8439     /**
8440      * Apps can use this method to find out if the device was provisioned as
8441      * organization-owend device with a managed profile.
8442      *
8443      * This, together with checking whether the device has a device owner (by calling
8444      * {@link #isDeviceOwnerApp}), could be used to learn whether the device is owned by an
8445      * organization or an individual:
8446      * If this method returns true OR {@link #isDeviceOwnerApp} returns true (for any package),
8447      * then the device is owned by an organization. Otherwise, it's owned by an individual.
8448      *
8449      * @return {@code true} if the device was provisioned as organization-owned device,
8450      * {@code false} otherwise.
8451      */
isOrganizationOwnedDeviceWithManagedProfile()8452     public boolean isOrganizationOwnedDeviceWithManagedProfile() {
8453         throwIfParentInstance("isOrganizationOwnedDeviceWithManagedProfile");
8454         if (mService != null) {
8455             try {
8456                 return mService.isOrganizationOwnedDeviceWithManagedProfile();
8457             } catch (RemoteException re) {
8458                 throw re.rethrowFromSystemServer();
8459             }
8460         }
8461         return false;
8462     }
8463 
8464     /**
8465      * Returns whether the specified package can read the device identifiers.
8466      *
8467      * @param packageName The package name of the app to check for device identifier access.
8468      * @param pid The process id of the package to be checked.
8469      * @param uid The uid of the package to be checked.
8470      * @return whether the package can read the device identifiers.
8471      *
8472      * @hide
8473      */
hasDeviceIdentifierAccess(@onNull String packageName, int pid, int uid)8474     public boolean hasDeviceIdentifierAccess(@NonNull String packageName, int pid, int uid) {
8475         throwIfParentInstance("hasDeviceIdentifierAccess");
8476         if (packageName == null) {
8477             return false;
8478         }
8479         if (mService != null) {
8480             try {
8481                 return mService.checkDeviceIdentifierAccess(packageName, pid, uid);
8482             } catch (RemoteException re) {
8483                 throw re.rethrowFromSystemServer();
8484             }
8485         }
8486         return false;
8487     }
8488 
8489     /**
8490      * Called by a profile owner or device owner to set a default activity that the system selects
8491      * to handle intents that match the given {@link IntentFilter}. This activity will remain the
8492      * default intent handler even if the set of potential event handlers for the intent filter
8493      * changes and if the intent preferences are reset.
8494      * <p>
8495      * Note that the caller should still declare the activity in the manifest, the API just sets
8496      * the activity to be the default one to handle the given intent filter.
8497      * <p>
8498      * The default disambiguation mechanism takes over if the activity is not installed (anymore).
8499      * When the activity is (re)installed, it is automatically reset as default intent handler for
8500      * the filter.
8501      * <p>
8502      * The calling device admin must be a profile owner or device owner. If it is not, a security
8503      * exception will be thrown.
8504      *
8505      * <p>NOTE: Performs disk I/O and shouldn't be called on the main thread.
8506      *
8507      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8508      * @param filter The IntentFilter for which a default handler is added.
8509      * @param activity The Activity that is added as default intent handler.
8510      * @throws SecurityException if {@code admin} is not a device or profile owner.
8511      */
addPersistentPreferredActivity(@onNull ComponentName admin, IntentFilter filter, @NonNull ComponentName activity)8512     public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
8513             @NonNull ComponentName activity) {
8514         throwIfParentInstance("addPersistentPreferredActivity");
8515         if (mService != null) {
8516             try {
8517                 mService.addPersistentPreferredActivity(admin, filter, activity);
8518             } catch (RemoteException e) {
8519                 throw e.rethrowFromSystemServer();
8520             }
8521         }
8522     }
8523 
8524     /**
8525      * Called by a profile owner or device owner to remove all persistent intent handler preferences
8526      * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
8527      * <p>
8528      * The calling device admin must be a profile owner. If it is not, a security exception will be
8529      * thrown.
8530      *
8531      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8532      * @param packageName The name of the package for which preferences are removed.
8533      * @throws SecurityException if {@code admin} is not a device or profile owner.
8534      */
clearPackagePersistentPreferredActivities(@onNull ComponentName admin, String packageName)8535     public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
8536             String packageName) {
8537         throwIfParentInstance("clearPackagePersistentPreferredActivities");
8538         if (mService != null) {
8539             try {
8540                 mService.clearPackagePersistentPreferredActivities(admin, packageName);
8541             } catch (RemoteException e) {
8542                 throw e.rethrowFromSystemServer();
8543             }
8544         }
8545     }
8546 
8547     /**
8548      * Must be called by a device owner or a profile owner of an organization-owned managed profile
8549      * to set the default SMS application.
8550      * <p>
8551      * This method can be called on the {@link DevicePolicyManager} instance, returned by
8552      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
8553      * of an organization-owned managed profile and the package must be a pre-installed system
8554      * package. If called on the parent instance, then the default SMS application is set on the
8555      * personal profile.
8556      *
8557      * @param admin       Which {@link DeviceAdminReceiver} this request is associated with.
8558      * @param packageName The name of the package to set as the default SMS application.
8559      * @throws SecurityException        if {@code admin} is not a device or profile owner or if
8560      *                                  called on the parent profile and the {@code admin} is not a
8561      *                                  profile owner of an organization-owned managed profile.
8562      * @throws IllegalArgumentException if called on the parent profile and the package
8563      *                                  provided is not a pre-installed system package.
8564      */
setDefaultSmsApplication(@onNull ComponentName admin, @NonNull String packageName)8565     public void setDefaultSmsApplication(@NonNull ComponentName admin,
8566             @NonNull String packageName) {
8567         if (mService != null) {
8568             try {
8569                 mService.setDefaultSmsApplication(admin, packageName, mParentInstance);
8570             } catch (RemoteException e) {
8571                 throw e.rethrowFromSystemServer();
8572             }
8573         }
8574     }
8575 
8576     /**
8577      * Called by a profile owner or device owner to grant permission to a package to manage
8578      * application restrictions for the calling user via {@link #setApplicationRestrictions} and
8579      * {@link #getApplicationRestrictions}.
8580      * <p>
8581      * This permission is persistent until it is later cleared by calling this method with a
8582      * {@code null} value or uninstalling the managing package.
8583      * <p>
8584      * The supplied application restriction managing package must be installed when calling this
8585      * API, otherwise an {@link NameNotFoundException} will be thrown.
8586      *
8587      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8588      * @param packageName The package name which will be given access to application restrictions
8589      *            APIs. If {@code null} is given the current package will be cleared.
8590      * @throws SecurityException if {@code admin} is not a device or profile owner.
8591      * @throws NameNotFoundException if {@code packageName} is not found
8592      *
8593      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
8594      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
8595      */
8596     @Deprecated
setApplicationRestrictionsManagingPackage(@onNull ComponentName admin, @Nullable String packageName)8597     public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
8598             @Nullable String packageName) throws NameNotFoundException {
8599         throwIfParentInstance("setApplicationRestrictionsManagingPackage");
8600         if (mService != null) {
8601             try {
8602                 if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
8603                     throw new NameNotFoundException(packageName);
8604                 }
8605             } catch (RemoteException e) {
8606                 throw e.rethrowFromSystemServer();
8607             }
8608         }
8609     }
8610 
8611     /**
8612      * Called by a profile owner or device owner to retrieve the application restrictions managing
8613      * package for the current user, or {@code null} if none is set. If there are multiple
8614      * delegates this function will return one of them.
8615      *
8616      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8617      * @return The package name allowed to manage application restrictions on the current user, or
8618      *         {@code null} if none is set.
8619      * @throws SecurityException if {@code admin} is not a device or profile owner.
8620      *
8621      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
8622      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
8623      */
8624     @Deprecated
8625     @Nullable
getApplicationRestrictionsManagingPackage( @onNull ComponentName admin)8626     public String getApplicationRestrictionsManagingPackage(
8627             @NonNull ComponentName admin) {
8628         throwIfParentInstance("getApplicationRestrictionsManagingPackage");
8629         if (mService != null) {
8630             try {
8631                 return mService.getApplicationRestrictionsManagingPackage(admin);
8632             } catch (RemoteException e) {
8633                 throw e.rethrowFromSystemServer();
8634             }
8635         }
8636         return null;
8637     }
8638 
8639     /**
8640      * Called by any application to find out whether it has been granted permission via
8641      * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
8642      * for the calling user.
8643      *
8644      * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
8645      * that method.
8646      *
8647      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes}
8648      * instead.
8649      */
8650     @Deprecated
isCallerApplicationRestrictionsManagingPackage()8651     public boolean isCallerApplicationRestrictionsManagingPackage() {
8652         throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
8653         if (mService != null) {
8654             try {
8655                 return mService.isCallerApplicationRestrictionsManagingPackage(
8656                         mContext.getPackageName());
8657             } catch (RemoteException e) {
8658                 throw e.rethrowFromSystemServer();
8659             }
8660         }
8661         return false;
8662     }
8663 
8664     /**
8665      * Sets the application restrictions for a given target application running in the calling user.
8666      * <p>
8667      * The caller must be a profile or device owner on that user, or the package allowed to manage
8668      * application restrictions via {@link #setDelegatedScopes} with the
8669      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
8670      * <p>
8671      * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
8672      * <ul>
8673      * <li>{@code boolean}
8674      * <li>{@code int}
8675      * <li>{@code String} or {@code String[]}
8676      * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
8677      * </ul>
8678      * <p>
8679      * If the restrictions are not available yet, but may be applied in the near future, the caller
8680      * can notify the target application of that by adding
8681      * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
8682      * <p>
8683      * The application restrictions are only made visible to the target application via
8684      * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
8685      * owner, and the application restrictions managing package via
8686      * {@link #getApplicationRestrictions}.
8687      *
8688      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
8689      *
8690      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8691      *            {@code null} if called by the application restrictions managing package.
8692      * @param packageName The name of the package to update restricted settings for.
8693      * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
8694      *            set of active restrictions.
8695      * @throws SecurityException if {@code admin} is not a device or profile owner.
8696      * @see #setDelegatedScopes
8697      * @see #DELEGATION_APP_RESTRICTIONS
8698      * @see UserManager#KEY_RESTRICTIONS_PENDING
8699      */
8700     @WorkerThread
setApplicationRestrictions(@ullable ComponentName admin, String packageName, Bundle settings)8701     public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
8702             Bundle settings) {
8703         throwIfParentInstance("setApplicationRestrictions");
8704         if (mService != null) {
8705             try {
8706                 mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName,
8707                         settings);
8708             } catch (RemoteException e) {
8709                 throw e.rethrowFromSystemServer();
8710             }
8711         }
8712     }
8713 
8714     /**
8715      * Sets a list of configuration features to enable for a trust agent component. This is meant to
8716      * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
8717      * agents but those enabled by this function call. If flag
8718      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
8719      * <p>
8720      * For any specific trust agent, whether it is disabled or not depends on the aggregated state
8721      * of each admin's {@link #KEYGUARD_DISABLE_TRUST_AGENTS} setting and its trust agent
8722      * configuration as set by this function call. In particular: if any admin sets
8723      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and does not additionally set any
8724      * trust agent configuration, the trust agent is disabled completely. Otherwise, the trust agent
8725      * will receive the list of configurations from all admins who set
8726      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and aggregate the configurations to determine its
8727      * behavior. The exact meaning of aggregation is trust-agent-specific.
8728      * <p>
8729      * The calling device admin must have requested
8730      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
8731      * if not, a security exception will be thrown.
8732      * <p>
8733      * This method can be called on the {@link DevicePolicyManager} instance returned by
8734      * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
8735      * the parent profile.
8736      * <p>
8737      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, calling
8738      * this method has no effect - no trust agent configuration will be set.
8739      *
8740      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8741      * @param target Component name of the agent to be configured.
8742      * @param configuration Trust-agent-specific feature configuration bundle. Please consult
8743      *        documentation of the specific trust agent to determine the interpretation of this
8744      *        bundle.
8745      * @throws SecurityException if {@code admin} is not an active administrator or does not use
8746      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
8747      */
8748     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setTrustAgentConfiguration(@onNull ComponentName admin, @NonNull ComponentName target, PersistableBundle configuration)8749     public void setTrustAgentConfiguration(@NonNull ComponentName admin,
8750             @NonNull ComponentName target, PersistableBundle configuration) {
8751         if (mService != null) {
8752             try {
8753                 mService.setTrustAgentConfiguration(admin, target, configuration, mParentInstance);
8754             } catch (RemoteException e) {
8755                 throw e.rethrowFromSystemServer();
8756             }
8757         }
8758     }
8759 
8760     /**
8761      * Gets configuration for the given trust agent based on aggregating all calls to
8762      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
8763      * all device admins.
8764      * <p>
8765      * This method can be called on the {@link DevicePolicyManager} instance returned by
8766      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
8767      * on the parent profile.
8768      * <p>
8769      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, null is
8770      * always returned.
8771      *
8772      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
8773      * this function returns a list of configurations for all admins that declare
8774      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
8775      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
8776      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
8777      * for this {@param agent} or calls it with a null configuration, null is returned.
8778      * @param agent Which component to get enabled features for.
8779      * @return configuration for the given trust agent.
8780      */
8781     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent)8782     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
8783             @Nullable ComponentName admin, @NonNull ComponentName agent) {
8784         return getTrustAgentConfiguration(admin, agent, myUserId());
8785     }
8786 
8787     /** @hide per-user version */
8788     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
8789     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent, int userHandle)8790     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
8791             @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
8792         if (mService != null) {
8793             try {
8794                 return mService.getTrustAgentConfiguration(admin, agent, userHandle,
8795                         mParentInstance);
8796             } catch (RemoteException e) {
8797                 throw e.rethrowFromSystemServer();
8798             }
8799         }
8800         return new ArrayList<PersistableBundle>(); // empty list
8801     }
8802 
8803     /**
8804      * Called by a profile owner of a managed profile to set whether caller-Id information from the
8805      * managed profile will be shown in the parent profile, for incoming calls.
8806      * <p>
8807      * The calling device admin must be a profile owner. If it is not, a security exception will be
8808      * thrown.
8809      *
8810      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8811      * @param disabled If true caller-Id information in the managed profile is not displayed.
8812      * @throws SecurityException if {@code admin} is not a profile owner.
8813      */
setCrossProfileCallerIdDisabled(@onNull ComponentName admin, boolean disabled)8814     public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
8815         throwIfParentInstance("setCrossProfileCallerIdDisabled");
8816         if (mService != null) {
8817             try {
8818                 mService.setCrossProfileCallerIdDisabled(admin, disabled);
8819             } catch (RemoteException e) {
8820                 throw e.rethrowFromSystemServer();
8821             }
8822         }
8823     }
8824 
8825     /**
8826      * Called by a profile owner of a managed profile to determine whether or not caller-Id
8827      * information has been disabled.
8828      * <p>
8829      * The calling device admin must be a profile owner. If it is not, a security exception will be
8830      * thrown.
8831      *
8832      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8833      * @throws SecurityException if {@code admin} is not a profile owner.
8834      */
getCrossProfileCallerIdDisabled(@onNull ComponentName admin)8835     public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
8836         throwIfParentInstance("getCrossProfileCallerIdDisabled");
8837         if (mService != null) {
8838             try {
8839                 return mService.getCrossProfileCallerIdDisabled(admin);
8840             } catch (RemoteException e) {
8841                 throw e.rethrowFromSystemServer();
8842             }
8843         }
8844         return false;
8845     }
8846 
8847     /**
8848      * Determine whether or not caller-Id information has been disabled.
8849      *
8850      * @param userHandle The user for whom to check the caller-id permission
8851      * @hide
8852      */
getCrossProfileCallerIdDisabled(UserHandle userHandle)8853     public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
8854         if (mService != null) {
8855             try {
8856                 return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
8857             } catch (RemoteException e) {
8858                 throw e.rethrowFromSystemServer();
8859             }
8860         }
8861         return false;
8862     }
8863 
8864     /**
8865      * Called by a profile owner of a managed profile to set whether contacts search from the
8866      * managed profile will be shown in the parent profile, for incoming calls.
8867      * <p>
8868      * The calling device admin must be a profile owner. If it is not, a security exception will be
8869      * thrown.
8870      *
8871      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8872      * @param disabled If true contacts search in the managed profile is not displayed.
8873      * @throws SecurityException if {@code admin} is not a profile owner.
8874      */
setCrossProfileContactsSearchDisabled(@onNull ComponentName admin, boolean disabled)8875     public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
8876             boolean disabled) {
8877         throwIfParentInstance("setCrossProfileContactsSearchDisabled");
8878         if (mService != null) {
8879             try {
8880                 mService.setCrossProfileContactsSearchDisabled(admin, disabled);
8881             } catch (RemoteException e) {
8882                 throw e.rethrowFromSystemServer();
8883             }
8884         }
8885     }
8886 
8887     /**
8888      * Called by a profile owner of a managed profile to determine whether or not contacts search
8889      * has been disabled.
8890      * <p>
8891      * The calling device admin must be a profile owner. If it is not, a security exception will be
8892      * thrown.
8893      *
8894      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8895      * @throws SecurityException if {@code admin} is not a profile owner.
8896      */
getCrossProfileContactsSearchDisabled(@onNull ComponentName admin)8897     public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
8898         throwIfParentInstance("getCrossProfileContactsSearchDisabled");
8899         if (mService != null) {
8900             try {
8901                 return mService.getCrossProfileContactsSearchDisabled(admin);
8902             } catch (RemoteException e) {
8903                 throw e.rethrowFromSystemServer();
8904             }
8905         }
8906         return false;
8907     }
8908 
8909 
8910     /**
8911      * Determine whether or not contacts search has been disabled.
8912      *
8913      * @param userHandle The user for whom to check the contacts search permission
8914      * @hide
8915      */
getCrossProfileContactsSearchDisabled(@onNull UserHandle userHandle)8916     public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
8917         if (mService != null) {
8918             try {
8919                 return mService
8920                         .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
8921             } catch (RemoteException e) {
8922                 throw e.rethrowFromSystemServer();
8923             }
8924         }
8925         return false;
8926     }
8927 
8928     /**
8929      * Start Quick Contact on the managed profile for the user, if the policy allows.
8930      *
8931      * @hide
8932      */
startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long directoryId, Intent originalIntent)8933     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
8934             boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
8935         if (mService != null) {
8936             try {
8937                 mService.startManagedQuickContact(actualLookupKey, actualContactId,
8938                         isContactIdIgnored, directoryId, originalIntent);
8939             } catch (RemoteException e) {
8940                 throw e.rethrowFromSystemServer();
8941             }
8942         }
8943     }
8944 
8945     /**
8946      * Start Quick Contact on the managed profile for the user, if the policy allows.
8947      * @hide
8948      */
startManagedQuickContact(String actualLookupKey, long actualContactId, Intent originalIntent)8949     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
8950             Intent originalIntent) {
8951         startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
8952                 originalIntent);
8953     }
8954 
8955     /**
8956      * Called by a profile owner of a managed profile to set whether bluetooth devices can access
8957      * enterprise contacts.
8958      * <p>
8959      * The calling device admin must be a profile owner. If it is not, a security exception will be
8960      * thrown.
8961      * <p>
8962      * This API works on managed profile only.
8963      *
8964      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8965      * @param disabled If true, bluetooth devices cannot access enterprise contacts.
8966      * @throws SecurityException if {@code admin} is not a profile owner.
8967      */
setBluetoothContactSharingDisabled(@onNull ComponentName admin, boolean disabled)8968     public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
8969         throwIfParentInstance("setBluetoothContactSharingDisabled");
8970         if (mService != null) {
8971             try {
8972                 mService.setBluetoothContactSharingDisabled(admin, disabled);
8973             } catch (RemoteException e) {
8974                 throw e.rethrowFromSystemServer();
8975             }
8976         }
8977     }
8978 
8979     /**
8980      * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
8981      * cannot access enterprise contacts.
8982      * <p>
8983      * The calling device admin must be a profile owner. If it is not, a security exception will be
8984      * thrown.
8985      * <p>
8986      * This API works on managed profile only.
8987      *
8988      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8989      * @throws SecurityException if {@code admin} is not a profile owner.
8990      */
getBluetoothContactSharingDisabled(@onNull ComponentName admin)8991     public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
8992         throwIfParentInstance("getBluetoothContactSharingDisabled");
8993         if (mService != null) {
8994             try {
8995                 return mService.getBluetoothContactSharingDisabled(admin);
8996             } catch (RemoteException e) {
8997                 throw e.rethrowFromSystemServer();
8998             }
8999         }
9000         return true;
9001     }
9002 
9003     /**
9004      * Determine whether or not Bluetooth devices cannot access contacts.
9005      * <p>
9006      * This API works on managed profile UserHandle only.
9007      *
9008      * @param userHandle The user for whom to check the caller-id permission
9009      * @hide
9010      */
9011     @SystemApi
9012     @RequiresPermission(permission.INTERACT_ACROSS_USERS)
getBluetoothContactSharingDisabled(@onNull UserHandle userHandle)9013     public boolean getBluetoothContactSharingDisabled(@NonNull UserHandle userHandle) {
9014         if (mService != null) {
9015             try {
9016                 return mService.getBluetoothContactSharingDisabledForUser(userHandle
9017                         .getIdentifier());
9018             } catch (RemoteException e) {
9019                 throw e.rethrowFromSystemServer();
9020             }
9021         }
9022         return true;
9023     }
9024 
9025     /**
9026      * Called by the profile owner of a managed profile so that some intents sent in the managed
9027      * profile can also be resolved in the parent, or vice versa. Only activity intents are
9028      * supported.
9029      *
9030      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9031      * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
9032      *            other profile
9033      * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
9034      *            {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
9035      * @throws SecurityException if {@code admin} is not a device or profile owner.
9036      */
addCrossProfileIntentFilter(@onNull ComponentName admin, IntentFilter filter, int flags)9037     public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
9038         throwIfParentInstance("addCrossProfileIntentFilter");
9039         if (mService != null) {
9040             try {
9041                 mService.addCrossProfileIntentFilter(admin, filter, flags);
9042             } catch (RemoteException e) {
9043                 throw e.rethrowFromSystemServer();
9044             }
9045         }
9046     }
9047 
9048     /**
9049      * Called by a profile owner of a managed profile to remove the cross-profile intent filters
9050      * that go from the managed profile to the parent, or from the parent to the managed profile.
9051      * Only removes those that have been set by the profile owner.
9052      * <p>
9053      * <em>Note</em>: A list of default cross profile intent filters are set up by the system when
9054      * the profile is created, some of them ensure the proper functioning of the profile, while
9055      * others enable sharing of data from the parent to the managed profile for user convenience.
9056      * These default intent filters are not cleared when this API is called. If the default cross
9057      * profile data sharing is not desired, they can be disabled with
9058      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE}.
9059      *
9060      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9061      * @throws SecurityException if {@code admin} is not a profile owner.
9062      */
clearCrossProfileIntentFilters(@onNull ComponentName admin)9063     public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
9064         throwIfParentInstance("clearCrossProfileIntentFilters");
9065         if (mService != null) {
9066             try {
9067                 mService.clearCrossProfileIntentFilters(admin);
9068             } catch (RemoteException e) {
9069                 throw e.rethrowFromSystemServer();
9070             }
9071         }
9072     }
9073 
9074     /**
9075      * Called by a profile or device owner to set the permitted
9076      * {@link android.accessibilityservice.AccessibilityService}. When set by
9077      * a device owner or profile owner the restriction applies to all profiles of the user the
9078      * device owner or profile owner is an admin for. By default, the user can use any accessibility
9079      * service. When zero or more packages have been added, accessibility services that are not in
9080      * the list and not part of the system can not be enabled by the user.
9081      * <p>
9082      * Calling with a null value for the list disables the restriction so that all services can be
9083      * used, calling with an empty list only allows the built-in system services. Any non-system
9084      * accessibility service that's currently enabled must be included in the list.
9085      * <p>
9086      * System accessibility services are always available to the user and this method can't
9087      * disable them.
9088      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9089      * @param packageNames List of accessibility service package names.
9090      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
9091      *         contain every enabled non-system accessibility service.
9092      * @throws SecurityException if {@code admin} is not a device or profile owner.
9093      */
setPermittedAccessibilityServices(@onNull ComponentName admin, List<String> packageNames)9094     public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
9095             List<String> packageNames) {
9096         throwIfParentInstance("setPermittedAccessibilityServices");
9097         if (mService != null) {
9098             try {
9099                 return mService.setPermittedAccessibilityServices(admin, packageNames);
9100             } catch (RemoteException e) {
9101                 throw e.rethrowFromSystemServer();
9102             }
9103         }
9104         return false;
9105     }
9106 
9107     /**
9108      * Returns the list of permitted accessibility services set by this device or profile owner.
9109      * <p>
9110      * An empty list means no accessibility services except system services are allowed. Null means
9111      * all accessibility services are allowed.
9112      *
9113      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9114      * @return List of accessiblity service package names.
9115      * @throws SecurityException if {@code admin} is not a device or profile owner.
9116      */
getPermittedAccessibilityServices(@onNull ComponentName admin)9117     public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
9118         throwIfParentInstance("getPermittedAccessibilityServices");
9119         if (mService != null) {
9120             try {
9121                 return mService.getPermittedAccessibilityServices(admin);
9122             } catch (RemoteException e) {
9123                 throw e.rethrowFromSystemServer();
9124             }
9125         }
9126         return null;
9127     }
9128 
9129     /**
9130      * Called by the system to check if a specific accessibility service is disabled by admin.
9131      *
9132      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9133      * @param packageName Accessibility service package name that needs to be checked.
9134      * @param userHandle user id the admin is running as.
9135      * @return true if the accessibility service is permitted, otherwise false.
9136      *
9137      * @hide
9138      */
isAccessibilityServicePermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)9139     public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
9140             @NonNull String packageName, int userHandle) {
9141         if (mService != null) {
9142             try {
9143                 return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
9144                         userHandle);
9145             } catch (RemoteException e) {
9146                 throw e.rethrowFromSystemServer();
9147             }
9148         }
9149         return false;
9150     }
9151 
9152     /**
9153      * Returns the list of accessibility services permitted by the device or profiles
9154      * owners of this user.
9155      *
9156      * <p>Null means all accessibility services are allowed, if a non-null list is returned
9157      * it will contain the intersection of the permitted lists for any device or profile
9158      * owners that apply to this user. It will also include any system accessibility services.
9159      *
9160      * @param userId which user to check for.
9161      * @return List of accessiblity service package names.
9162      * @hide
9163      */
9164      @SystemApi
9165      @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getPermittedAccessibilityServices(int userId)9166      public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
9167         throwIfParentInstance("getPermittedAccessibilityServices");
9168         if (mService != null) {
9169             try {
9170                 return mService.getPermittedAccessibilityServicesForUser(userId);
9171             } catch (RemoteException e) {
9172                 throw e.rethrowFromSystemServer();
9173             }
9174         }
9175         return null;
9176      }
9177 
9178     /**
9179      * Called by a profile or device owner to set the permitted input methods services for this
9180      * user. By default, the user can use any input method.
9181      * <p>
9182      * This method can be called on the {@link DevicePolicyManager} instance,
9183      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
9184      * a profile owner of an organization-owned device.
9185      * <p>
9186      * If called on the parent instance:
9187      * <ul>
9188      *    <li>The permitted input methods will be applied on the personal profile</li>
9189      *    <li>Can only permit all input methods (calling this method with a {@code null} package
9190      *    list) or only permit system input methods (calling this method with an empty package
9191      *    list). This is to prevent the caller from learning which packages are installed on
9192      *    the personal side</li>
9193      * </ul>
9194      * <p>
9195      * When zero or more packages have been added, input method that are not in the list and not
9196      * part of the system can not be enabled by the user. This method will fail if it is called for
9197      * a admin that is not for the foreground user or a profile of the foreground user. Any
9198      * non-system input method service that's currently enabled must be included in the list.
9199      * <p>
9200      * Calling with a null value for the list disables the restriction so that all input methods can
9201      * be used, calling with an empty list disables all but the system's own input methods.
9202      * <p>
9203      * System input methods are always available to the user - this method can't modify this.
9204      *
9205      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9206      * @param packageNames List of input method package names.
9207      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
9208      *        contain every enabled non-system input method service.
9209      * @throws SecurityException if {@code admin} is not a device, profile owner or if called on
9210      *                           the parent profile and the {@code admin} is not a profile owner
9211      *                           of an organization-owned managed profile.
9212      * @throws IllegalArgumentException if called on the parent profile, the {@code admin} is a
9213      *                           profile owner of an organization-owned managed profile and the
9214      *                           list of permitted input method package names is not null or empty.
9215      */
setPermittedInputMethods( @onNull ComponentName admin, List<String> packageNames)9216     public boolean setPermittedInputMethods(
9217             @NonNull ComponentName admin, List<String> packageNames) {
9218         if (mService != null) {
9219             try {
9220                 return mService.setPermittedInputMethods(admin, packageNames, mParentInstance);
9221             } catch (RemoteException e) {
9222                 throw e.rethrowFromSystemServer();
9223             }
9224         }
9225         return false;
9226     }
9227 
9228 
9229     /**
9230      * Returns the list of permitted input methods set by this device or profile owner.
9231      * <p>
9232      * This method can be called on the {@link DevicePolicyManager} instance,
9233      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
9234      * a profile owner of an organization-owned managed profile. If called on the parent instance,
9235      * then the returned list of permitted input methods are those which are applied on the
9236      * personal profile.
9237      * <p>
9238      * An empty list means no input methods except system input methods are allowed. Null means all
9239      * input methods are allowed.
9240      *
9241      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9242      * @return List of input method package names.
9243      * @throws SecurityException if {@code admin} is not a device, profile owner or if called on
9244      *                           the parent profile and the {@code admin} is not a profile owner
9245      *                           of an organization-owned managed profile.
9246      */
getPermittedInputMethods(@onNull ComponentName admin)9247     public @Nullable List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
9248         if (mService != null) {
9249             try {
9250                 return mService.getPermittedInputMethods(admin, mParentInstance);
9251             } catch (RemoteException e) {
9252                 throw e.rethrowFromSystemServer();
9253             }
9254         }
9255         return null;
9256     }
9257 
9258     /**
9259      * Called by the system to check if a specific input method is disabled by admin.
9260      * <p>
9261      * This method can be called on the {@link DevicePolicyManager} instance,
9262      * returned by {@link #getParentProfileInstance(ComponentName)}. If called on the parent
9263      * instance, this method will check whether the given input method is permitted on
9264      * the personal profile.
9265      *
9266      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9267      * @param packageName Input method package name that needs to be checked.
9268      * @param userHandle user id the admin is running as.
9269      * @return true if the input method is permitted, otherwise false.
9270      *
9271      * @hide
9272      */
isInputMethodPermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)9273     public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
9274             @NonNull String packageName, int userHandle) {
9275         if (mService != null) {
9276             try {
9277                 return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle,
9278                         mParentInstance);
9279             } catch (RemoteException e) {
9280                 throw e.rethrowFromSystemServer();
9281             }
9282         }
9283         return false;
9284     }
9285 
9286     /**
9287      * Returns the list of input methods permitted by the device or profiles owners.
9288      *
9289      * <p>On {@link android.os.Build.VERSION_CODES#Q} and later devices, this method returns the
9290      * result for the calling user.</p>
9291      *
9292      * <p>On Android P and prior devices, this method returns the result for the current user.</p>
9293      *
9294      * <p>Null means all input methods are allowed, if a non-null list is returned
9295      * it will contain the intersection of the permitted lists for any device or profile
9296      * owners that apply to this user. It will also include any system input methods.
9297      *
9298      * @return List of input method package names.
9299      * @hide
9300      */
9301     @SystemApi
9302     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getPermittedInputMethodsForCurrentUser()9303     public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
9304         throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
9305         if (mService != null) {
9306             try {
9307                 return mService.getPermittedInputMethodsForCurrentUser();
9308             } catch (RemoteException e) {
9309                 throw e.rethrowFromSystemServer();
9310             }
9311         }
9312         return null;
9313     }
9314 
9315     /**
9316      * Called by a profile owner of a managed profile to set the packages that are allowed to use
9317      * a {@link android.service.notification.NotificationListenerService} in the primary user to
9318      * see notifications from the managed profile. By default all packages are permitted by this
9319      * policy. When zero or more packages have been added, notification listeners installed on the
9320      * primary user that are not in the list and are not part of the system won't receive events
9321      * for managed profile notifications.
9322      * <p>
9323      * Calling with a {@code null} value for the list disables the restriction so that all
9324      * notification listener services be used. Calling with an empty list disables all but the
9325      * system's own notification listeners. System notification listener services are always
9326      * available to the user.
9327      * <p>
9328      * If a device or profile owner want to stop notification listeners in their user from seeing
9329      * that user's notifications they should prevent that service from running instead (e.g. via
9330      * {@link #setApplicationHidden(ComponentName, String, boolean)})
9331      *
9332      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9333      * @param packageList List of package names to allowlist
9334      * @return true if setting the restriction succeeded. It will fail if called outside a managed
9335      * profile
9336      * @throws SecurityException if {@code admin} is not a profile owner.
9337      *
9338      * @see android.service.notification.NotificationListenerService
9339      */
setPermittedCrossProfileNotificationListeners( @onNull ComponentName admin, @Nullable List<String> packageList)9340     public boolean setPermittedCrossProfileNotificationListeners(
9341             @NonNull ComponentName admin, @Nullable List<String> packageList) {
9342         throwIfParentInstance("setPermittedCrossProfileNotificationListeners");
9343         if (mService != null) {
9344             try {
9345                 return mService.setPermittedCrossProfileNotificationListeners(admin, packageList);
9346             } catch (RemoteException e) {
9347                 throw e.rethrowFromSystemServer();
9348             }
9349         }
9350         return false;
9351     }
9352 
9353     /**
9354      * Returns the list of packages installed on the primary user that allowed to use a
9355      * {@link android.service.notification.NotificationListenerService} to receive
9356      * notifications from this managed profile, as set by the profile owner.
9357      * <p>
9358      * An empty list means no notification listener services except system ones are allowed.
9359      * A {@code null} return value indicates that all notification listeners are allowed.
9360      */
getPermittedCrossProfileNotificationListeners( @onNull ComponentName admin)9361     public @Nullable List<String> getPermittedCrossProfileNotificationListeners(
9362             @NonNull ComponentName admin) {
9363         throwIfParentInstance("getPermittedCrossProfileNotificationListeners");
9364         if (mService != null) {
9365             try {
9366                 return mService.getPermittedCrossProfileNotificationListeners(admin);
9367             } catch (RemoteException e) {
9368                 throw e.rethrowFromSystemServer();
9369             }
9370         }
9371         return null;
9372     }
9373 
9374     /**
9375      * Returns true if {@code NotificationListenerServices} from the given package are allowed to
9376      * receive events for notifications from the given user id. Can only be called by the system uid
9377      *
9378      * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List)
9379      *
9380      * @hide
9381      */
isNotificationListenerServicePermitted( @onNull String packageName, @UserIdInt int userId)9382     public boolean isNotificationListenerServicePermitted(
9383             @NonNull String packageName, @UserIdInt int userId) {
9384         if (mService != null) {
9385             try {
9386                 return mService.isNotificationListenerServicePermitted(packageName, userId);
9387             } catch (RemoteException e) {
9388                 throw e.rethrowFromSystemServer();
9389             }
9390         }
9391         return true;
9392     }
9393 
9394     /**
9395      * Get the list of apps to keep around as APKs even if no user has currently installed it. This
9396      * function can be called by a device owner or by a delegate given the
9397      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
9398      * <p>
9399      * Please note that packages returned in this method are not automatically pre-cached.
9400      *
9401      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9402      *            {@code null} if the caller is a keep uninstalled packages delegate.
9403      * @return List of package names to keep cached.
9404      * @see #setDelegatedScopes
9405      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
9406      */
getKeepUninstalledPackages(@ullable ComponentName admin)9407     public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) {
9408         throwIfParentInstance("getKeepUninstalledPackages");
9409         if (mService != null) {
9410             try {
9411                 return mService.getKeepUninstalledPackages(admin, mContext.getPackageName());
9412             } catch (RemoteException e) {
9413                 throw e.rethrowFromSystemServer();
9414             }
9415         }
9416         return null;
9417     }
9418 
9419     /**
9420      * Set a list of apps to keep around as APKs even if no user has currently installed it. This
9421      * function can be called by a device owner or by a delegate given the
9422      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
9423      *
9424      * <p>Please note that setting this policy does not imply that specified apps will be
9425      * automatically pre-cached.</p>
9426      *
9427      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9428      *            {@code null} if the caller is a keep uninstalled packages delegate.
9429      * @param packageNames List of package names to keep cached.
9430      * @throws SecurityException if {@code admin} is not a device owner.
9431      * @see #setDelegatedScopes
9432      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
9433      */
setKeepUninstalledPackages(@ullable ComponentName admin, @NonNull List<String> packageNames)9434     public void setKeepUninstalledPackages(@Nullable ComponentName admin,
9435             @NonNull List<String> packageNames) {
9436         throwIfParentInstance("setKeepUninstalledPackages");
9437         if (mService != null) {
9438             try {
9439                 mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames);
9440             } catch (RemoteException e) {
9441                 throw e.rethrowFromSystemServer();
9442             }
9443         }
9444     }
9445 
9446     /**
9447       * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
9448       */
9449     public static final int SKIP_SETUP_WIZARD = 0x0001;
9450 
9451     /**
9452      * Flag used by {@link #createAndManageUser} to specify that the user should be created
9453      * ephemeral. Ephemeral users will be removed after switching to another user or rebooting the
9454      * device.
9455      */
9456     public static final int MAKE_USER_EPHEMERAL = 0x0002;
9457 
9458     /**
9459      * Flag used by {@link #createAndManageUser} to specify that the user should be created as a
9460      * demo user.
9461      * @hide
9462      */
9463     public static final int MAKE_USER_DEMO = 0x0004;
9464 
9465     /**
9466      * Flag used by {@link #createAndManageUser} to specify that the newly created user should skip
9467      * the disabling of system apps during provisioning.
9468      */
9469     public static final int LEAVE_ALL_SYSTEM_APPS_ENABLED = 0x0010;
9470 
9471     /**
9472      * @hide
9473      */
9474     @IntDef(flag = true, prefix = { "SKIP_", "MAKE_USER_", "START_", "LEAVE_" }, value = {
9475             SKIP_SETUP_WIZARD,
9476             MAKE_USER_EPHEMERAL,
9477             MAKE_USER_DEMO,
9478             LEAVE_ALL_SYSTEM_APPS_ENABLED
9479     })
9480     @Retention(RetentionPolicy.SOURCE)
9481     public @interface CreateAndManageUserFlags {}
9482 
9483     /**
9484      * Called by a device owner to create a user with the specified name and a given component of
9485      * the calling package as profile owner. The UserHandle returned by this method should not be
9486      * persisted as user handles are recycled as users are removed and created. If you need to
9487      * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
9488      * user will not be started in the background.
9489      * <p>
9490      * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
9491      * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
9492      * be registered as an active admin on the new user. The profile owner package will be installed
9493      * on the new user.
9494      * <p>
9495      * If the adminExtras are not null, they will be stored on the device until the user is started
9496      * for the first time. Then the extras will be passed to the admin when onEnable is called.
9497      * <p>From {@link android.os.Build.VERSION_CODES#P} onwards, if targeting
9498      * {@link android.os.Build.VERSION_CODES#P}, throws {@link UserOperationException} instead of
9499      * returning {@code null} on failure.
9500      *
9501      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9502      * @param name The user's name.
9503      * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
9504      *            same package as admin, otherwise no user is created and an
9505      *            IllegalArgumentException is thrown.
9506      * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
9507      *            user.
9508      * @param flags {@link #SKIP_SETUP_WIZARD}, {@link #MAKE_USER_EPHEMERAL} and
9509      *        {@link #LEAVE_ALL_SYSTEM_APPS_ENABLED} are supported.
9510      * @see UserHandle
9511      * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
9512      *         user could not be created.
9513      * @throws SecurityException if {@code admin} is not a device owner.
9514      * @throws UserOperationException if the user could not be created and the calling app is
9515      * targeting {@link android.os.Build.VERSION_CODES#P} and running on
9516      * {@link android.os.Build.VERSION_CODES#P}.
9517      */
createAndManageUser(@onNull ComponentName admin, @NonNull String name, @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras, @CreateAndManageUserFlags int flags)9518     public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
9519             @NonNull String name,
9520             @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
9521             @CreateAndManageUserFlags int flags) {
9522         throwIfParentInstance("createAndManageUser");
9523         try {
9524             return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
9525         } catch (ServiceSpecificException e) {
9526             throw new UserOperationException(e.getMessage(), e.errorCode);
9527         } catch (RemoteException re) {
9528             throw re.rethrowFromSystemServer();
9529         }
9530     }
9531 
9532     /**
9533      * Called by a device owner to remove a user/profile and all associated data. The primary user
9534      * can not be removed.
9535      *
9536      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9537      * @param userHandle the user to remove.
9538      * @return {@code true} if the user was removed, {@code false} otherwise.
9539      * @throws SecurityException if {@code admin} is not a device owner.
9540      */
removeUser(@onNull ComponentName admin, @NonNull UserHandle userHandle)9541     public boolean removeUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) {
9542         throwIfParentInstance("removeUser");
9543         try {
9544             return mService.removeUser(admin, userHandle);
9545         } catch (RemoteException re) {
9546             throw re.rethrowFromSystemServer();
9547         }
9548     }
9549 
9550     /**
9551      * Called by a device owner to switch the specified secondary user to the foreground.
9552      *
9553      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9554      * @param userHandle the user to switch to; null will switch to primary.
9555      * @return {@code true} if the switch was successful, {@code false} otherwise.
9556      * @throws SecurityException if {@code admin} is not a device owner.
9557      * @see Intent#ACTION_USER_FOREGROUND
9558      * @see #getSecondaryUsers(ComponentName)
9559      */
switchUser(@onNull ComponentName admin, @Nullable UserHandle userHandle)9560     public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
9561         throwIfParentInstance("switchUser");
9562         try {
9563             return mService.switchUser(admin, userHandle);
9564         } catch (RemoteException re) {
9565             throw re.rethrowFromSystemServer();
9566         }
9567     }
9568 
9569     /**
9570      * Called by a device owner to start the specified secondary user in background.
9571      *
9572      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9573      * @param userHandle the user to be started in background.
9574      * @return one of the following result codes:
9575      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
9576      * {@link UserManager#USER_OPERATION_SUCCESS},
9577      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
9578      * {@link UserManager#USER_OPERATION_ERROR_MAX_RUNNING_USERS},
9579      * @throws SecurityException if {@code admin} is not a device owner.
9580      * @see #getSecondaryUsers(ComponentName)
9581      */
startUserInBackground( @onNull ComponentName admin, @NonNull UserHandle userHandle)9582     public @UserOperationResult int startUserInBackground(
9583             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
9584         throwIfParentInstance("startUserInBackground");
9585         try {
9586             return mService.startUserInBackground(admin, userHandle);
9587         } catch (RemoteException re) {
9588             throw re.rethrowFromSystemServer();
9589         }
9590     }
9591 
9592     /**
9593      * Called by a device owner to stop the specified secondary user.
9594      *
9595      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9596      * @param userHandle the user to be stopped.
9597      * @return one of the following result codes:
9598      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
9599      * {@link UserManager#USER_OPERATION_SUCCESS},
9600      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
9601      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
9602      * @throws SecurityException if {@code admin} is not a device owner.
9603      * @see #getSecondaryUsers(ComponentName)
9604      */
stopUser( @onNull ComponentName admin, @NonNull UserHandle userHandle)9605     public @UserOperationResult int stopUser(
9606             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
9607         throwIfParentInstance("stopUser");
9608         try {
9609             return mService.stopUser(admin, userHandle);
9610         } catch (RemoteException re) {
9611             throw re.rethrowFromSystemServer();
9612         }
9613     }
9614 
9615     /**
9616      * Called by a profile owner of secondary user that is affiliated with the device to stop the
9617      * calling user and switch back to primary user.
9618      *
9619      * <p>Notice that on devices running with
9620      * {@link UserManager#isHeadlessSystemUserMode() headless system user mode}, there is no primary
9621      * user, so it switches back to the user that was in the foreground before the first call to
9622      * {@link #switchUser(ComponentName, UserHandle)} (or fails with
9623      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN} if that method was not called prior to this
9624      * call).
9625      *
9626      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9627      * @return one of the following result codes:
9628      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
9629      * {@link UserManager#USER_OPERATION_SUCCESS},
9630      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
9631      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
9632      * @throws SecurityException if {@code admin} is not a profile owner affiliated with the device.
9633      * @see #getSecondaryUsers(ComponentName)
9634      */
logoutUser(@onNull ComponentName admin)9635     public @UserOperationResult int logoutUser(@NonNull ComponentName admin) {
9636         throwIfParentInstance("logoutUser");
9637         try {
9638             return mService.logoutUser(admin);
9639         } catch (RemoteException re) {
9640             throw re.rethrowFromSystemServer();
9641         }
9642     }
9643 
9644     /**
9645      * Gets the user a {@link #logoutUser(ComponentName)} call would switch to,
9646      * or {@link UserHandle#USER_NULL} if the current user is not in a session.
9647      *
9648      * @hide
9649      */
9650     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getLogoutUserId()9651     public @UserIdInt int getLogoutUserId() {
9652         try {
9653             return mService.getLogoutUserId();
9654         } catch (RemoteException re) {
9655             throw re.rethrowFromSystemServer();
9656         }
9657     }
9658 
9659     /**
9660      * Clears the user that {@link #logoutUser(ComponentName)} would switch to.
9661      *
9662      * <p>Typically used by system UI after it logout a session.
9663      *
9664      * @hide
9665      */
9666     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
clearLogoutUser()9667     public void clearLogoutUser() {
9668         try {
9669             mService.clearLogoutUser();
9670         } catch (RemoteException re) {
9671             throw re.rethrowFromSystemServer();
9672         }
9673     }
9674 
9675     /**
9676      * Called by a device owner to list all secondary users on the device. Managed profiles are not
9677      * considered as secondary users.
9678      * <p> Used for various user management APIs, including {@link #switchUser}, {@link #removeUser}
9679      * and {@link #stopUser}.
9680      *
9681      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9682      * @return list of other {@link UserHandle}s on the device.
9683      * @throws SecurityException if {@code admin} is not a device owner.
9684      * @see #removeUser(ComponentName, UserHandle)
9685      * @see #switchUser(ComponentName, UserHandle)
9686      * @see #startUserInBackground(ComponentName, UserHandle)
9687      * @see #stopUser(ComponentName, UserHandle)
9688      */
getSecondaryUsers(@onNull ComponentName admin)9689     public List<UserHandle> getSecondaryUsers(@NonNull ComponentName admin) {
9690         throwIfParentInstance("getSecondaryUsers");
9691         try {
9692             return mService.getSecondaryUsers(admin);
9693         } catch (RemoteException re) {
9694             throw re.rethrowFromSystemServer();
9695         }
9696     }
9697 
9698     /**
9699      * Checks if the profile owner is running in an ephemeral user.
9700      *
9701      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9702      * @return whether the profile owner is running in an ephemeral user.
9703      */
isEphemeralUser(@onNull ComponentName admin)9704     public boolean isEphemeralUser(@NonNull ComponentName admin) {
9705         throwIfParentInstance("isEphemeralUser");
9706         try {
9707             return mService.isEphemeralUser(admin);
9708         } catch (RemoteException re) {
9709             throw re.rethrowFromSystemServer();
9710         }
9711     }
9712 
9713     /**
9714      * Retrieves the application restrictions for a given target application running in the calling
9715      * user.
9716      * <p>
9717      * The caller must be a profile or device owner on that user, or the package allowed to manage
9718      * application restrictions via {@link #setDelegatedScopes} with the
9719      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
9720      *
9721      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
9722      *
9723      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9724      *            {@code null} if called by the application restrictions managing package.
9725      * @param packageName The name of the package to fetch restricted settings of.
9726      * @return {@link Bundle} of settings corresponding to what was set last time
9727      *         {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
9728      *         {@link Bundle} if no restrictions have been set.
9729      * @throws SecurityException if {@code admin} is not a device or profile owner.
9730      * @see #setDelegatedScopes
9731      * @see #DELEGATION_APP_RESTRICTIONS
9732      */
9733     @WorkerThread
getApplicationRestrictions( @ullable ComponentName admin, String packageName)9734     public @NonNull Bundle getApplicationRestrictions(
9735             @Nullable ComponentName admin, String packageName) {
9736         throwIfParentInstance("getApplicationRestrictions");
9737         if (mService != null) {
9738             try {
9739                 return mService.getApplicationRestrictions(admin, mContext.getPackageName(),
9740                         packageName);
9741             } catch (RemoteException e) {
9742                 throw e.rethrowFromSystemServer();
9743             }
9744         }
9745         return null;
9746     }
9747 
9748     /**
9749      * Called by a profile or device owner to set a user restriction specified by the key.
9750      * <p>
9751      * The calling device admin must be a profile or device owner; if it is not, a security
9752      * exception will be thrown.
9753      * <p>
9754      * The profile owner of an organization-owned managed profile may invoke this method on
9755      * the {@link DevicePolicyManager} instance it obtained from
9756      * {@link #getParentProfileInstance(ComponentName)}, for enforcing device-wide restrictions.
9757      * <p>
9758      * See the constants in {@link android.os.UserManager} for the list of restrictions that can
9759      * be enforced device-wide.
9760      *
9761      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9762      * @param key   The key of the restriction.
9763      * @throws SecurityException if {@code admin} is not a device or profile owner.
9764      */
addUserRestriction(@onNull ComponentName admin, @UserManager.UserRestrictionKey String key)9765     public void addUserRestriction(@NonNull ComponentName admin,
9766             @UserManager.UserRestrictionKey String key) {
9767         if (mService != null) {
9768             try {
9769                 mService.setUserRestriction(admin, key, true, mParentInstance);
9770             } catch (RemoteException e) {
9771                 throw e.rethrowFromSystemServer();
9772             }
9773         }
9774     }
9775 
9776     /**
9777      * Called by a profile or device owner to clear a user restriction specified by the key.
9778      * <p>
9779      * The calling device admin must be a profile or device owner; if it is not, a security
9780      * exception will be thrown.
9781      * <p>
9782      * The profile owner of an organization-owned managed profile may invoke this method on
9783      * the {@link DevicePolicyManager} instance it obtained from
9784      * {@link #getParentProfileInstance(ComponentName)}, for clearing device-wide restrictions.
9785      * <p>
9786      * See the constants in {@link android.os.UserManager} for the list of restrictions.
9787      *
9788      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9789      * @param key   The key of the restriction.
9790      * @throws SecurityException if {@code admin} is not a device or profile owner.
9791      */
clearUserRestriction(@onNull ComponentName admin, @UserManager.UserRestrictionKey String key)9792     public void clearUserRestriction(@NonNull ComponentName admin,
9793             @UserManager.UserRestrictionKey String key) {
9794         if (mService != null) {
9795             try {
9796                 mService.setUserRestriction(admin, key, false, mParentInstance);
9797             } catch (RemoteException e) {
9798                 throw e.rethrowFromSystemServer();
9799             }
9800         }
9801     }
9802 
9803     /**
9804      * Called by a profile or device owner to get user restrictions set with
9805      * {@link #addUserRestriction(ComponentName, String)}.
9806      * <p>
9807      * The target user may have more restrictions set by the system or other device owner / profile
9808      * owner. To get all the user restrictions currently set, use
9809      * {@link UserManager#getUserRestrictions()}.
9810      * <p>
9811      * The profile owner of an organization-owned managed profile may invoke this method on
9812      * the {@link DevicePolicyManager} instance it obtained from
9813      * {@link #getParentProfileInstance(ComponentName)}, for retrieving device-wide restrictions
9814      * it previously set with {@link #addUserRestriction(ComponentName, String)}.
9815      *
9816      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9817      * @return a {@link Bundle} whose keys are the user restrictions, and the values a
9818      * {@code boolean} indicating whether the restriction is set.
9819      * @throws SecurityException if {@code admin} is not a device or profile owner.
9820      */
getUserRestrictions(@onNull ComponentName admin)9821     public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
9822         Bundle ret = null;
9823         if (mService != null) {
9824             try {
9825                 ret = mService.getUserRestrictions(admin, mParentInstance);
9826             } catch (RemoteException e) {
9827                 throw e.rethrowFromSystemServer();
9828             }
9829         }
9830         return ret == null ? new Bundle() : ret;
9831     }
9832 
9833     /**
9834      * Called by any app to display a support dialog when a feature was disabled by an admin.
9835      * This returns an intent that can be used with {@link Context#startActivity(Intent)} to
9836      * display the dialog. It will tell the user that the feature indicated by {@code restriction}
9837      * was disabled by an admin, and include a link for more information. The default content of
9838      * the dialog can be changed by the restricting admin via
9839      * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not
9840      * set (i.e. the feature is available), then the return value will be {@code null}.
9841      * @param restriction Indicates for which feature the dialog should be displayed. Can be a
9842      *            user restriction from {@link UserManager}, e.g.
9843      *            {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants
9844      *            {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
9845      * @return Intent An intent to be used to start the dialog-activity if the restriction is
9846      *            set by an admin, or null if the restriction does not exist or no admin set it.
9847      */
createAdminSupportIntent(@onNull String restriction)9848     public Intent createAdminSupportIntent(@NonNull String restriction) {
9849         throwIfParentInstance("createAdminSupportIntent");
9850         if (mService != null) {
9851             try {
9852                 return mService.createAdminSupportIntent(restriction);
9853             } catch (RemoteException e) {
9854                 throw e.rethrowFromSystemServer();
9855             }
9856         }
9857         return null;
9858     }
9859 
9860     /**
9861      * @param userId      The user for whom to retrieve information.
9862      * @param restriction The restriction enforced by admin. It could be any user restriction or
9863      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and
9864      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}.
9865      * @return Details of admin and user which enforced the restriction for the userId. If
9866      * restriction is null, profile owner for the user or device owner info is returned.
9867      * @hide
9868      */
getEnforcingAdminAndUserDetails(int userId, @Nullable String restriction)9869     public @Nullable Bundle getEnforcingAdminAndUserDetails(int userId,
9870             @Nullable String restriction) {
9871         if (mService != null) {
9872             try {
9873                 return mService.getEnforcingAdminAndUserDetails(userId, restriction);
9874             } catch (RemoteException e) {
9875                 throw e.rethrowFromSystemServer();
9876             }
9877         }
9878         return null;
9879     }
9880 
9881     /**
9882      * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and
9883      * actual package file remain. This function can be called by a device owner, profile owner, or
9884      * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
9885      * {@link #setDelegatedScopes}.
9886      * <p>
9887      * This method can be called on the {@link DevicePolicyManager} instance, returned by
9888      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
9889      * of an organization-owned managed profile and the package must be a system package. If called
9890      * on the parent instance, then the package is hidden or unhidden in the personal profile.
9891      *
9892      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9893      *            {@code null} if the caller is a package access delegate.
9894      * @param packageName The name of the package to hide or unhide.
9895      * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
9896      *            unhidden.
9897      * @return boolean Whether the hidden setting of the package was successfully updated.
9898      * @throws SecurityException if {@code admin} is not a device or profile owner or if called on
9899      *            the parent profile and the {@code admin} is not a profile owner of an
9900      *            organization-owned managed profile.
9901      * @throws IllegalArgumentException if called on the parent profile and the package provided
9902      *            is not a system package.
9903      * @see #setDelegatedScopes
9904      * @see #DELEGATION_PACKAGE_ACCESS
9905      */
setApplicationHidden(@onNull ComponentName admin, String packageName, boolean hidden)9906     public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
9907             boolean hidden) {
9908         if (mService != null) {
9909             try {
9910                 return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName,
9911                         hidden, mParentInstance);
9912             } catch (RemoteException e) {
9913                 throw e.rethrowFromSystemServer();
9914             }
9915         }
9916         return false;
9917     }
9918 
9919     /**
9920      * Determine if a package is hidden. This function can be called by a device owner, profile
9921      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
9922      * {@link #setDelegatedScopes}.
9923      * <p>
9924      * This method can be called on the {@link DevicePolicyManager} instance, returned by
9925      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
9926      * of an organization-owned managed profile and the package must be a system package. If called
9927      * on the parent instance, this will determine whether the package is hidden or unhidden in the
9928      * personal profile.
9929      *
9930      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9931      *            {@code null} if the caller is a package access delegate.
9932      * @param packageName The name of the package to retrieve the hidden status of.
9933      * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
9934      * @throws SecurityException if {@code admin} is not a device or profile owner or if called on
9935      *            the parent profile and the {@code admin} is not a profile owner of an
9936      *            organization-owned managed profile.
9937      * @throws IllegalArgumentException if called on the parent profile and the package provided
9938      *            is not a system package.
9939      * @see #setDelegatedScopes
9940      * @see #DELEGATION_PACKAGE_ACCESS
9941      */
isApplicationHidden(@onNull ComponentName admin, String packageName)9942     public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
9943         if (mService != null) {
9944             try {
9945                 return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName,
9946                         mParentInstance);
9947             } catch (RemoteException e) {
9948                 throw e.rethrowFromSystemServer();
9949             }
9950         }
9951         return false;
9952     }
9953 
9954     /**
9955      * Re-enable a system app that was disabled by default when the user was initialized. This
9956      * function can be called by a device owner, profile owner, or by a delegate given the
9957      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
9958      *
9959      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9960      *            {@code null} if the caller is an enable system app delegate.
9961      * @param packageName The package to be re-enabled in the calling profile.
9962      * @throws SecurityException if {@code admin} is not a device or profile owner.
9963      * @see #setDelegatedScopes
9964      * @see #DELEGATION_PACKAGE_ACCESS
9965      */
enableSystemApp(@onNull ComponentName admin, String packageName)9966     public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
9967         throwIfParentInstance("enableSystemApp");
9968         if (mService != null) {
9969             try {
9970                 mService.enableSystemApp(admin, mContext.getPackageName(), packageName);
9971             } catch (RemoteException e) {
9972                 throw e.rethrowFromSystemServer();
9973             }
9974         }
9975     }
9976 
9977     /**
9978      * Re-enable system apps by intent that were disabled by default when the user was initialized.
9979      * This function can be called by a device owner, profile owner, or by a delegate given the
9980      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
9981      *
9982      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9983      *            {@code null} if the caller is an enable system app delegate.
9984      * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
9985      *            intent will be re-enabled in the calling profile.
9986      * @return int The number of activities that matched the intent and were installed.
9987      * @throws SecurityException if {@code admin} is not a device or profile owner.
9988      * @see #setDelegatedScopes
9989      * @see #DELEGATION_PACKAGE_ACCESS
9990      */
enableSystemApp(@onNull ComponentName admin, Intent intent)9991     public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
9992         throwIfParentInstance("enableSystemApp");
9993         if (mService != null) {
9994             try {
9995                 return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent);
9996             } catch (RemoteException e) {
9997                 throw e.rethrowFromSystemServer();
9998             }
9999         }
10000         return 0;
10001     }
10002 
10003     /**
10004      * Install an existing package that has been installed in another user, or has been kept after
10005      * removal via {@link #setKeepUninstalledPackages}.
10006      * This function can be called by a device owner, profile owner or a delegate given
10007      * the {@link #DELEGATION_INSTALL_EXISTING_PACKAGE} scope via {@link #setDelegatedScopes}.
10008      * When called in a secondary user or managed profile, the user/profile must be affiliated with
10009      * the device. See {@link #isAffiliatedUser}.
10010      *
10011      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10012      * @param packageName The package to be installed in the calling profile.
10013      * @return {@code true} if the app is installed; {@code false} otherwise.
10014      * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
10015      * an affiliated user or profile.
10016      * @see #setKeepUninstalledPackages
10017      * @see #setDelegatedScopes
10018      * @see #isAffiliatedUser
10019      * @see #DELEGATION_PACKAGE_ACCESS
10020      */
installExistingPackage(@onNull ComponentName admin, String packageName)10021     public boolean installExistingPackage(@NonNull ComponentName admin, String packageName) {
10022         throwIfParentInstance("installExistingPackage");
10023         if (mService != null) {
10024             try {
10025                 return mService.installExistingPackage(admin, mContext.getPackageName(),
10026                         packageName);
10027             } catch (RemoteException e) {
10028                 throw e.rethrowFromSystemServer();
10029             }
10030         }
10031         return false;
10032     }
10033 
10034     /**
10035      * Called by a device owner or profile owner to disable account management for a specific type
10036      * of account.
10037      * <p>
10038      * The calling device admin must be a device owner or profile owner. If it is not, a security
10039      * exception will be thrown.
10040      * <p>
10041      * When account management is disabled for an account type, adding or removing an account of
10042      * that type will not be possible.
10043      * <p>
10044      * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
10045      * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
10046      * management for a specific type is disabled.
10047      * <p>
10048      * This method may be called on the {@code DevicePolicyManager} instance returned from
10049      * {@link #getParentProfileInstance(ComponentName)} by the profile owner on an
10050      * organization-owned device, to restrict accounts that may not be managed on the primary
10051      * profile.
10052      *
10053      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10054      * @param accountType For which account management is disabled or enabled.
10055      * @param disabled The boolean indicating that account management will be disabled (true) or
10056      *            enabled (false).
10057      * @throws SecurityException if {@code admin} is not a device or profile owner.
10058      */
setAccountManagementDisabled(@onNull ComponentName admin, String accountType, boolean disabled)10059     public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
10060             boolean disabled) {
10061         if (mService != null) {
10062             try {
10063                 mService.setAccountManagementDisabled(admin, accountType, disabled,
10064                         mParentInstance);
10065             } catch (RemoteException e) {
10066                 throw e.rethrowFromSystemServer();
10067             }
10068         }
10069     }
10070 
10071     /**
10072      * Gets the array of accounts for which account management is disabled by the profile owner
10073      * or device owner.
10074      *
10075      * <p> Account management can be disabled/enabled by calling
10076      * {@link #setAccountManagementDisabled}.
10077      * <p>
10078      * This method may be called on the {@code DevicePolicyManager} instance returned from
10079      * {@link #getParentProfileInstance(ComponentName)}. Note that only a profile owner on
10080      * an organization-owned device can affect account types on the parent profile instance.
10081      *
10082      * @return a list of account types for which account management has been disabled.
10083      *
10084      * @see #setAccountManagementDisabled
10085      */
getAccountTypesWithManagementDisabled()10086     public @Nullable String[] getAccountTypesWithManagementDisabled() {
10087         return getAccountTypesWithManagementDisabledAsUser(myUserId(), mParentInstance);
10088     }
10089 
10090     /**
10091      * @see #getAccountTypesWithManagementDisabled()
10092      * Note that calling this method on the parent profile instance will return the same
10093      * value as calling it on the main {@code DevicePolicyManager} instance.
10094      * @hide
10095      */
getAccountTypesWithManagementDisabledAsUser(int userId)10096     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
10097         return getAccountTypesWithManagementDisabledAsUser(userId, false);
10098     }
10099 
10100     /**
10101      * @see #getAccountTypesWithManagementDisabled()
10102      * @hide
10103      */
getAccountTypesWithManagementDisabledAsUser( int userId, boolean parentInstance)10104     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(
10105             int userId, boolean parentInstance) {
10106         if (mService != null) {
10107             try {
10108                 return mService.getAccountTypesWithManagementDisabledAsUser(userId, parentInstance);
10109             } catch (RemoteException e) {
10110                 throw e.rethrowFromSystemServer();
10111             }
10112         }
10113 
10114         return null;
10115     }
10116 
10117     /**
10118      * Called by device owner or profile owner to set whether a secondary lockscreen needs to be
10119      * shown.
10120      *
10121      * <p>The secondary lockscreen will by displayed after the primary keyguard security screen
10122      * requirements are met. To provide the lockscreen content the DO/PO will need to provide a
10123      * service handling the {@link #ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE} intent action,
10124      * extending the {@link DevicePolicyKeyguardService} class.
10125      *
10126      * <p>Relevant interactions on the secondary lockscreen should be communicated back to the
10127      * keyguard via {@link IKeyguardCallback}, such as when the screen is ready to be dismissed.
10128      *
10129      * <p>This API, and associated APIs, can only be called by the default supervision app when it
10130      * is set as the device owner or profile owner.
10131      *
10132      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10133      * @param enabled Whether or not the lockscreen needs to be shown.
10134      * @throws SecurityException if {@code admin} is not a device or profile owner.
10135      * @see #isSecondaryLockscreenEnabled
10136      * @hide
10137      **/
10138     @SystemApi
setSecondaryLockscreenEnabled(@onNull ComponentName admin, boolean enabled)10139     public void setSecondaryLockscreenEnabled(@NonNull ComponentName admin, boolean enabled) {
10140         throwIfParentInstance("setSecondaryLockscreenEnabled");
10141         if (mService != null) {
10142             try {
10143                 mService.setSecondaryLockscreenEnabled(admin, enabled);
10144             } catch (RemoteException e) {
10145                 throw e.rethrowFromSystemServer();
10146             }
10147         }
10148     }
10149 
10150     /**
10151      * Returns whether the secondary lock screen needs to be shown.
10152      * @see #setSecondaryLockscreenEnabled
10153      * @hide
10154      */
10155     @SystemApi
isSecondaryLockscreenEnabled(@onNull UserHandle userHandle)10156     public boolean isSecondaryLockscreenEnabled(@NonNull UserHandle userHandle) {
10157         throwIfParentInstance("isSecondaryLockscreenEnabled");
10158         if (mService != null) {
10159             try {
10160                 return mService.isSecondaryLockscreenEnabled(userHandle);
10161             } catch (RemoteException e) {
10162                 throw e.rethrowFromSystemServer();
10163             }
10164         }
10165         return false;
10166     }
10167 
10168     /**
10169      * Sets which packages may enter lock task mode.
10170      * <p>
10171      * Any packages that share uid with an allowed package will also be allowed to activate lock
10172      * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
10173      * package list results in locked tasks belonging to those packages to be finished.
10174      * <p>
10175      * This function can only be called by the device owner, a profile owner of an affiliated user
10176      * or profile, or the profile owner when no device owner is set. See {@link #isAffiliatedUser}.
10177      * Any package set via this method will be cleared if the user becomes unaffiliated.
10178      *
10179      * @param packages The list of packages allowed to enter lock task mode
10180      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10181      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
10182      * affiliated user or profile, or the profile owner when no device owner is set.
10183      * @see #isAffiliatedUser
10184      * @see Activity#startLockTask()
10185      * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
10186      * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
10187      * @see UserManager#DISALLOW_CREATE_WINDOWS
10188      */
setLockTaskPackages(@onNull ComponentName admin, @NonNull String[] packages)10189     public void setLockTaskPackages(@NonNull ComponentName admin, @NonNull String[] packages)
10190             throws SecurityException {
10191         throwIfParentInstance("setLockTaskPackages");
10192         if (mService != null) {
10193             try {
10194                 mService.setLockTaskPackages(admin, packages);
10195             } catch (RemoteException e) {
10196                 throw e.rethrowFromSystemServer();
10197             }
10198         }
10199     }
10200 
10201     /**
10202      * Returns the list of packages allowed to start the lock task mode.
10203      *
10204      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
10205      * affiliated user or profile, or the profile owner when no device owner is set.
10206      * @see #isAffiliatedUser
10207      * @see #setLockTaskPackages
10208      */
getLockTaskPackages(@onNull ComponentName admin)10209     public @NonNull String[] getLockTaskPackages(@NonNull ComponentName admin) {
10210         throwIfParentInstance("getLockTaskPackages");
10211         if (mService != null) {
10212             try {
10213                 return mService.getLockTaskPackages(admin);
10214             } catch (RemoteException e) {
10215                 throw e.rethrowFromSystemServer();
10216             }
10217         }
10218         return new String[0];
10219     }
10220 
10221     /**
10222      * This function lets the caller know whether the given component is allowed to start the
10223      * lock task mode.
10224      * @param pkg The package to check
10225      */
isLockTaskPermitted(String pkg)10226     public boolean isLockTaskPermitted(String pkg) {
10227         throwIfParentInstance("isLockTaskPermitted");
10228         if (mService != null) {
10229             try {
10230                 return mService.isLockTaskPermitted(pkg);
10231             } catch (RemoteException e) {
10232                 throw e.rethrowFromSystemServer();
10233             }
10234         }
10235         return false;
10236     }
10237 
10238     /**
10239      * Sets which system features are enabled when the device runs in lock task mode. This method
10240      * doesn't affect the features when lock task mode is inactive. Any system features not included
10241      * in {@code flags} are implicitly disabled when calling this method. By default, only
10242      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS} is enabled; all the other features are disabled. To
10243      * disable the global actions dialog, call this method omitting
10244      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}.
10245      *
10246      * <p>This method can only be called by the device owner, a profile owner of an affiliated
10247      * user or profile, or the profile owner when no device owner is set. See
10248      * {@link #isAffiliatedUser}.
10249      * Any features set using this method are cleared if the user becomes unaffiliated.
10250      *
10251      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10252      * @param flags The system features enabled during lock task mode.
10253      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
10254      * affiliated user or profile, or the profile owner when no device owner is set.
10255      * @see #isAffiliatedUser
10256      **/
setLockTaskFeatures(@onNull ComponentName admin, @LockTaskFeature int flags)10257     public void setLockTaskFeatures(@NonNull ComponentName admin, @LockTaskFeature int flags) {
10258         throwIfParentInstance("setLockTaskFeatures");
10259         if (mService != null) {
10260             try {
10261                 mService.setLockTaskFeatures(admin, flags);
10262             } catch (RemoteException e) {
10263                 throw e.rethrowFromSystemServer();
10264             }
10265         }
10266     }
10267 
10268     /**
10269      * Gets which system features are enabled for LockTask mode.
10270      *
10271      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10272      * @return bitfield of flags. See {@link #setLockTaskFeatures(ComponentName, int)} for a list.
10273      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
10274      * affiliated user or profile, or the profile owner when no device owner is set.
10275      * @see #isAffiliatedUser
10276      * @see #setLockTaskFeatures
10277      */
getLockTaskFeatures(@onNull ComponentName admin)10278     public @LockTaskFeature int getLockTaskFeatures(@NonNull ComponentName admin) {
10279         throwIfParentInstance("getLockTaskFeatures");
10280         if (mService != null) {
10281             try {
10282                 return mService.getLockTaskFeatures(admin);
10283             } catch (RemoteException e) {
10284                 throw e.rethrowFromSystemServer();
10285             }
10286         }
10287         return 0;
10288     }
10289 
10290     /**
10291      * Sets whether preferential network service is enabled on the work profile.
10292      * For example, an organization can have a deal/agreement with a carrier that all of
10293      * the work data from its employees’ devices will be sent via a network service dedicated
10294      * for enterprise use.
10295      *
10296      * An example of a supported preferential network service is the Enterprise
10297      * slice on 5G networks.
10298      *
10299      * By default, preferential network service is disabled on the work profile on supported
10300      * carriers and devices. Admins can explicitly enable it with this API.
10301      * On fully-managed devices this method is unsupported because all traffic is considered
10302      * work traffic.
10303      *
10304      * <p>This method can only be called by the profile owner of a managed profile.
10305      * @param enabled whether preferential network service should be enabled.
10306      * @throws SecurityException if the caller is not the profile owner.
10307      **/
setPreferentialNetworkServiceEnabled(boolean enabled)10308     public void setPreferentialNetworkServiceEnabled(boolean enabled) {
10309         throwIfParentInstance("setPreferentialNetworkServiceEnabled");
10310         if (mService == null) {
10311             return;
10312         }
10313 
10314         try {
10315             mService.setPreferentialNetworkServiceEnabled(enabled);
10316         } catch (RemoteException e) {
10317             throw e.rethrowFromSystemServer();
10318         }
10319     }
10320 
10321     /**
10322      * Indicates whether preferential network service is enabled.
10323      *
10324      * <p>This method can be called by the profile owner of a managed profile.
10325      *
10326      * @return whether preferential network service is enabled.
10327      * @throws SecurityException if the caller is not the profile owner.
10328      */
isPreferentialNetworkServiceEnabled()10329     public boolean isPreferentialNetworkServiceEnabled() {
10330         throwIfParentInstance("isPreferentialNetworkServiceEnabled");
10331         if (mService == null) {
10332             return false;
10333         }
10334         try {
10335             return mService.isPreferentialNetworkServiceEnabled(myUserId());
10336         } catch (RemoteException e) {
10337             throw e.rethrowFromSystemServer();
10338         }
10339     }
10340 
10341     /**
10342      * This method is mostly deprecated.
10343      * Most of the settings that still have an effect have dedicated setter methods or user
10344      * restrictions. See individual settings for details.
10345      * <p>
10346      * Called by device owner to update {@link android.provider.Settings.Global} settings.
10347      * Validation that the value of the setting is in the correct form for the setting type should
10348      * be performed by the caller.
10349      * <p>
10350      * The settings that can be updated with this method are:
10351      * <ul>
10352      * <li>{@link android.provider.Settings.Global#ADB_ENABLED} : use
10353      * {@link UserManager#DISALLOW_DEBUGGING_FEATURES} instead to restrict users from enabling
10354      * debugging features and this setting to turn adb on.</li>
10355      * <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
10356      * <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only
10357      * available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
10358      * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
10359      * <li>{@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This
10360      * setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
10361      * </ul>
10362      * <p>
10363      * The following settings used to be supported, but can be controlled in other ways:
10364      * <ul>
10365      * <li>{@link android.provider.Settings.Global#AUTO_TIME} : Use {@link #setAutoTimeEnabled} and
10366      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} instead.</li>
10367      * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE} : Use
10368      * {@link #setAutoTimeZoneEnabled} and {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
10369      * instead.</li>
10370      * <li>{@link android.provider.Settings.Global#DATA_ROAMING} : Use
10371      * {@link UserManager#DISALLOW_DATA_ROAMING} instead.</li>
10372      * </ul>
10373      * <p>
10374      * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
10375      * <ul>
10376      * <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use
10377      * {@link android.bluetooth.BluetoothAdapter#enable()} and
10378      * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
10379      * <li>{@link android.provider.Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
10380      * <li>{@link android.provider.Settings.Global#MODE_RINGER}. Use
10381      * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
10382      * <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li>
10383      * <li>{@link android.provider.Settings.Global#WIFI_ON}. Use
10384      * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
10385      * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}. No longer has effect.</li>
10386      * </ul>
10387      *
10388      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10389      * @param setting The name of the setting to update.
10390      * @param value The value to update the setting to.
10391      * @throws SecurityException if {@code admin} is not a device owner.
10392      */
setGlobalSetting(@onNull ComponentName admin, String setting, String value)10393     public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
10394         throwIfParentInstance("setGlobalSetting");
10395         if (mService != null) {
10396             try {
10397                 mService.setGlobalSetting(admin, setting, value);
10398             } catch (RemoteException e) {
10399                 throw e.rethrowFromSystemServer();
10400             }
10401         }
10402     }
10403 
10404     /** @hide */
10405     @StringDef({
10406             Settings.System.SCREEN_BRIGHTNESS_MODE,
10407             Settings.System.SCREEN_BRIGHTNESS,
10408             Settings.System.SCREEN_BRIGHTNESS_FLOAT,
10409             Settings.System.SCREEN_OFF_TIMEOUT
10410     })
10411     @Retention(RetentionPolicy.SOURCE)
10412     public @interface SystemSettingsWhitelist {}
10413 
10414     /**
10415      * Called by a device or profile owner to update {@link android.provider.Settings.System}
10416      * settings. Validation that the value of the setting is in the correct form for the setting
10417      * type should be performed by the caller.
10418      * <p>
10419      * The settings that can be updated by a device owner or profile owner of secondary user with
10420      * this method are:
10421      * <ul>
10422      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS}</li>
10423      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS_MODE}</li>
10424      * <li>{@link android.provider.Settings.System#SCREEN_OFF_TIMEOUT}</li>
10425      * </ul>
10426      * <p>
10427      *
10428      * @see android.provider.Settings.System#SCREEN_OFF_TIMEOUT
10429      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10430      * @param setting The name of the setting to update.
10431      * @param value The value to update the setting to.
10432      * @throws SecurityException if {@code admin} is not a device or profile owner.
10433      */
setSystemSetting(@onNull ComponentName admin, @NonNull @SystemSettingsWhitelist String setting, String value)10434     public void setSystemSetting(@NonNull ComponentName admin,
10435             @NonNull @SystemSettingsWhitelist String setting, String value) {
10436         throwIfParentInstance("setSystemSetting");
10437         if (mService != null) {
10438             try {
10439                 mService.setSystemSetting(admin, setting, value);
10440             } catch (RemoteException e) {
10441                 throw e.rethrowFromSystemServer();
10442             }
10443         }
10444     }
10445 
10446     /**
10447      * Called by a device owner or a profile owner of an organization-owned managed profile to
10448      * control whether the user can change networks configured by the admin.
10449      * <p>
10450      * WiFi network configuration lockdown is controlled by a global settings
10451      * {@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN} and calling
10452      * this API effectively modifies the global settings. Previously device owners can also
10453      * control this directly via {@link #setGlobalSetting} but they are recommended to switch
10454      * to this API.
10455      *
10456      * @param admin             admin Which {@link DeviceAdminReceiver} this request is associated
10457      *                          with.
10458      * @param lockdown Whether the admin configured networks should be unmodifiable by the
10459      *                          user.
10460      * @throws SecurityException if caller is not a device owner or a profile owner of an
10461      *                           organization-owned managed profile.
10462      */
setConfiguredNetworksLockdownState(@onNull ComponentName admin, boolean lockdown)10463     public void setConfiguredNetworksLockdownState(@NonNull ComponentName admin, boolean lockdown) {
10464         throwIfParentInstance("setConfiguredNetworksLockdownState");
10465         if (mService != null) {
10466             try {
10467                 mService.setConfiguredNetworksLockdownState(admin, lockdown);
10468             } catch (RemoteException e) {
10469                 throw e.rethrowFromSystemServer();
10470             }
10471         }
10472     }
10473 
10474     /**
10475      * Called by a device owner or a profile owner of an organization-owned managed profile to
10476      * determine whether the user is prevented from modifying networks configured by the admin.
10477      *
10478      * @param admin             admin Which {@link DeviceAdminReceiver} this request is associated
10479      *                          with.
10480      * @throws SecurityException if caller is not a device owner or a profile owner of an
10481      *                           organization-owned managed profile.
10482      */
hasLockdownAdminConfiguredNetworks(@onNull ComponentName admin)10483     public boolean hasLockdownAdminConfiguredNetworks(@NonNull ComponentName admin) {
10484         throwIfParentInstance("hasLockdownAdminConfiguredNetworks");
10485         if (mService != null) {
10486             try {
10487                 return mService.hasLockdownAdminConfiguredNetworks(admin);
10488             } catch (RemoteException e) {
10489                 throw e.rethrowFromSystemServer();
10490             }
10491         }
10492         return false;
10493     }
10494 
10495     /**
10496      * Called by a device owner or a profile owner of an organization-owned managed
10497      * profile to set the system wall clock time. This only takes effect if called when
10498      * {@link android.provider.Settings.Global#AUTO_TIME} is 0, otherwise {@code false}
10499      * will be returned.
10500      *
10501      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
10502      * @param millis time in milliseconds since the Epoch
10503      * @return {@code true} if set time succeeded, {@code false} otherwise.
10504      * @throws SecurityException if {@code admin} is not a device owner or a profile owner
10505      * of an organization-owned managed profile.
10506      */
setTime(@onNull ComponentName admin, long millis)10507     public boolean setTime(@NonNull ComponentName admin, long millis) {
10508         throwIfParentInstance("setTime");
10509         if (mService != null) {
10510             try {
10511                 return mService.setTime(admin, millis);
10512             } catch (RemoteException e) {
10513                 throw e.rethrowFromSystemServer();
10514             }
10515         }
10516         return false;
10517     }
10518 
10519     /**
10520      * Called by a device owner or a profile owner of an organization-owned managed
10521      * profile to set the system's persistent default time zone. This only takes
10522      * effect if called when {@link android.provider.Settings.Global#AUTO_TIME_ZONE}
10523      * is 0, otherwise {@code false} will be returned.
10524      *
10525      * @see android.app.AlarmManager#setTimeZone(String)
10526      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
10527      * @param timeZone one of the Olson ids from the list returned by
10528      *     {@link java.util.TimeZone#getAvailableIDs}
10529      * @return {@code true} if set timezone succeeded, {@code false} otherwise.
10530      * @throws SecurityException if {@code admin} is not a device owner or a profile owner
10531      * of an organization-owned managed profile.
10532      */
setTimeZone(@onNull ComponentName admin, String timeZone)10533     public boolean setTimeZone(@NonNull ComponentName admin, String timeZone) {
10534         throwIfParentInstance("setTimeZone");
10535         if (mService != null) {
10536             try {
10537                 return mService.setTimeZone(admin, timeZone);
10538             } catch (RemoteException e) {
10539                 throw e.rethrowFromSystemServer();
10540             }
10541         }
10542         return false;
10543     }
10544 
10545     /**
10546      * Called by device owners to set the user's global location setting.
10547      *
10548      *
10549      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
10550      * @param locationEnabled whether location should be enabled or disabled. <b>Note: </b> on
10551      * {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, calls to
10552      * disable will be ignored.
10553      * @throws SecurityException if {@code admin} is not a device owner.
10554      */
setLocationEnabled(@onNull ComponentName admin, boolean locationEnabled)10555     public void setLocationEnabled(@NonNull ComponentName admin, boolean locationEnabled) {
10556         throwIfParentInstance("setLocationEnabled");
10557         if (mService != null) {
10558             try {
10559                 mService.setLocationEnabled(admin, locationEnabled);
10560             } catch (RemoteException e) {
10561                 throw e.rethrowFromSystemServer();
10562             }
10563         }
10564     }
10565 
10566     /**
10567      * This method is mostly deprecated.
10568      * Most of the settings that still have an effect have dedicated setter methods
10569      * (e.g. {@link #setLocationEnabled}) or user restrictions.
10570      * <p>
10571      *
10572      * Called by profile or device owners to update {@link android.provider.Settings.Secure}
10573      * settings. Validation that the value of the setting is in the correct form for the setting
10574      * type should be performed by the caller.
10575      * <p>
10576      * The settings that can be updated by a profile or device owner with this method are:
10577      * <ul>
10578      * <li>{@link android.provider.Settings.Secure#DEFAULT_INPUT_METHOD}</li>
10579      * <li>{@link android.provider.Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
10580      * </ul>
10581      * <p>
10582      * A device owner can additionally update the following settings:
10583      * <ul>
10584      * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}, but see note below.</li>
10585      * </ul>
10586      *
10587      * <strong>Note: Starting from Android O, apps should no longer call this method with the
10588      * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is
10589      * deprecated. Instead, device owners or profile owners should use the restriction
10590      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}.
10591      * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method
10592      * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS},
10593      * an {@link UnsupportedOperationException} is thrown.
10594      *
10595      * Starting from Android Q, the device and profile owner can also call
10596      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY} to restrict unknown sources for
10597      * all users.
10598      * </strong>
10599      *
10600      * <strong>Note: Starting from Android R, apps should no longer call this method with the
10601      * setting {@link android.provider.Settings.Secure#LOCATION_MODE}, which is deprecated. Instead,
10602      * device owners should call {@link #setLocationEnabled(ComponentName, boolean)}. This will be
10603      * enforced for all apps targeting Android R or above.
10604      * </strong>
10605      *
10606      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10607      * @param setting The name of the setting to update.
10608      * @param value The value to update the setting to.
10609      * @throws SecurityException if {@code admin} is not a device or profile owner.
10610      */
setSecureSetting(@onNull ComponentName admin, String setting, String value)10611     public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
10612         throwIfParentInstance("setSecureSetting");
10613 
10614         if (mService != null) {
10615             try {
10616                 mService.setSecureSetting(admin, setting, value);
10617             } catch (RemoteException e) {
10618                 throw e.rethrowFromSystemServer();
10619             }
10620         }
10621     }
10622 
10623     /**
10624      * Designates a specific service component as the provider for making permission requests of a
10625      * local or remote administrator of the user.
10626      * <p/>
10627      * Only a device owner or profile owner can designate the restrictions provider.
10628      *
10629      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10630      * @param provider The component name of the service that implements
10631      *            {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
10632      *            provider previously assigned.
10633      * @throws SecurityException if {@code admin} is not a device or profile owner.
10634      */
setRestrictionsProvider(@onNull ComponentName admin, @Nullable ComponentName provider)10635     public void setRestrictionsProvider(@NonNull ComponentName admin,
10636             @Nullable ComponentName provider) {
10637         throwIfParentInstance("setRestrictionsProvider");
10638         if (mService != null) {
10639             try {
10640                 mService.setRestrictionsProvider(admin, provider);
10641             } catch (RemoteException re) {
10642                 throw re.rethrowFromSystemServer();
10643             }
10644         }
10645     }
10646 
10647     /**
10648      * Called by profile or device owners to set the global volume mute on or off.
10649      * This has no effect when set on a managed profile.
10650      *
10651      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10652      * @param on {@code true} to mute global volume, {@code false} to turn mute off.
10653      * @throws SecurityException if {@code admin} is not a device or profile owner.
10654      */
setMasterVolumeMuted(@onNull ComponentName admin, boolean on)10655     public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
10656         throwIfParentInstance("setMasterVolumeMuted");
10657         if (mService != null) {
10658             try {
10659                 mService.setMasterVolumeMuted(admin, on);
10660             } catch (RemoteException re) {
10661                 throw re.rethrowFromSystemServer();
10662             }
10663         }
10664     }
10665 
10666     /**
10667      * Called by profile or device owners to check whether the global volume mute is on or off.
10668      *
10669      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10670      * @return {@code true} if global volume is muted, {@code false} if it's not.
10671      * @throws SecurityException if {@code admin} is not a device or profile owner.
10672      */
isMasterVolumeMuted(@onNull ComponentName admin)10673     public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
10674         throwIfParentInstance("isMasterVolumeMuted");
10675         if (mService != null) {
10676             try {
10677                 return mService.isMasterVolumeMuted(admin);
10678             } catch (RemoteException re) {
10679                 throw re.rethrowFromSystemServer();
10680             }
10681         }
10682         return false;
10683     }
10684 
10685     /**
10686      * Change whether a user can uninstall a package. This function can be called by a device owner,
10687      * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via
10688      * {@link #setDelegatedScopes}.
10689      *
10690      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10691      *             {@code null} if the caller is a block uninstall delegate.
10692      * @param packageName package to change.
10693      * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
10694      * @throws SecurityException if {@code admin} is not a device or profile owner.
10695      * @see #setDelegatedScopes
10696      * @see #DELEGATION_BLOCK_UNINSTALL
10697      */
setUninstallBlocked(@ullable ComponentName admin, String packageName, boolean uninstallBlocked)10698     public void setUninstallBlocked(@Nullable ComponentName admin, String packageName,
10699             boolean uninstallBlocked) {
10700         throwIfParentInstance("setUninstallBlocked");
10701         if (mService != null) {
10702             try {
10703                 mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName,
10704                     uninstallBlocked);
10705             } catch (RemoteException re) {
10706                 throw re.rethrowFromSystemServer();
10707             }
10708         }
10709     }
10710 
10711     /**
10712      * Check whether the user has been blocked by device policy from uninstalling a package.
10713      * Requires the caller to be the profile owner if checking a specific admin's policy.
10714      * <p>
10715      * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
10716      * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
10717      * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
10718      * will cause a NullPointerException to be raised.
10719      *
10720      * @param admin The name of the admin component whose blocking policy will be checked, or
10721      *            {@code null} to check whether any admin has blocked the uninstallation.
10722      * @param packageName package to check.
10723      * @return true if uninstallation is blocked.
10724      * @throws SecurityException if {@code admin} is not a device or profile owner.
10725      */
isUninstallBlocked(@ullable ComponentName admin, String packageName)10726     public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
10727         throwIfParentInstance("isUninstallBlocked");
10728         if (mService != null) {
10729             try {
10730                 return mService.isUninstallBlocked(admin, packageName);
10731             } catch (RemoteException re) {
10732                 throw re.rethrowFromSystemServer();
10733             }
10734         }
10735         return false;
10736     }
10737 
10738     /**
10739      * Called by the profile owner of a managed profile to enable widget providers from a given
10740      * package to be available in the parent profile. As a result the user will be able to add
10741      * widgets from the allowlisted package running under the profile to a widget host which runs
10742      * under the parent profile, for example the home screen. Note that a package may have zero or
10743      * more provider components, where each component provides a different widget type.
10744      * <p>
10745      * <strong>Note:</strong> By default no widget provider package is allowlisted.
10746      *
10747      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10748      * @param packageName The package from which widget providers are allowlisted.
10749      * @return Whether the package was added.
10750      * @throws SecurityException if {@code admin} is not a profile owner.
10751      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
10752      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
10753      */
addCrossProfileWidgetProvider(@onNull ComponentName admin, String packageName)10754     public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
10755         throwIfParentInstance("addCrossProfileWidgetProvider");
10756         if (mService != null) {
10757             try {
10758                 return mService.addCrossProfileWidgetProvider(admin, packageName);
10759             } catch (RemoteException re) {
10760                 throw re.rethrowFromSystemServer();
10761             }
10762         }
10763         return false;
10764     }
10765 
10766     /**
10767      * Called by the profile owner of a managed profile to disable widget providers from a given
10768      * package to be available in the parent profile. For this method to take effect the package
10769      * should have been added via
10770      * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
10771      * <p>
10772      * <strong>Note:</strong> By default no widget provider package is allowlisted.
10773      *
10774      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10775      * @param packageName The package from which widget providers are no longer allowlisted.
10776      * @return Whether the package was removed.
10777      * @throws SecurityException if {@code admin} is not a profile owner.
10778      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
10779      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
10780      */
removeCrossProfileWidgetProvider( @onNull ComponentName admin, String packageName)10781     public boolean removeCrossProfileWidgetProvider(
10782             @NonNull ComponentName admin, String packageName) {
10783         throwIfParentInstance("removeCrossProfileWidgetProvider");
10784         if (mService != null) {
10785             try {
10786                 return mService.removeCrossProfileWidgetProvider(admin, packageName);
10787             } catch (RemoteException re) {
10788                 throw re.rethrowFromSystemServer();
10789             }
10790         }
10791         return false;
10792     }
10793 
10794     /**
10795      * Called by the profile owner of a managed profile to query providers from which packages are
10796      * available in the parent profile.
10797      *
10798      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10799      * @return The allowlisted package list.
10800      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
10801      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
10802      * @throws SecurityException if {@code admin} is not a profile owner.
10803      */
getCrossProfileWidgetProviders(@onNull ComponentName admin)10804     public @NonNull List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
10805         throwIfParentInstance("getCrossProfileWidgetProviders");
10806         if (mService != null) {
10807             try {
10808                 List<String> providers = mService.getCrossProfileWidgetProviders(admin);
10809                 if (providers != null) {
10810                     return providers;
10811                 }
10812             } catch (RemoteException re) {
10813                 throw re.rethrowFromSystemServer();
10814             }
10815         }
10816         return Collections.emptyList();
10817     }
10818 
10819     /**
10820      * Called by profile or device owners to set the user's photo.
10821      *
10822      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10823      * @param icon the bitmap to set as the photo.
10824      * @throws SecurityException if {@code admin} is not a device or profile owner.
10825      */
setUserIcon(@onNull ComponentName admin, Bitmap icon)10826     public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
10827         throwIfParentInstance("setUserIcon");
10828         try {
10829             mService.setUserIcon(admin, icon);
10830         } catch (RemoteException re) {
10831             throw re.rethrowFromSystemServer();
10832         }
10833     }
10834 
10835     /**
10836      * Called by device owners or profile owners of an organization-owned managed profile to to set
10837      * a local system update policy. When a new policy is set,
10838      * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
10839      * <p>
10840      * If the supplied system update policy has freeze periods set but the freeze periods do not
10841      * meet 90-day maximum length or 60-day minimum separation requirement set out in
10842      * {@link SystemUpdatePolicy#setFreezePeriods},
10843      * {@link SystemUpdatePolicy.ValidationFailedException} will the thrown. Note that the system
10844      * keeps a record of freeze periods the device experienced previously, and combines them with
10845      * the new freeze periods to be set when checking the maximum freeze length and minimum freeze
10846      * separation constraints. As a result, freeze periods that passed validation during
10847      * {@link SystemUpdatePolicy#setFreezePeriods} might fail the additional checks here due to
10848      * the freeze period history. If this is causing issues during development,
10849      * {@code adb shell dpm clear-freeze-period-record} can be used to clear the record.
10850      *
10851      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
10852      *            components in the device owner package can set system update policies and the most
10853      *            recent policy takes effect.
10854      * @param policy the new policy, or {@code null} to clear the current policy.
10855      * @throws SecurityException if {@code admin} is not a device owner or a profile owner of an
10856      *      organization-owned managed profile.
10857      * @throws IllegalArgumentException if the policy type or maintenance window is not valid.
10858      * @throws SystemUpdatePolicy.ValidationFailedException if the policy's freeze period does not
10859      *             meet the requirement.
10860      * @see SystemUpdatePolicy
10861      * @see SystemUpdatePolicy#setFreezePeriods(List)
10862      */
setSystemUpdatePolicy(@onNull ComponentName admin, SystemUpdatePolicy policy)10863     public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
10864         throwIfParentInstance("setSystemUpdatePolicy");
10865         if (mService != null) {
10866             try {
10867                 mService.setSystemUpdatePolicy(admin, policy);
10868             } catch (RemoteException re) {
10869                 throw re.rethrowFromSystemServer();
10870             }
10871         }
10872     }
10873 
10874     /**
10875      * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
10876      *
10877      * @return The current policy object, or {@code null} if no policy is set.
10878      */
getSystemUpdatePolicy()10879     public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
10880         throwIfParentInstance("getSystemUpdatePolicy");
10881         if (mService != null) {
10882             try {
10883                 return mService.getSystemUpdatePolicy();
10884             } catch (RemoteException re) {
10885                 throw re.rethrowFromSystemServer();
10886             }
10887         }
10888         return null;
10889     }
10890 
10891     /**
10892      * Reset record of previous system update freeze period the device went through.
10893      * @hide
10894      */
10895     @TestApi
10896     @RequiresPermission(android.Manifest.permission.CLEAR_FREEZE_PERIOD)
clearSystemUpdatePolicyFreezePeriodRecord()10897     public void clearSystemUpdatePolicyFreezePeriodRecord() {
10898         throwIfParentInstance("clearSystemUpdatePolicyFreezePeriodRecord");
10899         if (mService == null) {
10900             return;
10901         }
10902         try {
10903             mService.clearSystemUpdatePolicyFreezePeriodRecord();
10904         } catch (RemoteException re) {
10905             throw re.rethrowFromSystemServer();
10906         }
10907     }
10908 
10909     /**
10910      * Called by a device owner or profile owner of secondary users that is affiliated with the
10911      * device to disable the keyguard altogether.
10912      * <p>
10913      * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
10914      * type. However, this call has no effect if a password, pin or pattern is currently set. If a
10915      * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
10916      * disabled.
10917      *
10918      * <p>
10919      * As of {@link android.os.Build.VERSION_CODES#P}, this call also dismisses the
10920      * keyguard if it is currently shown.
10921      *
10922      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10923      * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
10924      * @return {@code false} if attempting to disable the keyguard while a lock password was in
10925      *         place. {@code true} otherwise.
10926      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
10927      * secondary user that is affiliated with the device.
10928      * @see #isAffiliatedUser
10929      * @see #getSecondaryUsers
10930      */
setKeyguardDisabled(@onNull ComponentName admin, boolean disabled)10931     public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
10932         throwIfParentInstance("setKeyguardDisabled");
10933         try {
10934             return mService.setKeyguardDisabled(admin, disabled);
10935         } catch (RemoteException re) {
10936             throw re.rethrowFromSystemServer();
10937         }
10938     }
10939 
10940     /**
10941      * Called by device owner or profile owner of secondary users that is affiliated with the
10942      * device to disable the status bar. Disabling the status bar blocks notifications and quick
10943      * settings.
10944      * <p>
10945      * <strong>Note:</strong> This method has no effect for LockTask mode. The behavior of the
10946      * status bar in LockTask mode can be configured with
10947      * {@link #setLockTaskFeatures(ComponentName, int)}. Calls to this method when the device is in
10948      * LockTask mode will be registered, but will only take effect when the device leaves LockTask
10949      * mode.
10950      *
10951      * <p>This policy does not have any effect while on the lock screen, where the status bar will
10952      * not be disabled. Using LockTask instead of this method is recommended.
10953      *
10954      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10955      * @param disabled {@code true} disables the status bar, {@code false} reenables it.
10956      * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
10957      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
10958      * secondary user that is affiliated with the device.
10959      * @see #isAffiliatedUser
10960      * @see #getSecondaryUsers
10961      */
setStatusBarDisabled(@onNull ComponentName admin, boolean disabled)10962     public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
10963         throwIfParentInstance("setStatusBarDisabled");
10964         try {
10965             return mService.setStatusBarDisabled(admin, disabled);
10966         } catch (RemoteException re) {
10967             throw re.rethrowFromSystemServer();
10968         }
10969     }
10970 
10971     /**
10972      * Called by the system update service to notify device and profile owners of pending system
10973      * updates.
10974      *
10975      * This method should only be used when it is unknown whether the pending system
10976      * update is a security patch. Otherwise, use
10977      * {@link #notifyPendingSystemUpdate(long, boolean)}.
10978      *
10979      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
10980      *         indicating when the current pending update was first available. {@code -1} if no
10981      *         update is available.
10982      * @see #notifyPendingSystemUpdate(long, boolean)
10983      * @hide
10984      */
10985     @SystemApi
10986     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime)10987     public void notifyPendingSystemUpdate(long updateReceivedTime) {
10988         throwIfParentInstance("notifyPendingSystemUpdate");
10989         if (mService != null) {
10990             try {
10991                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime));
10992             } catch (RemoteException re) {
10993                 throw re.rethrowFromSystemServer();
10994             }
10995         }
10996     }
10997 
10998     /**
10999      * Called by the system update service to notify device and profile owners of pending system
11000      * updates.
11001      *
11002      * This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
11003      * when it is known whether the pending system update is a security patch.
11004      *
11005      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
11006      *         indicating when the current pending update was first available. {@code -1} if no
11007      *         update is available.
11008      * @param isSecurityPatch {@code true} if this system update is purely a security patch;
11009      *         {@code false} if not.
11010      * @see #notifyPendingSystemUpdate(long)
11011      * @hide
11012      */
11013     @SystemApi
11014     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch)11015     public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) {
11016         throwIfParentInstance("notifyPendingSystemUpdate");
11017         if (mService != null) {
11018             try {
11019                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime,
11020                         isSecurityPatch));
11021             } catch (RemoteException re) {
11022                 throw re.rethrowFromSystemServer();
11023             }
11024         }
11025     }
11026 
11027     /**
11028      * Called by device or profile owners to get information about a pending system update.
11029      *
11030      * @param admin Which profile or device owner this request is associated with.
11031      * @return Information about a pending system update or {@code null} if no update pending.
11032      * @throws SecurityException if {@code admin} is not a device or profile owner.
11033      * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long)
11034      */
getPendingSystemUpdate(@onNull ComponentName admin)11035     public @Nullable SystemUpdateInfo getPendingSystemUpdate(@NonNull ComponentName admin) {
11036         throwIfParentInstance("getPendingSystemUpdate");
11037         try {
11038             return mService.getPendingSystemUpdate(admin);
11039         } catch (RemoteException re) {
11040             throw re.rethrowFromSystemServer();
11041         }
11042     }
11043 
11044     /**
11045      * Set the default response for future runtime permission requests by applications. This
11046      * function can be called by a device owner, profile owner, or by a delegate given the
11047      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
11048      * The policy can allow for normal operation which prompts the user to grant a permission, or
11049      * can allow automatic granting or denying of runtime permission requests by an application.
11050      * This also applies to new permissions declared by app updates. When a permission is denied or
11051      * granted this way, the effect is equivalent to setting the permission * grant state via
11052      * {@link #setPermissionGrantState}.
11053      * <p/>
11054      * As this policy only acts on runtime permission requests, it only applies to applications
11055      * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
11056      *
11057      * <p>
11058      * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, an auto-grant
11059      * policy will not apply to certain sensors-related permissions on some configurations.
11060      * See {@link #setPermissionGrantState(ComponentName, String, String, int)} for the list of
11061      * permissions affected, and the behavior change for managed profiles and fully-managed
11062      * devices.
11063      *
11064      * @param admin Which profile or device owner this request is associated with.
11065      * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
11066      *            {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
11067      * @throws SecurityException if {@code admin} is not a device or profile owner.
11068      * @see #setPermissionGrantState
11069      * @see #setDelegatedScopes
11070      * @see #DELEGATION_PERMISSION_GRANT
11071      */
setPermissionPolicy(@onNull ComponentName admin, int policy)11072     public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
11073         throwIfParentInstance("setPermissionPolicy");
11074         try {
11075             mService.setPermissionPolicy(admin, mContext.getPackageName(), policy);
11076         } catch (RemoteException re) {
11077             throw re.rethrowFromSystemServer();
11078         }
11079     }
11080 
11081     /**
11082      * Returns the current runtime permission policy set by the device or profile owner. The
11083      * default is {@link #PERMISSION_POLICY_PROMPT}.
11084      *
11085      * @param admin Which profile or device owner this request is associated with.
11086      * @return the current policy for future permission requests.
11087      */
getPermissionPolicy(ComponentName admin)11088     public int getPermissionPolicy(ComponentName admin) {
11089         throwIfParentInstance("getPermissionPolicy");
11090         try {
11091             return mService.getPermissionPolicy(admin);
11092         } catch (RemoteException re) {
11093             throw re.rethrowFromSystemServer();
11094         }
11095     }
11096 
11097     /**
11098      * Sets the grant state of a runtime permission for a specific application. The state can be
11099      * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
11100      * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
11101      * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
11102      * the permission is granted and the user cannot manage it through the UI. This method can only
11103      * be called by a profile owner, device owner, or a delegate given the
11104      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
11105      * <p/>
11106      * Note that user cannot manage other permissions in the affected group through the UI
11107      * either and their granted state will be kept as the current value. Thus, it's recommended that
11108      * you set the grant state of all the permissions in the affected group.
11109      * <p/>
11110      * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
11111      * the permission. It retains the previous grant, if any.
11112      * <p/>
11113      * Device admins with a {@code targetSdkVersion} &lt; {@link android.os.Build.VERSION_CODES#Q}
11114      * cannot grant and revoke permissions for applications built with a {@code targetSdkVersion}
11115      * &lt; {@link android.os.Build.VERSION_CODES#M}.
11116      * <p/>
11117      * Admins with a {@code targetSdkVersion} &ge; {@link android.os.Build.VERSION_CODES#Q} can
11118      * grant and revoke permissions of all apps. Similar to the user revoking a permission from a
11119      * application built with a {@code targetSdkVersion} &lt;
11120      * {@link android.os.Build.VERSION_CODES#M} the app-op matching the permission is set to
11121      * {@link android.app.AppOpsManager#MODE_IGNORED}, but the permission stays granted.
11122      * <p>
11123      * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, control over
11124      * the following, sensors-related, permissions is restricted:
11125      * <ul>
11126      *    <li>Manifest.permission.ACCESS_FINE_LOCATION</li>
11127      *    <li>Manifest.permission.ACCESS_BACKGROUND_LOCATION</li>
11128      *    <li>Manifest.permission.ACCESS_COARSE_LOCATION</li>
11129      *    <li>Manifest.permission.CAMERA</li>
11130      *    <li>Manifest.permission.RECORD_AUDIO</li>
11131      *    <li>Manifest.permission.RECORD_BACKGROUND_AUDIO</li>
11132      *    <li>Manifest.permission.ACTIVITY_RECOGNITION</li>
11133      *    <li>Manifest.permission.BODY_SENSORS</li>
11134      * </ul>
11135      * <p>
11136      * A profile owner may not grant these permissions (i.e. call this method with any of the
11137      * permissions listed above and {@code grantState} of {@code #PERMISSION_GRANT_STATE_GRANTED}),
11138      * but may deny them.
11139      * <p>
11140      * A device owner, by default, may continue granting these permissions. However, for increased
11141      * user control, the admin may opt out of controlling grants for these permissions by including
11142      * {@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT} in the provisioning parameters.
11143      * In that case the device owner's control will be limited do denying these permissions.
11144      * <p>
11145      * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, control over
11146      * the following permissions are restricted for managed profile owners:
11147      * <ul>
11148      *    <li>Manifest.permission.READ_SMS</li>
11149      * </ul>
11150      * <p>
11151      * A managed profile owner may not grant these permissions (i.e. call this method with any of
11152      * the permissions listed above and {@code grantState} of
11153      * {@code #PERMISSION_GRANT_STATE_GRANTED}), but may deny them.
11154      * <p>
11155      * Attempts by the admin to grant these permissions, when the admin is restricted from doing
11156      * so, will be silently ignored (no exception will be thrown).
11157      *
11158      * @param admin Which profile or device owner this request is associated with.
11159      * @param packageName The application to grant or revoke a permission to.
11160      * @param permission The permission to grant or revoke.
11161      * @param grantState The permission grant state which is one of
11162      *            {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
11163      *            {@link #PERMISSION_GRANT_STATE_GRANTED},
11164      * @return whether the permission was successfully granted or revoked.
11165      * @throws SecurityException if {@code admin} is not a device or profile owner.
11166      * @see #PERMISSION_GRANT_STATE_DENIED
11167      * @see #PERMISSION_GRANT_STATE_DEFAULT
11168      * @see #PERMISSION_GRANT_STATE_GRANTED
11169      * @see #setDelegatedScopes
11170      * @see #DELEGATION_PERMISSION_GRANT
11171      */
setPermissionGrantState(@onNull ComponentName admin, @NonNull String packageName, @NonNull String permission, @PermissionGrantState int grantState)11172     public boolean setPermissionGrantState(@NonNull ComponentName admin,
11173             @NonNull String packageName, @NonNull String permission,
11174             @PermissionGrantState int grantState) {
11175         throwIfParentInstance("setPermissionGrantState");
11176         try {
11177             CompletableFuture<Boolean> result = new CompletableFuture<>();
11178 
11179             mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName,
11180                     permission, grantState, new RemoteCallback((b) -> result.complete(b != null)));
11181 
11182             // Timeout
11183             BackgroundThread.getHandler().sendMessageDelayed(
11184                     obtainMessage(CompletableFuture::complete, result, false),
11185                     20_000);
11186 
11187             return result.get();
11188         } catch (RemoteException re) {
11189             throw re.rethrowFromSystemServer();
11190         } catch (InterruptedException | ExecutionException e) {
11191             throw new RuntimeException(e);
11192         }
11193     }
11194 
11195     /**
11196      * Returns the current grant state of a runtime permission for a specific application. This
11197      * function can be called by a device owner, profile owner, or by a delegate given the
11198      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
11199      *
11200      * @param admin Which profile or device owner this request is associated with, or {@code null}
11201      *            if the caller is a permission grant delegate.
11202      * @param packageName The application to check the grant state for.
11203      * @param permission The permission to check for.
11204      * @return the current grant state specified by device policy. If the profile or device owner
11205      *         has not set a grant state, the return value is
11206      *         {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
11207      *         permission is currently granted for the package.
11208      *         <p/>
11209      *         If a grant state was set by the profile or device owner, then the return value will
11210      *         be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
11211      *         {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
11212      *         currently denied or granted.
11213      * @throws SecurityException if {@code admin} is not a device or profile owner.
11214      * @see #setPermissionGrantState(ComponentName, String, String, int)
11215      * @see PackageManager#checkPermission(String, String)
11216      * @see #setDelegatedScopes
11217      * @see #DELEGATION_PERMISSION_GRANT
11218      */
getPermissionGrantState(@ullable ComponentName admin, @NonNull String packageName, @NonNull String permission)11219     public @PermissionGrantState int getPermissionGrantState(@Nullable ComponentName admin,
11220             @NonNull String packageName, @NonNull String permission) {
11221         throwIfParentInstance("getPermissionGrantState");
11222         try {
11223             return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName,
11224                     permission);
11225         } catch (RemoteException re) {
11226             throw re.rethrowFromSystemServer();
11227         }
11228     }
11229 
11230     /**
11231      * Returns whether it is possible for the caller to initiate provisioning of a managed profile
11232      * or device, setting itself as the device or profile owner.
11233      *
11234      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
11235      * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
11236      * @return whether provisioning a managed profile or device is possible.
11237      * @throws IllegalArgumentException if the supplied action is not valid.
11238      */
isProvisioningAllowed(@onNull String action)11239     public boolean isProvisioningAllowed(@NonNull String action) {
11240         throwIfParentInstance("isProvisioningAllowed");
11241         try {
11242             return mService.isProvisioningAllowed(action, mContext.getPackageName());
11243         } catch (RemoteException re) {
11244             throw re.rethrowFromSystemServer();
11245         }
11246     }
11247 
11248     /**
11249      * Checks whether it is possible to initiate provisioning a managed device,
11250      * profile or user, setting the given package as owner.
11251      *
11252      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
11253      *        {@link #ACTION_PROVISION_MANAGED_PROFILE}
11254      * @param packageName The package of the component that would be set as device, user, or profile
11255      *        owner.
11256      * @return A {@link ProvisioningPreCondition} value indicating whether provisioning is allowed.
11257      * @hide
11258      */
11259     @TestApi
checkProvisioningPreCondition( @ullable String action, @NonNull String packageName)11260     public @ProvisioningPreCondition int checkProvisioningPreCondition(
11261             @Nullable String action, @NonNull String packageName) {
11262         try {
11263             return mService.checkProvisioningPreCondition(action, packageName);
11264         } catch (RemoteException re) {
11265             throw re.rethrowFromSystemServer();
11266         }
11267     }
11268 
11269     /**
11270      * Return if this user is a managed profile of another user. An admin can become the profile
11271      * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
11272      * user with {@link #createAndManageUser}
11273      * @param admin Which profile owner this request is associated with.
11274      * @return if this user is a managed profile of another user.
11275      */
isManagedProfile(@onNull ComponentName admin)11276     public boolean isManagedProfile(@NonNull ComponentName admin) {
11277         throwIfParentInstance("isManagedProfile");
11278         try {
11279             return mService.isManagedProfile(admin);
11280         } catch (RemoteException re) {
11281             throw re.rethrowFromSystemServer();
11282         }
11283     }
11284 
11285     /**
11286      * Called by device owner, or profile owner on organization-owned device, to get the MAC
11287      * address of the Wi-Fi device.
11288      *
11289      * NOTE: The MAC address returned here should only be used for inventory management and is
11290      * not likely to be the MAC address used by the device to connect to Wi-Fi networks: MAC
11291      * addresses used for scanning and connecting to Wi-Fi networks are randomized by default.
11292      * To get the randomized MAC address used, call
11293      * {@link android.net.wifi.WifiConfiguration#getRandomizedMacAddress}.
11294      *
11295      * @param admin Which device owner this request is associated with.
11296      * @return the MAC address of the Wi-Fi device, or null when the information is not available.
11297      *         (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
11298      *         <p>
11299      *         The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
11300      * @throws SecurityException if {@code admin} is not a device owner.
11301      */
getWifiMacAddress(@onNull ComponentName admin)11302     public @Nullable String getWifiMacAddress(@NonNull ComponentName admin) {
11303         throwIfParentInstance("getWifiMacAddress");
11304         try {
11305             return mService.getWifiMacAddress(admin);
11306         } catch (RemoteException re) {
11307             throw re.rethrowFromSystemServer();
11308         }
11309     }
11310 
11311     /**
11312      * Called by device owner to reboot the device. If there is an ongoing call on the device,
11313      * throws an {@link IllegalStateException}.
11314      * @param admin Which device owner the request is associated with.
11315      * @throws IllegalStateException if device has an ongoing call.
11316      * @throws SecurityException if {@code admin} is not a device owner.
11317      * @see TelephonyManager#CALL_STATE_IDLE
11318      */
reboot(@onNull ComponentName admin)11319     public void reboot(@NonNull ComponentName admin) {
11320         throwIfParentInstance("reboot");
11321         try {
11322             mService.reboot(admin);
11323         } catch (RemoteException re) {
11324             throw re.rethrowFromSystemServer();
11325         }
11326     }
11327 
11328     /**
11329      * Called by a device admin to set the short support message. This will be displayed to the user
11330      * in settings screens where funtionality has been disabled by the admin. The message should be
11331      * limited to a short statement such as "This setting is disabled by your administrator. Contact
11332      * someone@example.com for support." If the message is longer than 200 characters it may be
11333      * truncated.
11334      * <p>
11335      * If the short support message needs to be localized, it is the responsibility of the
11336      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
11337      * and set a new version of this string accordingly.
11338      *
11339      * @see #setLongSupportMessage
11340      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11341      * @param message Short message to be displayed to the user in settings or null to clear the
11342      *            existing message.
11343      * @throws SecurityException if {@code admin} is not an active administrator.
11344      */
setShortSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)11345     public void setShortSupportMessage(@NonNull ComponentName admin,
11346             @Nullable CharSequence message) {
11347         throwIfParentInstance("setShortSupportMessage");
11348         if (mService != null) {
11349             try {
11350                 mService.setShortSupportMessage(admin, message);
11351             } catch (RemoteException e) {
11352                 throw e.rethrowFromSystemServer();
11353             }
11354         }
11355     }
11356 
11357     /**
11358      * Called by a device admin to get the short support message.
11359      *
11360      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11361      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
11362      *         null if no message has been set.
11363      * @throws SecurityException if {@code admin} is not an active administrator.
11364      */
getShortSupportMessage(@onNull ComponentName admin)11365     public CharSequence getShortSupportMessage(@NonNull ComponentName admin) {
11366         throwIfParentInstance("getShortSupportMessage");
11367         if (mService != null) {
11368             try {
11369                 return mService.getShortSupportMessage(admin);
11370             } catch (RemoteException e) {
11371                 throw e.rethrowFromSystemServer();
11372             }
11373         }
11374         return null;
11375     }
11376 
11377     /**
11378      * Called by a device admin to set the long support message. This will be displayed to the user
11379      * in the device administators settings screen.
11380      * <p>
11381      * If the long support message needs to be localized, it is the responsibility of the
11382      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
11383      * and set a new version of this string accordingly.
11384      *
11385      * @see #setShortSupportMessage
11386      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11387      * @param message Long message to be displayed to the user in settings or null to clear the
11388      *            existing message.
11389      * @throws SecurityException if {@code admin} is not an active administrator.
11390      */
setLongSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)11391     public void setLongSupportMessage(@NonNull ComponentName admin,
11392             @Nullable CharSequence message) {
11393         throwIfParentInstance("setLongSupportMessage");
11394         if (mService != null) {
11395             try {
11396                 mService.setLongSupportMessage(admin, message);
11397             } catch (RemoteException e) {
11398                 throw e.rethrowFromSystemServer();
11399             }
11400         }
11401     }
11402 
11403     /**
11404      * Called by a device admin to get the long support message.
11405      *
11406      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11407      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
11408      *         null if no message has been set.
11409      * @throws SecurityException if {@code admin} is not an active administrator.
11410      */
getLongSupportMessage(@onNull ComponentName admin)11411     public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
11412         throwIfParentInstance("getLongSupportMessage");
11413         if (mService != null) {
11414             try {
11415                 return mService.getLongSupportMessage(admin);
11416             } catch (RemoteException e) {
11417                 throw e.rethrowFromSystemServer();
11418             }
11419         }
11420         return null;
11421     }
11422 
11423     /**
11424      * Called by the system to get the short support message.
11425      *
11426      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11427      * @param userHandle user id the admin is running as.
11428      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
11429      *
11430      * @hide
11431      */
getShortSupportMessageForUser(@onNull ComponentName admin, int userHandle)11432     public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
11433             int userHandle) {
11434         if (mService != null) {
11435             try {
11436                 return mService.getShortSupportMessageForUser(admin, userHandle);
11437             } catch (RemoteException e) {
11438                 throw e.rethrowFromSystemServer();
11439             }
11440         }
11441         return null;
11442     }
11443 
11444 
11445     /**
11446      * Called by the system to get the long support message.
11447      *
11448      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11449      * @param userHandle user id the admin is running as.
11450      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
11451      *
11452      * @hide
11453      */
getLongSupportMessageForUser( @onNull ComponentName admin, int userHandle)11454     public @Nullable CharSequence getLongSupportMessageForUser(
11455             @NonNull ComponentName admin, int userHandle) {
11456         if (mService != null) {
11457             try {
11458                 return mService.getLongSupportMessageForUser(admin, userHandle);
11459             } catch (RemoteException e) {
11460                 throw e.rethrowFromSystemServer();
11461             }
11462         }
11463         return null;
11464     }
11465 
11466     /**
11467      * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
11468      * whose calls act on the parent profile.
11469      *
11470      * <p>The following methods are supported for the parent instance, all other methods will
11471      * throw a SecurityException when called on the parent instance:
11472      * <ul>
11473      * <li>{@link #getPasswordQuality}</li>
11474      * <li>{@link #setPasswordQuality}</li>
11475      * <li>{@link #getPasswordMinimumLength}</li>
11476      * <li>{@link #setPasswordMinimumLength}</li>
11477      * <li>{@link #getPasswordMinimumUpperCase}</li>
11478      * <li>{@link #setPasswordMinimumUpperCase}</li>
11479      * <li>{@link #getPasswordMinimumLowerCase}</li>
11480      * <li>{@link #setPasswordMinimumLowerCase}</li>
11481      * <li>{@link #getPasswordMinimumLetters}</li>
11482      * <li>{@link #setPasswordMinimumLetters}</li>
11483      * <li>{@link #getPasswordMinimumNumeric}</li>
11484      * <li>{@link #setPasswordMinimumNumeric}</li>
11485      * <li>{@link #getPasswordMinimumSymbols}</li>
11486      * <li>{@link #setPasswordMinimumSymbols}</li>
11487      * <li>{@link #getPasswordMinimumNonLetter}</li>
11488      * <li>{@link #setPasswordMinimumNonLetter}</li>
11489      * <li>{@link #getPasswordHistoryLength}</li>
11490      * <li>{@link #setPasswordHistoryLength}</li>
11491      * <li>{@link #getPasswordExpirationTimeout}</li>
11492      * <li>{@link #setPasswordExpirationTimeout}</li>
11493      * <li>{@link #getPasswordExpiration}</li>
11494      * <li>{@link #getPasswordMaximumLength}</li>
11495      * <li>{@link #isActivePasswordSufficient}</li>
11496      * <li>{@link #getCurrentFailedPasswordAttempts}</li>
11497      * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
11498      * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
11499      * <li>{@link #getMaximumTimeToLock}</li>
11500      * <li>{@link #setMaximumTimeToLock}</li>
11501      * <li>{@link #lockNow}</li>
11502      * <li>{@link #getKeyguardDisabledFeatures}</li>
11503      * <li>{@link #setKeyguardDisabledFeatures}</li>
11504      * <li>{@link #getTrustAgentConfiguration}</li>
11505      * <li>{@link #setTrustAgentConfiguration}</li>
11506      * <li>{@link #getRequiredStrongAuthTimeout}</li>
11507      * <li>{@link #setRequiredStrongAuthTimeout}</li>
11508      * <li>{@link #getAccountTypesWithManagementDisabled}</li>
11509      * <li>{@link #setRequiredPasswordComplexity(int)} </li>
11510      * <li>{@link #getRequiredPasswordComplexity()}</li>
11511      * </ul>
11512      * <p>
11513      * The following methods are supported for the parent instance but can only be called by the
11514      * profile owner of a managed profile that was created during the device provisioning flow:
11515      * <ul>
11516      * <li>{@link #getPasswordComplexity}</li>
11517      * <li>{@link #setCameraDisabled}</li>
11518      * <li>{@link #getCameraDisabled}</li>
11519      * <li>{@link #setAccountManagementDisabled(ComponentName, String, boolean)}</li>
11520      * <li>{@link #setPermittedInputMethods}</li>
11521      * <li>{@link #getPermittedInputMethods}</li>
11522      * </ul>
11523      *
11524      * <p>The following methods can be called by the profile owner of a managed profile
11525      * on an organization-owned device:
11526      * <ul>
11527      * <li>{@link #wipeData}</li>
11528      * </ul>
11529      *
11530      * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
11531      * @throws SecurityException if {@code admin} is not a profile owner.
11532      */
getParentProfileInstance(@onNull ComponentName admin)11533     public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
11534         throwIfParentInstance("getParentProfileInstance");
11535         try {
11536             if (!mService.isManagedProfile(admin)) {
11537                 throw new SecurityException("The current user does not have a parent profile.");
11538             }
11539             return new DevicePolicyManager(mContext, mService, true);
11540         } catch (RemoteException e) {
11541             throw e.rethrowFromSystemServer();
11542         }
11543     }
11544 
11545     /**
11546      * Called by device owner or a profile owner of an organization-owned managed profile to
11547      * control the security logging feature.
11548      *
11549      * <p> Security logs contain various information intended for security auditing purposes.
11550      * When security logging is enabled by a profile owner of
11551      * an organization-owned managed profile, certain security logs are not visible (for example
11552      * personal app launch events) or they will be redacted (for example, details of the physical
11553      * volume mount events). Please see {@link SecurityEvent} for details.
11554      *
11555      * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there
11556      * are unaffiliated secondary users or profiles on the device, regardless of whether the
11557      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
11558      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
11559      * new users as soon as possible after provisioning via {@link #setAffiliationIds}. Profile
11560      * owner of organization-owned managed profile is not subject to this restriction since all
11561      * privacy-sensitive events happening outside the managed profile would have been redacted
11562      * already.
11563      *
11564      * @param admin Which device admin this request is associated with.
11565      * @param enabled whether security logging should be enabled or not.
11566      * @throws SecurityException if {@code admin} is not allowed to control security logging.
11567      * @see #setAffiliationIds
11568      * @see #retrieveSecurityLogs
11569      */
setSecurityLoggingEnabled(@onNull ComponentName admin, boolean enabled)11570     public void setSecurityLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
11571         throwIfParentInstance("setSecurityLoggingEnabled");
11572         try {
11573             mService.setSecurityLoggingEnabled(admin, mContext.getPackageName(), enabled);
11574         } catch (RemoteException re) {
11575             throw re.rethrowFromSystemServer();
11576         }
11577     }
11578 
11579     /**
11580      * Return whether security logging is enabled or not by the admin.
11581      *
11582      * <p>Can only be called by the device owner or a profile owner of an organization-owned
11583      * managed profile, otherwise a {@link SecurityException} will be thrown.
11584      *
11585      * @param admin Which device admin this request is associated with.
11586      * @return {@code true} if security logging is enabled by device owner, {@code false} otherwise.
11587      * @throws SecurityException if {@code admin} is not allowed to control security logging.
11588      */
isSecurityLoggingEnabled(@ullable ComponentName admin)11589     public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) {
11590         throwIfParentInstance("isSecurityLoggingEnabled");
11591         try {
11592             return mService.isSecurityLoggingEnabled(admin, mContext.getPackageName());
11593         } catch (RemoteException re) {
11594             throw re.rethrowFromSystemServer();
11595         }
11596     }
11597 
11598     /**
11599      * Called by device owner or profile owner of an organization-owned managed profile to retrieve
11600      * all new security logging entries since the last call to this API after device boots.
11601      *
11602      * <p> Access to the logs is rate limited and it will only return new logs after the device
11603      * owner has been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
11604      *
11605      * <p> When called by a device owner, if there is any other user or profile on the device,
11606      * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown.
11607      * See {@link #isAffiliatedUser}.
11608      *
11609      * @param admin Which device admin this request is associated with.
11610      * @return the new batch of security logs which is a list of {@link SecurityEvent},
11611      * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
11612      * @throws SecurityException if {@code admin} is not allowed to access security logging,
11613      * or there is at least one profile or secondary user that is not affiliated with the device.
11614      * @see #isAffiliatedUser
11615      * @see DeviceAdminReceiver#onSecurityLogsAvailable
11616      */
11617     @SuppressLint("NullableCollection")
retrieveSecurityLogs(@onNull ComponentName admin)11618     public @Nullable List<SecurityEvent> retrieveSecurityLogs(@NonNull ComponentName admin) {
11619         throwIfParentInstance("retrieveSecurityLogs");
11620         try {
11621             ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(
11622                     admin, mContext.getPackageName());
11623             if (list != null) {
11624                 return list.getList();
11625             } else {
11626                 // Rate limit exceeded.
11627                 return null;
11628             }
11629         } catch (RemoteException re) {
11630             throw re.rethrowFromSystemServer();
11631         }
11632     }
11633 
11634     /**
11635      * Makes all accumulated network logs available to DPC in a new batch.
11636      * If throttled, returns time to wait in milliseconds, otherwise 0.
11637      * @hide
11638      */
11639     @TestApi
11640     @RequiresPermission(android.Manifest.permission.FORCE_DEVICE_POLICY_MANAGER_LOGS)
forceNetworkLogs()11641     public long forceNetworkLogs() {
11642         if (mService == null) {
11643             return -1;
11644         }
11645         try {
11646             return mService.forceNetworkLogs();
11647         } catch (RemoteException re) {
11648             throw re.rethrowFromSystemServer();
11649         }
11650     }
11651 
11652     /**
11653      * Forces a batch of security logs to be fetched from logd and makes it available for DPC.
11654      * If throttled, returns time to wait in milliseconds, otherwise 0.
11655      * @hide
11656      */
11657     @TestApi
11658     @RequiresPermission(android.Manifest.permission.FORCE_DEVICE_POLICY_MANAGER_LOGS)
forceSecurityLogs()11659     public long forceSecurityLogs() {
11660         if (mService == null) {
11661             return 0;
11662         }
11663         try {
11664             return mService.forceSecurityLogs();
11665         } catch (RemoteException re) {
11666             throw re.rethrowFromSystemServer();
11667         }
11668     }
11669 
11670     /**
11671      * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
11672      * profile.
11673      *
11674      * @hide
11675      */
getParentProfileInstance(UserInfo uInfo)11676     public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
11677         mContext.checkSelfPermission(
11678                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
11679         if (!uInfo.isManagedProfile()) {
11680             throw new SecurityException("The user " + uInfo.id
11681                     + " does not have a parent profile.");
11682         }
11683         return new DevicePolicyManager(mContext, mService, true);
11684     }
11685 
11686     /**
11687      * Called by a device or profile owner to restrict packages from using metered data.
11688      *
11689      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11690      * @param packageNames the list of package names to be restricted.
11691      * @return a list of package names which could not be restricted.
11692      * @throws SecurityException if {@code admin} is not a device or profile owner.
11693      */
setMeteredDataDisabledPackages(@onNull ComponentName admin, @NonNull List<String> packageNames)11694     public @NonNull List<String> setMeteredDataDisabledPackages(@NonNull ComponentName admin,
11695             @NonNull List<String> packageNames) {
11696         throwIfParentInstance("setMeteredDataDisabled");
11697         if (mService != null) {
11698             try {
11699                 return mService.setMeteredDataDisabledPackages(admin, packageNames);
11700             } catch (RemoteException re) {
11701                 throw re.rethrowFromSystemServer();
11702             }
11703         }
11704         return packageNames;
11705     }
11706 
11707     /**
11708      * Called by a device or profile owner to retrieve the list of packages which are restricted
11709      * by the admin from using metered data.
11710      *
11711      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11712      * @return the list of restricted package names.
11713      * @throws SecurityException if {@code admin} is not a device or profile owner.
11714      */
getMeteredDataDisabledPackages(@onNull ComponentName admin)11715     public @NonNull List<String> getMeteredDataDisabledPackages(@NonNull ComponentName admin) {
11716         throwIfParentInstance("getMeteredDataDisabled");
11717         if (mService != null) {
11718             try {
11719                 return mService.getMeteredDataDisabledPackages(admin);
11720             } catch (RemoteException re) {
11721                 throw re.rethrowFromSystemServer();
11722             }
11723         }
11724         return new ArrayList<>();
11725     }
11726 
11727     /**
11728      * Called by the system to check if a package is restricted from using metered data
11729      * by {@param admin}.
11730      *
11731      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11732      * @param packageName the package whose restricted status is needed.
11733      * @param userId the user to which {@param packageName} belongs.
11734      * @return {@code true} if the package is restricted by admin, otherwise {@code false}
11735      * @throws SecurityException if the caller doesn't run with {@link Process#SYSTEM_UID}
11736      * @hide
11737      */
isMeteredDataDisabledPackageForUser(@onNull ComponentName admin, String packageName, @UserIdInt int userId)11738     public boolean isMeteredDataDisabledPackageForUser(@NonNull ComponentName admin,
11739             String packageName, @UserIdInt int userId) {
11740         throwIfParentInstance("getMeteredDataDisabledForUser");
11741         if (mService != null) {
11742             try {
11743                 return mService.isMeteredDataDisabledPackageForUser(admin, packageName, userId);
11744             } catch (RemoteException re) {
11745                 throw re.rethrowFromSystemServer();
11746             }
11747         }
11748         return false;
11749     }
11750 
11751     /**
11752      * Called by device owner or profile owner of an organization-owned managed profile to retrieve
11753      * device logs from before the device's last reboot.
11754      * <p>
11755      * <strong> This API is not supported on all devices. Calling this API on unsupported devices
11756      * will result in {@code null} being returned. The device logs are retrieved from a RAM region
11757      * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
11758      * about data corruption when parsing. </strong>
11759      *
11760      * <p> When called by a device owner, if there is any other user or profile on the device,
11761      * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown.
11762      * See {@link #isAffiliatedUser}.
11763      *
11764      * @param admin Which device admin this request is associated with.
11765      * @return Device logs from before the latest reboot of the system, or {@code null} if this API
11766      *         is not supported on the device.
11767      * @throws SecurityException if {@code admin} is not allowed to access security logging, or
11768      * there is at least one profile or secondary user that is not affiliated with the device.
11769      * @see #isAffiliatedUser
11770      * @see #retrieveSecurityLogs
11771      */
11772     @SuppressLint("NullableCollection")
retrievePreRebootSecurityLogs( @onNull ComponentName admin)11773     public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
11774             @NonNull ComponentName admin) {
11775         throwIfParentInstance("retrievePreRebootSecurityLogs");
11776         try {
11777             ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(
11778                     admin, mContext.getPackageName());
11779             if (list != null) {
11780                 return list.getList();
11781             } else {
11782                 return null;
11783             }
11784         } catch (RemoteException re) {
11785             throw re.rethrowFromSystemServer();
11786         }
11787     }
11788 
11789     /**
11790      * Called by a profile owner of a managed profile to set the color used for customization. This
11791      * color is used as background color of the confirm credentials screen for that user. The
11792      * default color is teal (#00796B).
11793      * <p>
11794      * The confirm credentials screen can be created using
11795      * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
11796      * <p>
11797      * Starting from Android R, the organization color will no longer be used as the background
11798      * color of the confirm credentials screen.
11799      *
11800      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11801      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
11802      * @throws SecurityException if {@code admin} is not a profile owner.
11803      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
11804      * used as the background color of the confirm credentials screen.
11805      */
11806     @Deprecated
setOrganizationColor(@onNull ComponentName admin, int color)11807     public void setOrganizationColor(@NonNull ComponentName admin, int color) {
11808         throwIfParentInstance("setOrganizationColor");
11809         try {
11810             // always enforce alpha channel to have 100% opacity
11811             color |= 0xFF000000;
11812             mService.setOrganizationColor(admin, color);
11813         } catch (RemoteException re) {
11814             throw re.rethrowFromSystemServer();
11815         }
11816     }
11817 
11818     /**
11819      * @hide
11820      *
11821      * Sets the color used for customization.
11822      *
11823      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
11824      * @param userId which user to set the color to.
11825      * @RequiresPermission(allOf = {
11826      *       Manifest.permission.MANAGE_USERS,
11827      *       Manifest.permission.INTERACT_ACROSS_USERS_FULL})
11828      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
11829      * used as the background color of the confirm credentials screen.
11830      */
11831     @Deprecated
setOrganizationColorForUser(@olorInt int color, @UserIdInt int userId)11832     public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
11833         try {
11834             // always enforce alpha channel to have 100% opacity
11835             color |= 0xFF000000;
11836             mService.setOrganizationColorForUser(color, userId);
11837         } catch (RemoteException re) {
11838             throw re.rethrowFromSystemServer();
11839         }
11840     }
11841 
11842     /**
11843      * Called by a profile owner of a managed profile to retrieve the color used for customization.
11844      * This color is used as background color of the confirm credentials screen for that user.
11845      *
11846      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11847      * @return The 24bit (0xRRGGBB) representation of the color to be used.
11848      * @throws SecurityException if {@code admin} is not a profile owner.
11849      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
11850      * used as the background color of the confirm credentials screen.
11851      */
11852     @Deprecated
getOrganizationColor(@onNull ComponentName admin)11853     public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
11854         throwIfParentInstance("getOrganizationColor");
11855         try {
11856             return mService.getOrganizationColor(admin);
11857         } catch (RemoteException re) {
11858             throw re.rethrowFromSystemServer();
11859         }
11860     }
11861 
11862     /**
11863      * @hide
11864      * Retrieve the customization color for a given user.
11865      *
11866      * @param userHandle The user id of the user we're interested in.
11867      * @return The 24bit (0xRRGGBB) representation of the color to be used.
11868      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
11869      * used as the background color of the confirm credentials screen.
11870      */
11871     @Deprecated
getOrganizationColorForUser(int userHandle)11872     public @ColorInt int getOrganizationColorForUser(int userHandle) {
11873         try {
11874             return mService.getOrganizationColorForUser(userHandle);
11875         } catch (RemoteException re) {
11876             throw re.rethrowFromSystemServer();
11877         }
11878     }
11879 
11880     /**
11881      * Called by the device owner (since API 26) or profile owner (since API 24) to set the name of
11882      * the organization under management.
11883      *
11884      * <p>If the organization name needs to be localized, it is the responsibility of the {@link
11885      * DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast and set
11886      * a new version of this string accordingly.
11887      *
11888      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11889      * @param title The organization name or {@code null} to clear a previously set name.
11890      * @throws SecurityException if {@code admin} is not a device or profile owner.
11891      */
setOrganizationName(@onNull ComponentName admin, @Nullable CharSequence title)11892     public void setOrganizationName(@NonNull ComponentName admin, @Nullable CharSequence title) {
11893         throwIfParentInstance("setOrganizationName");
11894         try {
11895             mService.setOrganizationName(admin, title);
11896         } catch (RemoteException re) {
11897             throw re.rethrowFromSystemServer();
11898         }
11899     }
11900 
11901     /**
11902      * Called by a profile owner of a managed profile to retrieve the name of the organization under
11903      * management.
11904      *
11905      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11906      * @return The organization name or {@code null} if none is set.
11907      * @throws SecurityException if {@code admin} is not a profile owner.
11908      */
getOrganizationName(@onNull ComponentName admin)11909     public @Nullable CharSequence getOrganizationName(@NonNull ComponentName admin) {
11910         throwIfParentInstance("getOrganizationName");
11911         try {
11912             return mService.getOrganizationName(admin);
11913         } catch (RemoteException re) {
11914             throw re.rethrowFromSystemServer();
11915         }
11916     }
11917 
11918     /**
11919      * Called by the system to retrieve the name of the organization managing the device.
11920      *
11921      * @return The organization name or {@code null} if none is set.
11922      * @throws SecurityException if the caller is not the device owner, does not hold the
11923      *         MANAGE_USERS permission and is not the system.
11924      *
11925      * @hide
11926      */
11927     @SystemApi
11928     @SuppressLint("RequiresPermission")
getDeviceOwnerOrganizationName()11929     public @Nullable CharSequence getDeviceOwnerOrganizationName() {
11930         try {
11931             return mService.getDeviceOwnerOrganizationName();
11932         } catch (RemoteException re) {
11933             throw re.rethrowFromSystemServer();
11934         }
11935     }
11936 
11937     /**
11938      * Retrieve the default title message used in the confirm credentials screen for a given user.
11939      *
11940      * @param userHandle The user id of the user we're interested in.
11941      * @return The organization name or {@code null} if none is set.
11942      *
11943      * @hide
11944      */
getOrganizationNameForUser(int userHandle)11945     public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
11946         try {
11947             return mService.getOrganizationNameForUser(userHandle);
11948         } catch (RemoteException re) {
11949             throw re.rethrowFromSystemServer();
11950         }
11951     }
11952 
11953     /**
11954      * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
11955      *         return {@link #STATE_USER_UNMANAGED}
11956      * @hide
11957      */
11958     @SystemApi
11959     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
11960     @UserProvisioningState
getUserProvisioningState()11961     public int getUserProvisioningState() {
11962         throwIfParentInstance("getUserProvisioningState");
11963         if (mService != null) {
11964             try {
11965                 return mService.getUserProvisioningState();
11966             } catch (RemoteException e) {
11967                 throw e.rethrowFromSystemServer();
11968             }
11969         }
11970         return STATE_USER_UNMANAGED;
11971     }
11972 
11973     /**
11974      * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
11975      *
11976      * @param state to store
11977      * @param userHandle for user
11978      * @hide
11979      */
setUserProvisioningState(@serProvisioningState int state, int userHandle)11980     public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
11981         if (mService != null) {
11982             try {
11983                 mService.setUserProvisioningState(state, userHandle);
11984             } catch (RemoteException e) {
11985                 throw e.rethrowFromSystemServer();
11986             }
11987         }
11988     }
11989 
11990     /**
11991      * Indicates the entity that controls the device. Two users are
11992      * affiliated if the set of ids set by the device owner and the admin of the secondary user.
11993      *
11994      * <p>A user that is affiliated with the device owner user is considered to be
11995      * affiliated with the device.
11996      *
11997      * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
11998      * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user
11999      * is created, until it becomes affiliated. Therefore it is recommended that the appropriate
12000      * affiliation ids are set by its owner as soon as possible after the user is
12001      * created.
12002      * <p>
12003      * Note: This method used to be available for affiliating device owner and profile
12004      * owner. However, since Android 11, this combination is not possible. This method is now
12005      * only useful for affiliating the primary user with managed secondary users.
12006      *
12007      * @param admin Which device owner, or owner of secondary user, this request is associated with.
12008      * @param ids A set of opaque non-empty affiliation ids.
12009      *
12010      * @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
12011      * @see #isAffiliatedUser
12012      */
setAffiliationIds(@onNull ComponentName admin, @NonNull Set<String> ids)12013     public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) {
12014         throwIfParentInstance("setAffiliationIds");
12015         if (ids == null) {
12016             throw new IllegalArgumentException("ids must not be null");
12017         }
12018         try {
12019             mService.setAffiliationIds(admin, new ArrayList<>(ids));
12020         } catch (RemoteException e) {
12021             throw e.rethrowFromSystemServer();
12022         }
12023     }
12024 
12025     /**
12026      * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
12027      * empty set if none have been set.
12028      */
getAffiliationIds(@onNull ComponentName admin)12029     public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
12030         throwIfParentInstance("getAffiliationIds");
12031         try {
12032             return new ArraySet<>(mService.getAffiliationIds(admin));
12033         } catch (RemoteException e) {
12034             throw e.rethrowFromSystemServer();
12035         }
12036     }
12037 
12038     /**
12039      * Returns whether this user is affiliated with the device.
12040      * <p>
12041      * By definition, the user that the device owner runs on is always affiliated with the device.
12042      * Any other user is considered affiliated with the device if the set specified by its
12043      * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
12044      * @see #setAffiliationIds
12045      */
isAffiliatedUser()12046     public boolean isAffiliatedUser() {
12047         throwIfParentInstance("isAffiliatedUser");
12048         try {
12049             return mService.isCallingUserAffiliated();
12050         } catch (RemoteException e) {
12051             throw e.rethrowFromSystemServer();
12052         }
12053     }
12054 
12055     /**
12056      * @hide
12057      * Returns whether target user is affiliated with the device.
12058      */
isAffiliatedUser(@serIdInt int userId)12059     public boolean isAffiliatedUser(@UserIdInt int userId) {
12060         try {
12061             return mService.isAffiliatedUser(userId);
12062         } catch (RemoteException e) {
12063             throw e.rethrowFromSystemServer();
12064         }
12065     }
12066 
12067     /**
12068      * @hide
12069      * Returns whether the uninstall for {@code packageName} for the current user is in queue
12070      * to be started
12071      * @param packageName the package to check for
12072      * @return whether the uninstall intent for {@code packageName} is pending
12073      */
isUninstallInQueue(String packageName)12074     public boolean isUninstallInQueue(String packageName) {
12075         try {
12076             return mService.isUninstallInQueue(packageName);
12077         } catch (RemoteException re) {
12078             throw re.rethrowFromSystemServer();
12079         }
12080     }
12081 
12082     /**
12083      * @hide
12084      * @param packageName the package containing active DAs to be uninstalled
12085      */
uninstallPackageWithActiveAdmins(String packageName)12086     public void uninstallPackageWithActiveAdmins(String packageName) {
12087         try {
12088             mService.uninstallPackageWithActiveAdmins(packageName);
12089         } catch (RemoteException re) {
12090             throw re.rethrowFromSystemServer();
12091         }
12092     }
12093 
12094     /**
12095      * @hide
12096      * Remove a test admin synchronously without sending it a broadcast about being removed.
12097      * If the admin is a profile owner or device owner it will still be removed.
12098      *
12099      * @param userHandle user id to remove the admin for.
12100      * @param admin The administration compononent to remove.
12101      * @throws SecurityException if the caller is not shell / root or the admin package
12102      *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
12103      */
12104     @TestApi
12105     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
forceRemoveActiveAdmin( @onNull ComponentName adminReceiver, @UserIdInt int userHandle)12106     public void forceRemoveActiveAdmin(
12107             @NonNull ComponentName adminReceiver, @UserIdInt int userHandle) {
12108         try {
12109             mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
12110         } catch (RemoteException re) {
12111             throw re.rethrowFromSystemServer();
12112         }
12113     }
12114 
12115     /**
12116      * Returns whether the device has been provisioned.
12117      *
12118      * <p>Not for use by third-party applications.
12119      *
12120      * @hide
12121      */
12122     @SystemApi
12123     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioned()12124     public boolean isDeviceProvisioned() {
12125         try {
12126             return mService.isDeviceProvisioned();
12127         } catch (RemoteException re) {
12128             throw re.rethrowFromSystemServer();
12129         }
12130     }
12131 
12132     /**
12133       * Writes that the provisioning configuration has been applied.
12134       *
12135       * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
12136       * permission.
12137       *
12138       * <p>Not for use by third-party applications.
12139       *
12140       * @hide
12141       */
12142     @SystemApi
12143     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
setDeviceProvisioningConfigApplied()12144     public void setDeviceProvisioningConfigApplied() {
12145         try {
12146             mService.setDeviceProvisioningConfigApplied();
12147         } catch (RemoteException re) {
12148             throw re.rethrowFromSystemServer();
12149         }
12150     }
12151 
12152     /**
12153      * Returns whether the provisioning configuration has been applied.
12154      *
12155      * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
12156      *
12157      * <p>Not for use by third-party applications.
12158      *
12159      * @return whether the provisioning configuration has been applied.
12160      *
12161      * @hide
12162      */
12163     @SystemApi
12164     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioningConfigApplied()12165     public boolean isDeviceProvisioningConfigApplied() {
12166         try {
12167             return mService.isDeviceProvisioningConfigApplied();
12168         } catch (RemoteException re) {
12169             throw re.rethrowFromSystemServer();
12170         }
12171     }
12172 
12173     /**
12174      * @hide
12175      * Force update user setup completed status for the given {@code userId}.
12176      * @throws {@link SecurityException} if the caller has no
12177      *         {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS}.
12178      */
12179     @TestApi
forceUpdateUserSetupComplete(@serIdInt int userId)12180     public void forceUpdateUserSetupComplete(@UserIdInt int userId) {
12181         try {
12182             mService.forceUpdateUserSetupComplete(userId);
12183         } catch (RemoteException re) {
12184             throw re.rethrowFromSystemServer();
12185         }
12186     }
12187 
12188     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
throwIfParentInstance(String functionName)12189     private void throwIfParentInstance(String functionName) {
12190         if (mParentInstance) {
12191             throw new SecurityException(functionName + " cannot be called on the parent instance");
12192         }
12193     }
12194 
12195     /**
12196      * Allows the device owner or profile owner to enable or disable the backup service.
12197      *
12198      * <p> Each user has its own backup service which manages the backup and restore mechanisms in
12199      * that user. Disabling the backup service will prevent data from being backed up or restored.
12200      *
12201      * <p> Device owner calls this API to control backup services across all users on the device.
12202      * Profile owner can use this API to enable or disable the profile's backup service. However,
12203      * for a managed profile its backup functionality is only enabled if both the device owner
12204      * and the profile owner have enabled the backup service.
12205      *
12206      * <p> By default, backup service is disabled on a device with device owner, and within a
12207      * managed profile.
12208      *
12209      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12210      * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
12211      * @throws SecurityException if {@code admin} is not a device owner or a profile owner.
12212      */
setBackupServiceEnabled(@onNull ComponentName admin, boolean enabled)12213     public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
12214         throwIfParentInstance("setBackupServiceEnabled");
12215         try {
12216             mService.setBackupServiceEnabled(admin, enabled);
12217         } catch (RemoteException re) {
12218             throw re.rethrowFromSystemServer();
12219         }
12220     }
12221 
12222     /**
12223      * Return whether the backup service is enabled by the device owner or profile owner for the
12224      * current user, as previously set by {@link #setBackupServiceEnabled(ComponentName, boolean)}.
12225      *
12226      * <p> Whether the backup functionality is actually enabled or not depends on settings from both
12227      * the current user and the device owner, please see
12228      * {@link #setBackupServiceEnabled(ComponentName, boolean)} for details.
12229      *
12230      * <p> Backup service manages all backup and restore mechanisms on the device.
12231      *
12232      * @return {@code true} if backup service is enabled, {@code false} otherwise.
12233      * @see #setBackupServiceEnabled
12234      */
isBackupServiceEnabled(@onNull ComponentName admin)12235     public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
12236         throwIfParentInstance("isBackupServiceEnabled");
12237         try {
12238             return mService.isBackupServiceEnabled(admin);
12239         } catch (RemoteException re) {
12240             throw re.rethrowFromSystemServer();
12241         }
12242     }
12243 
12244     /**
12245      * Called by a device owner, profile owner of a managed profile or delegated app with
12246      * {@link #DELEGATION_NETWORK_LOGGING} to control the network logging feature.
12247      *
12248      * <p> When network logging is enabled by a profile owner, the network logs will only include
12249      * work profile network activity, not activity on the personal profile.
12250      *
12251      * <p> Network logs contain DNS lookup and connect() library call events. The following library
12252      *     functions are recorded while network logging is active:
12253      *     <ul>
12254      *       <li>{@code getaddrinfo()}</li>
12255      *       <li>{@code gethostbyname()}</li>
12256      *       <li>{@code connect()}</li>
12257      *     </ul>
12258      *
12259      * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
12260      *     full system call logging; event reporting is enabled by default for all processes but not
12261      *     strongly enforced.
12262      *     Events from applications using alternative implementations of libc, making direct kernel
12263      *     calls, or deliberately obfuscating traffic may not be recorded.
12264      *
12265      * <p> Some common network events may not be reported. For example:
12266      *     <ul>
12267      *       <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
12268      *           an alternative system for name resolution, and so avoid calling
12269      *           {@code getaddrinfo()} or {@code gethostbyname}.</li>
12270      *       <li>Applications may use datagram sockets for performance reasons, for example
12271      *           for a game client. Calling {@code connect()} is unnecessary for this kind of
12272      *           socket, so it will not trigger a network event.</li>
12273      *     </ul>
12274      *
12275      * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
12276      *     always-on VPN service.
12277      *     See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
12278      *     and {@link android.net.VpnService} for details.
12279      *
12280      * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
12281      * are unaffiliated secondary users or profiles on the device, regardless of whether the
12282      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
12283      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
12284      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
12285      *
12286      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
12287      *        {@code null} if called by a delegated app.
12288      * @param enabled whether network logging should be enabled or not.
12289      * @throws SecurityException if {@code admin} is not a device owner or profile owner.
12290      * @see #setAffiliationIds
12291      * @see #retrieveNetworkLogs
12292      */
setNetworkLoggingEnabled(@ullable ComponentName admin, boolean enabled)12293     public void setNetworkLoggingEnabled(@Nullable ComponentName admin, boolean enabled) {
12294         throwIfParentInstance("setNetworkLoggingEnabled");
12295         try {
12296             mService.setNetworkLoggingEnabled(admin, mContext.getPackageName(), enabled);
12297         } catch (RemoteException re) {
12298             throw re.rethrowFromSystemServer();
12299         }
12300     }
12301 
12302     /**
12303      * Return whether network logging is enabled by a device owner or profile owner of
12304      * a managed profile.
12305      *
12306      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
12307      * be {@code null} if the caller is a delegated app with {@link #DELEGATION_NETWORK_LOGGING}
12308      * or has MANAGE_USERS permission.
12309      * @return {@code true} if network logging is enabled by device owner or profile owner,
12310      * {@code false} otherwise.
12311      * @throws SecurityException if {@code admin} is not a device owner or profile owner and
12312      * caller has no MANAGE_USERS permission
12313      */
isNetworkLoggingEnabled(@ullable ComponentName admin)12314     public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
12315         throwIfParentInstance("isNetworkLoggingEnabled");
12316         try {
12317             return mService.isNetworkLoggingEnabled(admin, mContext.getPackageName());
12318         } catch (RemoteException re) {
12319             throw re.rethrowFromSystemServer();
12320         }
12321     }
12322 
12323     /**
12324      * Called by device owner, profile owner of a managed profile or delegated app with
12325      * {@link #DELEGATION_NETWORK_LOGGING} to retrieve the most recent batch of
12326      * network logging events.
12327      *
12328      * <p> When network logging is enabled by a profile owner, the network logs will only include
12329      * work profile network activity, not activity on the personal profile.
12330      *
12331      * A device owner or profile owner has to provide a batchToken provided as part of
12332      * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
12333      * token of the most recent available batch of logs, {@code null} will be returned.
12334      *
12335      * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
12336      *
12337      * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
12338      *
12339      * <p> Access to the logs is rate limited and this method will only return a new batch of logs
12340      * after the device device owner has been notified via
12341      * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
12342      *
12343      * <p>If the caller is not a profile owner and a secondary user or profile is created, calling
12344      * this method will throw a {@link SecurityException} until all users become affiliated again.
12345      * It will also no longer be possible to retrieve the network logs batch with the most recent
12346      * batchToken provided by {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
12347      * See {@link DevicePolicyManager#setAffiliationIds}.
12348      *
12349      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
12350      *        {@code null} if called by a delegated app.
12351      * @param batchToken A token of the batch to retrieve
12352      * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
12353      *        {@code null} if the batch represented by batchToken is no longer available or if
12354      *        logging is disabled.
12355      * @throws SecurityException if {@code admin} is not a device owner, profile owner or if the
12356      * {@code admin} is not a profile owner and there is at least one profile or secondary user
12357      * that is not affiliated with the device.
12358      * @see #setAffiliationIds
12359      * @see DeviceAdminReceiver#onNetworkLogsAvailable
12360      */
retrieveNetworkLogs(@ullable ComponentName admin, long batchToken)12361     public @Nullable List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin,
12362             long batchToken) {
12363         throwIfParentInstance("retrieveNetworkLogs");
12364         try {
12365             return mService.retrieveNetworkLogs(admin, mContext.getPackageName(), batchToken);
12366         } catch (RemoteException re) {
12367             throw re.rethrowFromSystemServer();
12368         }
12369     }
12370 
12371     /**
12372      * Called by a device owner to bind to a service from a secondary managed user or vice versa.
12373      * See {@link #getBindDeviceAdminTargetUsers} for the pre-requirements of a
12374      * device owner to bind to services of another managed user.
12375      * <p>
12376      * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
12377      * Note that the {@link Context} used to obtain this
12378      * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
12379      * to bind to the {@link android.app.Service}.
12380      * <p>
12381      * Note: This method used to be available for communication between device owner and profile
12382      * owner. However, since Android 11, this combination is not possible. This method is now
12383      * only useful for communication between device owner and managed secondary users.
12384      *
12385      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12386      * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
12387      *        explicit component name or a package name to match an
12388      *        {@link IntentFilter} published by a service.
12389      * @param conn Receives information as the service is started and stopped in main thread. This
12390      *        must be a valid {@link ServiceConnection} object; it must not be {@code null}.
12391      * @param flags Operation options for the binding operation. See
12392      *        {@link Context#bindService(Intent, ServiceConnection, int)}.
12393      * @param targetUser Which user to bind to. Must be one of the users returned by
12394      *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
12395      *        be thrown.
12396      * @return If you have successfully bound to the service, {@code true} is returned;
12397      *         {@code false} is returned if the connection is not made and you will not
12398      *         receive the service object.
12399      *
12400      * @see Context#bindService(Intent, ServiceConnection, int)
12401      * @see #getBindDeviceAdminTargetUsers(ComponentName)
12402      */
bindDeviceAdminServiceAsUser( @onNull ComponentName admin, Intent serviceIntent, @NonNull ServiceConnection conn, @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser)12403     public boolean bindDeviceAdminServiceAsUser(
12404             @NonNull ComponentName admin,  Intent serviceIntent, @NonNull ServiceConnection conn,
12405             @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser) {
12406         throwIfParentInstance("bindDeviceAdminServiceAsUser");
12407         // Keep this in sync with ContextImpl.bindServiceCommon.
12408         try {
12409             final IServiceConnection sd = mContext.getServiceDispatcher(
12410                     conn, mContext.getMainThreadHandler(), flags);
12411             serviceIntent.prepareToLeaveProcess(mContext);
12412             return mService.bindDeviceAdminServiceAsUser(admin,
12413                     mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
12414                     sd, flags, targetUser.getIdentifier());
12415         } catch (RemoteException re) {
12416             throw re.rethrowFromSystemServer();
12417         }
12418     }
12419 
12420     /**
12421      * Returns the list of target users that the calling device owner or owner of secondary user
12422      * can use when calling {@link #bindDeviceAdminServiceAsUser}.
12423      * <p>
12424      * A device owner can bind to a service from a secondary managed user and vice versa, provided
12425      * that both users are affiliated. See {@link #setAffiliationIds}.
12426      */
getBindDeviceAdminTargetUsers(@onNull ComponentName admin)12427     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
12428         throwIfParentInstance("getBindDeviceAdminTargetUsers");
12429         try {
12430             return mService.getBindDeviceAdminTargetUsers(admin);
12431         } catch (RemoteException re) {
12432             throw re.rethrowFromSystemServer();
12433         }
12434     }
12435 
12436     /**
12437      * Called by the system to get the time at which the device owner last retrieved security
12438      * logging entries.
12439      *
12440      * @return the time at which the device owner most recently retrieved security logging entries,
12441      *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
12442      * @throws SecurityException if the caller is not the device owner, does not hold the
12443      *         MANAGE_USERS permission and is not the system.
12444      *
12445      * @hide
12446      */
12447     @TestApi
getLastSecurityLogRetrievalTime()12448     public long getLastSecurityLogRetrievalTime() {
12449         try {
12450             return mService.getLastSecurityLogRetrievalTime();
12451         } catch (RemoteException re) {
12452             throw re.rethrowFromSystemServer();
12453         }
12454     }
12455 
12456     /**
12457      * Called by the system to get the time at which the device owner last requested a bug report.
12458      *
12459      * @return the time at which the device owner most recently requested a bug report, in
12460      *         milliseconds since epoch; -1 if a bug report was never requested.
12461      * @throws SecurityException if the caller is not the device owner, does not hold the
12462      *         MANAGE_USERS permission and is not the system.
12463      *
12464      * @hide
12465      */
12466     @TestApi
getLastBugReportRequestTime()12467     public long getLastBugReportRequestTime() {
12468         try {
12469             return mService.getLastBugReportRequestTime();
12470         } catch (RemoteException re) {
12471             throw re.rethrowFromSystemServer();
12472         }
12473     }
12474 
12475     /**
12476      * Called by the system to get the time at which the device owner or profile owner of a
12477      * managed profile last retrieved network logging events.
12478      *
12479      * @return the time at which the device owner or profile owner most recently retrieved network
12480      *         logging events, in milliseconds since epoch; -1 if network logging events were
12481      *         never retrieved.
12482      * @throws SecurityException if the caller is not the device owner, does not hold the
12483      *         MANAGE_USERS permission and is not the system.
12484      *
12485      * @hide
12486      */
12487     @TestApi
getLastNetworkLogRetrievalTime()12488     public long getLastNetworkLogRetrievalTime() {
12489         try {
12490             return mService.getLastNetworkLogRetrievalTime();
12491         } catch (RemoteException re) {
12492             throw re.rethrowFromSystemServer();
12493         }
12494     }
12495 
12496     /**
12497      * Called by the system to find out whether the current user's IME was set by the device/profile
12498      * owner or the user.
12499      *
12500      * @return {@code true} if the user's IME was set by the device or profile owner, {@code false}
12501      *         otherwise.
12502      * @throws SecurityException if the caller is not the device owner/profile owner.
12503      *
12504      * @hide
12505      */
12506     @TestApi
isCurrentInputMethodSetByOwner()12507     public boolean isCurrentInputMethodSetByOwner() {
12508         try {
12509             return mService.isCurrentInputMethodSetByOwner();
12510         } catch (RemoteException re) {
12511             throw re.rethrowFromSystemServer();
12512         }
12513     }
12514 
12515     /**
12516      * Called by the system to get a list of CA certificates that were installed by the device or
12517      * profile owner.
12518      *
12519      * <p> The caller must be the target user's device owner/profile Owner or hold the
12520      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
12521      *
12522      * @param user The user for whom to retrieve information.
12523      * @return list of aliases identifying CA certificates installed by the device or profile owner
12524      * @throws SecurityException if the caller does not have permission to retrieve information
12525      *         about the given user's CA certificates.
12526      *
12527      * @hide
12528      */
12529     @TestApi
getOwnerInstalledCaCerts(@onNull UserHandle user)12530     public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
12531         try {
12532             return mService.getOwnerInstalledCaCerts(user).getList();
12533         } catch (RemoteException re) {
12534             throw re.rethrowFromSystemServer();
12535         }
12536     }
12537 
12538     /**
12539      * Returns whether factory reset protection policy is supported on the device.
12540      *
12541      * @return {@code true} if the device support factory reset protection policy.
12542      *
12543      * @hide
12544      */
12545     @TestApi
isFactoryResetProtectionPolicySupported()12546     public boolean isFactoryResetProtectionPolicySupported() {
12547         try {
12548             return mService.isFactoryResetProtectionPolicySupported();
12549         } catch (RemoteException re) {
12550             throw re.rethrowFromSystemServer();
12551         }
12552     }
12553 
12554     /**
12555      * Called by the device owner or profile owner to clear application user data of a given
12556      * package. The behaviour of this is equivalent to the target application calling
12557      * {@link android.app.ActivityManager#clearApplicationUserData()}.
12558      *
12559      * <p><strong>Note:</strong> an application can store data outside of its application data, e.g.
12560      * external storage or user dictionary. This data will not be wiped by calling this API.
12561      *
12562      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12563      * @param packageName The name of the package which will have its user data wiped.
12564      * @param executor The executor through which the listener should be invoked.
12565      * @param listener A callback object that will inform the caller when the clearing is done.
12566      * @throws SecurityException if the caller is not the device owner/profile owner.
12567      */
clearApplicationUserData(@onNull ComponentName admin, @NonNull String packageName, @NonNull @CallbackExecutor Executor executor, @NonNull OnClearApplicationUserDataListener listener)12568     public void clearApplicationUserData(@NonNull ComponentName admin,
12569             @NonNull String packageName, @NonNull @CallbackExecutor Executor executor,
12570             @NonNull OnClearApplicationUserDataListener listener) {
12571         throwIfParentInstance("clearAppData");
12572         Objects.requireNonNull(executor);
12573         Objects.requireNonNull(listener);
12574         try {
12575             mService.clearApplicationUserData(admin, packageName,
12576                     new IPackageDataObserver.Stub() {
12577                         public void onRemoveCompleted(String pkg, boolean succeeded) {
12578                             executor.execute(() ->
12579                                     listener.onApplicationUserDataCleared(pkg, succeeded));
12580                         }
12581                     });
12582         } catch (RemoteException re) {
12583             throw re.rethrowFromSystemServer();
12584         }
12585     }
12586 
12587     /**
12588      * Called by a device owner to specify whether logout is enabled for all secondary users. The
12589      * system may show a logout button that stops the user and switches back to the primary user.
12590      *
12591      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12592      * @param enabled whether logout should be enabled or not.
12593      * @throws SecurityException if {@code admin} is not a device owner.
12594      */
setLogoutEnabled(@onNull ComponentName admin, boolean enabled)12595     public void setLogoutEnabled(@NonNull ComponentName admin, boolean enabled) {
12596         throwIfParentInstance("setLogoutEnabled");
12597         try {
12598             mService.setLogoutEnabled(admin, enabled);
12599         } catch (RemoteException re) {
12600             throw re.rethrowFromSystemServer();
12601         }
12602     }
12603 
12604     /**
12605      * Returns whether logout is enabled by a device owner.
12606      *
12607      * @return {@code true} if logout is enabled by device owner, {@code false} otherwise.
12608      */
isLogoutEnabled()12609     public boolean isLogoutEnabled() {
12610         throwIfParentInstance("isLogoutEnabled");
12611         try {
12612             return mService.isLogoutEnabled();
12613         } catch (RemoteException re) {
12614             throw re.rethrowFromSystemServer();
12615         }
12616     }
12617 
12618     /**
12619      * Callback used in {@link #clearApplicationUserData}
12620      * to indicate that the clearing of an application's user data is done.
12621      */
12622     public interface OnClearApplicationUserDataListener {
12623         /**
12624          * Method invoked when clearing the application user data has completed.
12625          *
12626          * @param packageName The name of the package which had its user data cleared.
12627          * @param succeeded Whether the clearing succeeded. Clearing fails for device administrator
12628          *                  apps and protected system packages.
12629          */
onApplicationUserDataCleared(String packageName, boolean succeeded)12630         void onApplicationUserDataCleared(String packageName, boolean succeeded);
12631     }
12632 
12633     /**
12634      * Returns set of system apps that should be removed during provisioning.
12635      *
12636      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12637      * @param userId ID of the user to be provisioned.
12638      * @param provisioningAction action indicating type of provisioning, should be one of
12639      * {@link #ACTION_PROVISION_MANAGED_DEVICE}, {@link #ACTION_PROVISION_MANAGED_PROFILE} or
12640      * {@link #ACTION_PROVISION_MANAGED_USER}.
12641      *
12642      * @hide
12643      */
12644     @TestApi
getDisallowedSystemApps(@onNull ComponentName admin, @UserIdInt int userId, @NonNull String provisioningAction)12645     public @NonNull Set<String> getDisallowedSystemApps(@NonNull ComponentName admin,
12646             @UserIdInt int userId, @NonNull String provisioningAction) {
12647         try {
12648             return new ArraySet<>(
12649                     mService.getDisallowedSystemApps(admin, userId, provisioningAction));
12650         } catch (RemoteException re) {
12651             throw re.rethrowFromSystemServer();
12652         }
12653     }
12654 
12655     /**
12656      * Changes the current administrator to another one. All policies from the current
12657      * administrator are migrated to the new administrator. The whole operation is atomic -
12658      * the transfer is either complete or not done at all.
12659      *
12660      * <p>Depending on the current administrator (device owner, profile owner), you have the
12661      * following expected behaviour:
12662      * <ul>
12663      *     <li>A device owner can only be transferred to a new device owner</li>
12664      *     <li>A profile owner can only be transferred to a new profile owner</li>
12665      * </ul>
12666      *
12667      * <p>Use the {@code bundle} parameter to pass data to the new administrator. The data
12668      * will be received in the
12669      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}
12670      * callback of the new administrator.
12671      *
12672      * <p>The transfer has failed if the original administrator is still the corresponding owner
12673      * after calling this method.
12674      *
12675      * <p>The incoming target administrator must have the
12676      * <code>&lt;support-transfer-ownership /&gt;</code> tag inside the
12677      * <code>&lt;device-admin&gt;&lt;/device-admin&gt;</code> tags in the xml file referenced by
12678      * {@link DeviceAdminReceiver#DEVICE_ADMIN_META_DATA}. Otherwise an
12679      * {@link IllegalArgumentException} will be thrown.
12680      *
12681      * @param admin which {@link DeviceAdminReceiver} this request is associated with
12682      * @param target which {@link DeviceAdminReceiver} we want the new administrator to be
12683      * @param bundle data to be sent to the new administrator
12684      * @throws SecurityException if {@code admin} is not a device owner nor a profile owner
12685      * @throws IllegalArgumentException if {@code admin} or {@code target} is {@code null}, they
12686      * are components in the same package or {@code target} is not an active admin
12687      */
transferOwnership(@onNull ComponentName admin, @NonNull ComponentName target, @Nullable PersistableBundle bundle)12688     public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
12689             @Nullable PersistableBundle bundle) {
12690         throwIfParentInstance("transferOwnership");
12691         try {
12692             mService.transferOwnership(admin, target, bundle);
12693         } catch (RemoteException re) {
12694             throw re.rethrowFromSystemServer();
12695         }
12696     }
12697 
12698     /**
12699      * Called by a device owner to specify the user session start message. This may be displayed
12700      * during a user switch.
12701      * <p>
12702      * The message should be limited to a short statement or it may be truncated.
12703      * <p>
12704      * If the message needs to be localized, it is the responsibility of the
12705      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
12706      * and set a new version of this message accordingly.
12707      *
12708      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12709      * @param startUserSessionMessage message for starting user session, or {@code null} to use
12710      * system default message.
12711      * @throws SecurityException if {@code admin} is not a device owner.
12712      */
setStartUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence startUserSessionMessage)12713     public void setStartUserSessionMessage(
12714             @NonNull ComponentName admin, @Nullable CharSequence startUserSessionMessage) {
12715         throwIfParentInstance("setStartUserSessionMessage");
12716         try {
12717             mService.setStartUserSessionMessage(admin, startUserSessionMessage);
12718         } catch (RemoteException re) {
12719             throw re.rethrowFromSystemServer();
12720         }
12721     }
12722 
12723     /**
12724      * Called by a device owner to specify the user session end message. This may be displayed
12725      * during a user switch.
12726      * <p>
12727      * The message should be limited to a short statement or it may be truncated.
12728      * <p>
12729      * If the message needs to be localized, it is the responsibility of the
12730      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
12731      * and set a new version of this message accordingly.
12732      *
12733      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12734      * @param endUserSessionMessage message for ending user session, or {@code null} to use system
12735      * default message.
12736      * @throws SecurityException if {@code admin} is not a device owner.
12737      */
setEndUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence endUserSessionMessage)12738     public void setEndUserSessionMessage(
12739             @NonNull ComponentName admin, @Nullable CharSequence endUserSessionMessage) {
12740         throwIfParentInstance("setEndUserSessionMessage");
12741         try {
12742             mService.setEndUserSessionMessage(admin, endUserSessionMessage);
12743         } catch (RemoteException re) {
12744             throw re.rethrowFromSystemServer();
12745         }
12746     }
12747 
12748     /**
12749      * Returns the user session start message.
12750      *
12751      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12752      * @throws SecurityException if {@code admin} is not a device owner.
12753      */
getStartUserSessionMessage(@onNull ComponentName admin)12754     public CharSequence getStartUserSessionMessage(@NonNull ComponentName admin) {
12755         throwIfParentInstance("getStartUserSessionMessage");
12756         try {
12757             return mService.getStartUserSessionMessage(admin);
12758         } catch (RemoteException re) {
12759             throw re.rethrowFromSystemServer();
12760         }
12761     }
12762 
12763     /**
12764      * Returns the user session end message.
12765      *
12766      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12767      * @throws SecurityException if {@code admin} is not a device owner.
12768      */
getEndUserSessionMessage(@onNull ComponentName admin)12769     public CharSequence getEndUserSessionMessage(@NonNull ComponentName admin) {
12770         throwIfParentInstance("getEndUserSessionMessage");
12771         try {
12772             return mService.getEndUserSessionMessage(admin);
12773         } catch (RemoteException re) {
12774             throw re.rethrowFromSystemServer();
12775         }
12776     }
12777 
12778     /**
12779      * Called by device owner to add an override APN.
12780      *
12781      * <p>This method may returns {@code -1} if {@code apnSetting} conflicts with an existing
12782      * override APN. Update the existing conflicted APN with
12783      * {@link #updateOverrideApn(ComponentName, int, ApnSetting)} instead of adding a new entry.
12784      * <p>Two override APNs are considered to conflict when all the following APIs return
12785      * the same values on both override APNs:
12786      * <ul>
12787      *   <li>{@link ApnSetting#getOperatorNumeric()}</li>
12788      *   <li>{@link ApnSetting#getApnName()}</li>
12789      *   <li>{@link ApnSetting#getProxyAddressAsString()}</li>
12790      *   <li>{@link ApnSetting#getProxyPort()}</li>
12791      *   <li>{@link ApnSetting#getMmsProxyAddressAsString()}</li>
12792      *   <li>{@link ApnSetting#getMmsProxyPort()}</li>
12793      *   <li>{@link ApnSetting#getMmsc()}</li>
12794      *   <li>{@link ApnSetting#isEnabled()}</li>
12795      *   <li>{@link ApnSetting#getMvnoType()}</li>
12796      *   <li>{@link ApnSetting#getProtocol()}</li>
12797      *   <li>{@link ApnSetting#getRoamingProtocol()}</li>
12798      * </ul>
12799      *
12800      * @param admin which {@link DeviceAdminReceiver} this request is associated with
12801      * @param apnSetting the override APN to insert
12802      * @return The {@code id} of inserted override APN. Or {@code -1} when failed to insert into
12803      *         the database.
12804      * @throws SecurityException if {@code admin} is not a device owner.
12805      *
12806      * @see #setOverrideApnsEnabled(ComponentName, boolean)
12807      */
addOverrideApn(@onNull ComponentName admin, @NonNull ApnSetting apnSetting)12808     public int addOverrideApn(@NonNull ComponentName admin, @NonNull ApnSetting apnSetting) {
12809         throwIfParentInstance("addOverrideApn");
12810         if (mService != null) {
12811             try {
12812                 return mService.addOverrideApn(admin, apnSetting);
12813             } catch (RemoteException e) {
12814                 throw e.rethrowFromSystemServer();
12815             }
12816         }
12817         return -1;
12818     }
12819 
12820     /**
12821      * Called by device owner to update an override APN.
12822      *
12823      * <p>This method may returns {@code false} if there is no override APN with the given
12824      * {@code apnId}.
12825      * <p>This method may also returns {@code false} if {@code apnSetting} conflicts with an
12826      * existing override APN. Update the existing conflicted APN instead.
12827      * <p>See {@link #addOverrideApn} for the definition of conflict.
12828      *
12829      * @param admin which {@link DeviceAdminReceiver} this request is associated with
12830      * @param apnId the {@code id} of the override APN to update
12831      * @param apnSetting the override APN to update
12832      * @return {@code true} if the required override APN is successfully updated,
12833      *         {@code false} otherwise.
12834      * @throws SecurityException if {@code admin} is not a device owner.
12835      *
12836      * @see #setOverrideApnsEnabled(ComponentName, boolean)
12837      */
updateOverrideApn(@onNull ComponentName admin, int apnId, @NonNull ApnSetting apnSetting)12838     public boolean updateOverrideApn(@NonNull ComponentName admin, int apnId,
12839             @NonNull ApnSetting apnSetting) {
12840         throwIfParentInstance("updateOverrideApn");
12841         if (mService != null) {
12842             try {
12843                 return mService.updateOverrideApn(admin, apnId, apnSetting);
12844             } catch (RemoteException e) {
12845                 throw e.rethrowFromSystemServer();
12846             }
12847         }
12848         return false;
12849     }
12850 
12851     /**
12852      * Called by device owner to remove an override APN.
12853      *
12854      * <p>This method may returns {@code false} if there is no override APN with the given
12855      * {@code apnId}.
12856      *
12857      * @param admin which {@link DeviceAdminReceiver} this request is associated with
12858      * @param apnId the {@code id} of the override APN to remove
12859      * @return {@code true} if the required override APN is successfully removed, {@code false}
12860      *         otherwise.
12861      * @throws SecurityException if {@code admin} is not a device owner.
12862      *
12863      * @see #setOverrideApnsEnabled(ComponentName, boolean)
12864      */
removeOverrideApn(@onNull ComponentName admin, int apnId)12865     public boolean removeOverrideApn(@NonNull ComponentName admin, int apnId) {
12866         throwIfParentInstance("removeOverrideApn");
12867         if (mService != null) {
12868             try {
12869                 return mService.removeOverrideApn(admin, apnId);
12870             } catch (RemoteException e) {
12871                 throw e.rethrowFromSystemServer();
12872             }
12873         }
12874         return false;
12875     }
12876 
12877     /**
12878      * Called by device owner to get all override APNs inserted by device owner.
12879      *
12880      * @param admin which {@link DeviceAdminReceiver} this request is associated with
12881      * @return A list of override APNs inserted by device owner.
12882      * @throws SecurityException if {@code admin} is not a device owner.
12883      *
12884      * @see #setOverrideApnsEnabled(ComponentName, boolean)
12885      */
getOverrideApns(@onNull ComponentName admin)12886     public List<ApnSetting> getOverrideApns(@NonNull ComponentName admin) {
12887         throwIfParentInstance("getOverrideApns");
12888         if (mService != null) {
12889             try {
12890                 return mService.getOverrideApns(admin);
12891             } catch (RemoteException e) {
12892                 throw e.rethrowFromSystemServer();
12893             }
12894         }
12895         return Collections.emptyList();
12896     }
12897 
12898     /**
12899      * Called by device owner to set if override APNs should be enabled.
12900      * <p> Override APNs are separated from other APNs on the device, and can only be inserted or
12901      * modified by the device owner. When enabled, only override APNs are in use, any other APNs
12902      * are ignored.
12903      *
12904      * @param admin which {@link DeviceAdminReceiver} this request is associated with
12905      * @param enabled {@code true} if override APNs should be enabled, {@code false} otherwise
12906      * @throws SecurityException if {@code admin} is not a device owner.
12907      */
setOverrideApnsEnabled(@onNull ComponentName admin, boolean enabled)12908     public void setOverrideApnsEnabled(@NonNull ComponentName admin, boolean enabled) {
12909         throwIfParentInstance("setOverrideApnEnabled");
12910         if (mService != null) {
12911             try {
12912                 mService.setOverrideApnsEnabled(admin, enabled);
12913             } catch (RemoteException e) {
12914                 throw e.rethrowFromSystemServer();
12915             }
12916         }
12917     }
12918 
12919     /**
12920      * Called by device owner to check if override APNs are currently enabled.
12921      *
12922      * @param admin which {@link DeviceAdminReceiver} this request is associated with
12923      * @return {@code true} if override APNs are currently enabled, {@code false} otherwise.
12924      * @throws SecurityException if {@code admin} is not a device owner.
12925      *
12926      * @see #setOverrideApnsEnabled(ComponentName, boolean)
12927      */
isOverrideApnEnabled(@onNull ComponentName admin)12928     public boolean isOverrideApnEnabled(@NonNull ComponentName admin) {
12929         throwIfParentInstance("isOverrideApnEnabled");
12930         if (mService != null) {
12931             try {
12932                 return mService.isOverrideApnEnabled(admin);
12933             } catch (RemoteException e) {
12934                 throw e.rethrowFromSystemServer();
12935             }
12936         }
12937         return false;
12938     }
12939 
12940     /**
12941      * Returns the data passed from the current administrator to the new administrator during an
12942      * ownership transfer. This is the same {@code bundle} passed in
12943      * {@link #transferOwnership(ComponentName, ComponentName, PersistableBundle)}. The bundle is
12944      * persisted until the profile owner or device owner is removed.
12945      *
12946      * <p>This is the same <code>bundle</code> received in the
12947      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}.
12948      * Use this method to retrieve it after the transfer as long as the new administrator is the
12949      * active device or profile owner.
12950      *
12951      * <p>Returns <code>null</code> if no ownership transfer was started for the calling user.
12952      *
12953      * @see #transferOwnership
12954      * @see DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)
12955      * @throws SecurityException if the caller is not a device or profile owner.
12956      */
12957     @Nullable
getTransferOwnershipBundle()12958     public PersistableBundle getTransferOwnershipBundle() {
12959         throwIfParentInstance("getTransferOwnershipBundle");
12960         try {
12961             return mService.getTransferOwnershipBundle();
12962         } catch (RemoteException re) {
12963             throw re.rethrowFromSystemServer();
12964         }
12965     }
12966 
12967     /**
12968      * Sets the global Private DNS mode to opportunistic.
12969      * May only be called by the device owner.
12970      *
12971      * <p>In this mode, the DNS subsystem will attempt a TLS handshake to the network-supplied
12972      * resolver prior to attempting name resolution in cleartext.
12973      *
12974      * <p>Note: The device owner won't be able to set the global private DNS mode if there are
12975      * unaffiliated secondary users or profiles on the device. It's recommended that affiliation
12976      * ids are set for new users as soon as possible after provisioning via
12977      * {@link #setAffiliationIds}.
12978      *
12979      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12980      *
12981      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully, or
12982      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set.
12983      *
12984      * @throws SecurityException if the caller is not the device owner.
12985      */
setGlobalPrivateDnsModeOpportunistic( @onNull ComponentName admin)12986     public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeOpportunistic(
12987             @NonNull ComponentName admin) {
12988         throwIfParentInstance("setGlobalPrivateDnsModeOpportunistic");
12989 
12990         if (mService == null) {
12991             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
12992         }
12993 
12994         try {
12995             return mService.setGlobalPrivateDns(admin, PRIVATE_DNS_MODE_OPPORTUNISTIC, null);
12996         } catch (RemoteException re) {
12997             throw re.rethrowFromSystemServer();
12998         }
12999     }
13000 
13001     /**
13002      * Sets the global Private DNS host to be used.
13003      * May only be called by the device owner.
13004      *
13005      * <p>Note that the method is blocking as it will perform a connectivity check to the resolver,
13006      * to ensure it is valid. Because of that, the method should not be called on any thread that
13007      * relates to user interaction, such as the UI thread.
13008      *
13009      * <p>In case a VPN is used in conjunction with Private DNS resolver, the Private DNS resolver
13010      * must be reachable both from within and outside the VPN. Otherwise, the device may lose
13011      * the ability to resolve hostnames as system traffic to the resolver may not go through the
13012      * VPN.
13013      *
13014      * <p>Note: The device owner won't be able to set the global private DNS mode if there are
13015      * unaffiliated secondary users or profiles on the device. It's recommended that affiliation
13016      * ids are set for new users as soon as possible after provisioning via
13017      * {@link #setAffiliationIds}.
13018      *
13019      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
13020      * @param privateDnsHost The hostname of a server that implements DNS over TLS (RFC7858).
13021      *
13022      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully,
13023      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set or
13024      *         {@code PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING} if the specified host does not
13025      *         implement RFC7858.
13026      *
13027      * @throws IllegalArgumentException if the {@code privateDnsHost} is not a valid hostname.
13028      *
13029      * @throws SecurityException if the caller is not the device owner.
13030      */
setGlobalPrivateDnsModeSpecifiedHost( @onNull ComponentName admin, @NonNull String privateDnsHost)13031     @WorkerThread public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeSpecifiedHost(
13032             @NonNull ComponentName admin, @NonNull String privateDnsHost) {
13033         throwIfParentInstance("setGlobalPrivateDnsModeSpecifiedHost");
13034         Objects.requireNonNull(privateDnsHost, "dns resolver is null");
13035 
13036         if (mService == null) {
13037             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
13038         }
13039 
13040         if (NetworkUtilsInternal.isWeaklyValidatedHostname(privateDnsHost)) {
13041             if (!PrivateDnsConnectivityChecker.canConnectToPrivateDnsServer(privateDnsHost)) {
13042                 return PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING;
13043             }
13044         }
13045 
13046         try {
13047             return mService.setGlobalPrivateDns(
13048                     admin, PRIVATE_DNS_MODE_PROVIDER_HOSTNAME, privateDnsHost);
13049         } catch (RemoteException re) {
13050             throw re.rethrowFromSystemServer();
13051         }
13052     }
13053 
13054     /**
13055      * Called by device owner or profile owner of an organization-owned managed profile to install
13056      * a system update from the given file. The device will be
13057      * rebooted in order to finish installing the update. Note that if the device is rebooted, this
13058      * doesn't necessarily mean that the update has been applied successfully. The caller should
13059      * additionally check the system version with {@link android.os.Build#FINGERPRINT} or {@link
13060      * android.os.Build.VERSION}. If an error occurs during processing the OTA before the reboot,
13061      * the caller will be notified by {@link InstallSystemUpdateCallback}. If device does not have
13062      * sufficient battery level, the installation will fail with error {@link
13063      * InstallSystemUpdateCallback#UPDATE_ERROR_BATTERY_LOW}.
13064      *
13065      * @param admin The {@link DeviceAdminReceiver} that this request is associated with.
13066      * @param updateFilePath An Uri of the file that contains the update. The file should be
13067      * readable by the calling app.
13068      * @param executor The executor through which the callback should be invoked.
13069      * @param callback A callback object that will inform the caller when installing an update
13070      * fails.
13071      */
installSystemUpdate( @onNull ComponentName admin, @NonNull Uri updateFilePath, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)13072     public void installSystemUpdate(
13073             @NonNull ComponentName admin, @NonNull Uri updateFilePath,
13074             @NonNull @CallbackExecutor Executor executor,
13075             @NonNull InstallSystemUpdateCallback callback) {
13076         throwIfParentInstance("installUpdate");
13077         if (mService == null) {
13078             return;
13079         }
13080         try (ParcelFileDescriptor fileDescriptor = mContext.getContentResolver()
13081                     .openFileDescriptor(updateFilePath, "r")) {
13082             mService.installUpdateFromFile(
13083                     admin, fileDescriptor, new StartInstallingUpdateCallback.Stub() {
13084                         @Override
13085                         public void onStartInstallingUpdateError(
13086                                 int errorCode, String errorMessage) {
13087                             executeCallback(errorCode, errorMessage, executor, callback);
13088                         }
13089                     });
13090         } catch (RemoteException e) {
13091             throw e.rethrowFromSystemServer();
13092         } catch (FileNotFoundException e) {
13093             Log.w(TAG, e);
13094             executeCallback(
13095                     InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
13096                     Log.getStackTraceString(e),
13097                     executor, callback);
13098         } catch (IOException e) {
13099             Log.w(TAG, e);
13100             executeCallback(
13101                     InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN, Log.getStackTraceString(e),
13102                     executor, callback);
13103         }
13104     }
13105 
executeCallback(int errorCode, String errorMessage, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)13106     private void executeCallback(int errorCode, String errorMessage,
13107             @NonNull @CallbackExecutor Executor executor,
13108             @NonNull InstallSystemUpdateCallback callback) {
13109         executor.execute(() -> callback.onInstallUpdateError(errorCode, errorMessage));
13110     }
13111 
13112     /**
13113      * Returns the system-wide Private DNS mode.
13114      *
13115      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
13116      * @return one of {@code PRIVATE_DNS_MODE_OFF}, {@code PRIVATE_DNS_MODE_OPPORTUNISTIC},
13117      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} or {@code PRIVATE_DNS_MODE_UNKNOWN}.
13118      * @throws SecurityException if the caller is not the device owner.
13119      */
getGlobalPrivateDnsMode(@onNull ComponentName admin)13120     public int getGlobalPrivateDnsMode(@NonNull ComponentName admin) {
13121         throwIfParentInstance("setGlobalPrivateDns");
13122         if (mService == null) {
13123             return PRIVATE_DNS_MODE_UNKNOWN;
13124         }
13125 
13126         try {
13127             return mService.getGlobalPrivateDnsMode(admin);
13128         } catch (RemoteException re) {
13129             throw re.rethrowFromSystemServer();
13130         }
13131     }
13132 
13133     /**
13134      * Returns the system-wide Private DNS host.
13135      *
13136      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
13137      * @return The hostname used for Private DNS queries, null if none is set.
13138      * @throws SecurityException if the caller is not the device owner.
13139      */
getGlobalPrivateDnsHost(@onNull ComponentName admin)13140     public @Nullable String getGlobalPrivateDnsHost(@NonNull ComponentName admin) {
13141         throwIfParentInstance("setGlobalPrivateDns");
13142         if (mService == null) {
13143             return null;
13144         }
13145 
13146         try {
13147             return mService.getGlobalPrivateDnsHost(admin);
13148         } catch (RemoteException re) {
13149             throw re.rethrowFromSystemServer();
13150         }
13151     }
13152 
13153     /**
13154      * Deprecated. Use {@code markProfileOwnerOnOrganizationOwnedDevice} instead.
13155      * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#Q} or
13156      * below, will behave the same as {@link #markProfileOwnerOnOrganizationOwnedDevice}.
13157      *
13158      * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#R}
13159      * or above, will throw an UnsupportedOperationException when called.
13160      *
13161      * @deprecated Use {@link #markProfileOwnerOnOrganizationOwnedDevice} instead.
13162      *
13163      * @hide
13164      */
13165     @Deprecated
13166     @SystemApi
13167     @RequiresPermission(value = android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS,
13168             conditional = true)
setProfileOwnerCanAccessDeviceIds(@onNull ComponentName who)13169     public void setProfileOwnerCanAccessDeviceIds(@NonNull ComponentName who) {
13170         ApplicationInfo ai = mContext.getApplicationInfo();
13171         if (ai.targetSdkVersion > Build.VERSION_CODES.Q) {
13172             throw new UnsupportedOperationException(
13173                     "This method is deprecated. use markProfileOwnerOnOrganizationOwnedDevice"
13174                     + " instead.");
13175         } else {
13176             markProfileOwnerOnOrganizationOwnedDevice(who);
13177         }
13178     }
13179 
13180     /**
13181      * Marks the profile owner of the given user as managing an organization-owned device.
13182      * That will give it access to device identifiers (such as serial number, IMEI and MEID)
13183      * as well as other privileges.
13184      *
13185      * @hide
13186      */
13187     @TestApi
13188     @RequiresPermission(anyOf = {
13189             android.Manifest.permission.MARK_DEVICE_ORGANIZATION_OWNED,
13190             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
13191     }, conditional = true)
markProfileOwnerOnOrganizationOwnedDevice(@onNull ComponentName who)13192     public void markProfileOwnerOnOrganizationOwnedDevice(@NonNull ComponentName who) {
13193         if (mService == null) {
13194             return;
13195         }
13196         try {
13197             mService.markProfileOwnerOnOrganizationOwnedDevice(who, myUserId());
13198         } catch (RemoteException re) {
13199             throw re.rethrowFromSystemServer();
13200         }
13201     }
13202 
13203     /**
13204      * Allows a set of packages to access cross-profile calendar APIs.
13205      *
13206      * <p>Called by a profile owner of a managed profile.
13207      *
13208      * <p>Calling with a {@code null} value for the set disables the restriction so that all
13209      * packages are allowed to access cross-profile calendar APIs. Calling with an empty set
13210      * disallows all packages from accessing cross-profile calendar APIs. If this method isn't
13211      * called, no package is allowed to access cross-profile calendar APIs by default.
13212      *
13213      * @param admin which {@link DeviceAdminReceiver} this request is associated with
13214      * @param packageNames set of packages to be allowlisted
13215      * @throws SecurityException if {@code admin} is not a profile owner
13216      *
13217      * @see #getCrossProfileCalendarPackages(ComponentName)
13218      */
setCrossProfileCalendarPackages(@onNull ComponentName admin, @Nullable Set<String> packageNames)13219     public void setCrossProfileCalendarPackages(@NonNull ComponentName admin,
13220             @Nullable Set<String> packageNames) {
13221         throwIfParentInstance("setCrossProfileCalendarPackages");
13222         if (mService != null) {
13223             try {
13224                 mService.setCrossProfileCalendarPackages(admin, packageNames == null ? null
13225                         : new ArrayList<>(packageNames));
13226             } catch (RemoteException e) {
13227                 throw e.rethrowFromSystemServer();
13228             }
13229         }
13230     }
13231 
13232     /**
13233      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
13234      *
13235      * <p>Called by a profile owner of a managed profile.
13236      *
13237      * @param admin which {@link DeviceAdminReceiver} this request is associated with
13238      * @return the set of names of packages that were previously allowed via
13239      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
13240      * empty set if none have been allowed
13241      * @throws SecurityException if {@code admin} is not a profile owner
13242      *
13243      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
13244      */
getCrossProfileCalendarPackages(@onNull ComponentName admin)13245     public @Nullable Set<String> getCrossProfileCalendarPackages(@NonNull ComponentName admin) {
13246         throwIfParentInstance("getCrossProfileCalendarPackages");
13247         if (mService != null) {
13248             try {
13249                 final List<String> packageNames = mService.getCrossProfileCalendarPackages(admin);
13250                 return packageNames == null ? null : new ArraySet<>(packageNames);
13251             } catch (RemoteException e) {
13252                 throw e.rethrowFromSystemServer();
13253             }
13254         }
13255         return Collections.emptySet();
13256     }
13257 
13258     /**
13259      * Returns if a package is allowed to access cross-profile calendar APIs.
13260      *
13261      * <p>A package is allowed to access cross-profile calendar APIs if it's allowed by
13262      * admins via {@link #setCrossProfileCalendarPackages(ComponentName, Set)} and
13263      * {@link android.provider.Settings.Secure#CROSS_PROFILE_CALENDAR_ENABLED}
13264      * is turned on in the managed profile.
13265      *
13266      * <p>To query for a specific user, use
13267      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
13268      * that user, and get a {@link DevicePolicyManager} from this context.
13269      *
13270      * @param packageName the name of the package
13271      * @return {@code true} if the package is allowed to access cross-profile calendar APIs,
13272      * {@code false} otherwise
13273      *
13274      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
13275      * @see #getCrossProfileCalendarPackages(ComponentName)
13276      * @hide
13277      */
13278     @RequiresPermission(anyOf = {
13279             permission.INTERACT_ACROSS_USERS_FULL,
13280             permission.INTERACT_ACROSS_USERS
13281     }, conditional = true)
isPackageAllowedToAccessCalendar(@onNull String packageName)13282     public boolean isPackageAllowedToAccessCalendar(@NonNull  String packageName) {
13283         throwIfParentInstance("isPackageAllowedToAccessCalendar");
13284         if (mService != null) {
13285             try {
13286                 return mService.isPackageAllowedToAccessCalendarForUser(packageName,
13287                         myUserId());
13288             } catch (RemoteException e) {
13289                 throw e.rethrowFromSystemServer();
13290             }
13291         }
13292         return false;
13293     }
13294 
13295     /**
13296      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
13297      *
13298      * <p>To query for a specific user, use
13299      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
13300      * that user, and get a {@link DevicePolicyManager} from this context.
13301      *
13302      * @return the set of names of packages that were previously allowed via
13303      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
13304      * empty set if none have been allowed
13305      *
13306      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
13307      * @see #getCrossProfileCalendarPackages(ComponentName)
13308      * @hide
13309      */
13310     @RequiresPermission(anyOf = {
13311             permission.INTERACT_ACROSS_USERS_FULL,
13312             permission.INTERACT_ACROSS_USERS
13313     })
getCrossProfileCalendarPackages()13314     public @Nullable Set<String> getCrossProfileCalendarPackages() {
13315         throwIfParentInstance("getCrossProfileCalendarPackages");
13316         if (mService != null) {
13317             try {
13318                 final List<String> packageNames = mService.getCrossProfileCalendarPackagesForUser(
13319                         myUserId());
13320                 return packageNames == null ? null : new ArraySet<>(packageNames);
13321             } catch (RemoteException e) {
13322                 throw e.rethrowFromSystemServer();
13323             }
13324         }
13325         return Collections.emptySet();
13326     }
13327 
13328     /**
13329      * Sets the set of admin-allowlisted package names that are allowed to request user consent for
13330      * cross-profile communication.
13331      *
13332      * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
13333      *
13334      * <p>Previous calls are overridden by each subsequent call to this method.
13335      *
13336      * <p>Note that other apps may be able to request user consent for cross-profile communication
13337      * if they have been explicitly allowlisted by the OEM.
13338      *
13339      * <p>When previously-set cross-profile packages are missing from {@code packageNames}, the
13340      * app-op for {@code INTERACT_ACROSS_PROFILES} will be reset for those packages. This will not
13341      * occur for packages that are allowlisted by the OEM.
13342      *
13343      * @param admin the {@link DeviceAdminReceiver} this request is associated with
13344      * @param packageNames the new cross-profile package names
13345      */
setCrossProfilePackages( @onNull ComponentName admin, @NonNull Set<String> packageNames)13346     public void setCrossProfilePackages(
13347             @NonNull ComponentName admin, @NonNull Set<String> packageNames) {
13348         throwIfParentInstance("setCrossProfilePackages");
13349         if (mService != null) {
13350             try {
13351                 mService.setCrossProfilePackages(admin, new ArrayList<>(packageNames));
13352             } catch (RemoteException e) {
13353                 throw e.rethrowFromSystemServer();
13354             }
13355         }
13356     }
13357 
13358     /**
13359      * Returns the set of package names that the admin has previously set as allowed to request user
13360      * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
13361      * Set)}.
13362      *
13363      * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
13364      *
13365      * <p>Note that other apps not included in the returned set may be able to request user consent
13366      * for cross-profile communication if they have been explicitly allowlisted by the OEM.
13367      *
13368      * @param admin the {@link DeviceAdminReceiver} this request is associated with
13369      * @return the set of package names the admin has previously set as allowed to request user
13370      * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
13371      * Set)}
13372      */
getCrossProfilePackages(@onNull ComponentName admin)13373     public @NonNull Set<String> getCrossProfilePackages(@NonNull ComponentName admin) {
13374         throwIfParentInstance("getCrossProfilePackages");
13375         if (mService != null) {
13376             try {
13377                 return new ArraySet<>(mService.getCrossProfilePackages(admin));
13378             } catch (RemoteException e) {
13379                 throw e.rethrowFromSystemServer();
13380             }
13381         }
13382         return Collections.emptySet();
13383     }
13384 
13385     /**
13386      * Returns the combined set of the following:
13387      * <ul>
13388      * <li>The package names that the admin has previously set as allowed to request user consent
13389      * for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
13390      * Set)}.</li>
13391      * <li>The default package names set by the OEM that are allowed to request user consent for
13392      * cross-profile communication without being explicitly enabled by the admin, via {@link
13393      * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array
13394      * #vendor_cross_profile_apps}.</li>
13395      * </ul>
13396      *
13397      * @return the combined set of allowlisted package names set via
13398      * {@link #setCrossProfilePackages(ComponentName, Set)}, {@link com.android.internal.R.array
13399      * #cross_profile_apps}, and {@link com.android.internal.R.array#vendor_cross_profile_apps}.
13400      *
13401      * @hide
13402      */
13403     @RequiresPermission(anyOf = {
13404             permission.INTERACT_ACROSS_USERS_FULL,
13405             permission.INTERACT_ACROSS_USERS,
13406             permission.INTERACT_ACROSS_PROFILES
13407     })
getAllCrossProfilePackages()13408     public @NonNull Set<String> getAllCrossProfilePackages() {
13409         throwIfParentInstance("getAllCrossProfilePackages");
13410         if (mService != null) {
13411             try {
13412                 return new ArraySet<>(mService.getAllCrossProfilePackages());
13413             } catch (RemoteException e) {
13414                 throw e.rethrowFromSystemServer();
13415             }
13416         }
13417         return Collections.emptySet();
13418     }
13419 
13420     /**
13421      * Returns the default package names set by the OEM that are allowed to request user consent for
13422      * cross-profile communication without being explicitly enabled by the admin, via {@link
13423      * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array
13424      * #vendor_cross_profile_apps}.
13425      *
13426      * @hide
13427      */
13428     @TestApi
getDefaultCrossProfilePackages()13429     public @NonNull Set<String> getDefaultCrossProfilePackages() {
13430         throwIfParentInstance("getDefaultCrossProfilePackages");
13431         if (mService != null) {
13432             try {
13433                 return new ArraySet<>(mService.getDefaultCrossProfilePackages());
13434             } catch (RemoteException e) {
13435                 throw e.rethrowFromSystemServer();
13436             }
13437         }
13438         return Collections.emptySet();
13439     }
13440 
13441     /**
13442      * Returns whether the device is being used as a managed kiosk. These requirements are as
13443      * follows:
13444      * <ul>
13445      *     <li>The device is in Lock Task (therefore there is also a Device Owner app on the
13446      *     device)</li>
13447      *     <li>The Lock Task feature {@link DevicePolicyManager#LOCK_TASK_FEATURE_SYSTEM_INFO} is
13448      *     not enabled, so the system info in the status bar is not visible</li>
13449      *     <li>The device does not have a secure lock screen (e.g. it has no lock screen or has
13450      *     swipe-to-unlock)</li>
13451      *     <li>The device is not in the middle of an ephemeral user session</li>
13452      * </ul>
13453      *
13454      * <p>Publicly-accessible dedicated devices don't have the same privacy model as
13455      * personally-used devices. In particular, user consent popups don't make sense as a barrier to
13456      * accessing persistent data on these devices since the user giving consent and the user whose
13457      * data is on the device are unlikely to be the same. These consent popups prevent the true
13458      * remote management of these devices.
13459      *
13460      * <p>This condition is not sufficient to cover APIs that would access data that only lives for
13461      * the duration of the user's session, since the user has an expectation of privacy in these
13462      * conditions that more closely resembles use of a personal device. In those cases, see {@link
13463      * #isUnattendedManagedKiosk()}.
13464      *
13465      * @hide
13466      */
13467     @SystemApi
13468     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isManagedKiosk()13469     public boolean isManagedKiosk() {
13470         throwIfParentInstance("isManagedKiosk");
13471         if (mService != null) {
13472             try {
13473                 return mService.isManagedKiosk();
13474             } catch (RemoteException e) {
13475                 throw e.rethrowFromSystemServer();
13476             }
13477         }
13478         return false;
13479     }
13480 
13481     /**
13482      * Returns whether the device is being used as an unattended managed kiosk. These requirements
13483      * are as follows:
13484      * <ul>
13485      *     <li>The device is being used as a managed kiosk, as defined at {@link
13486      *     #isManagedKiosk()}</li>
13487      *     <li>The device has not received user input for at least 30 minutes</li>
13488      * </ul>
13489      *
13490      * <p>See {@link #isManagedKiosk()} for context. This is a stronger requirement that also
13491      * ensures that the device hasn't been interacted with recently, making it an appropriate check
13492      * for privacy-sensitive APIs that wouldn't be appropriate during an active user session.
13493      *
13494      * @hide
13495      */
13496     @SystemApi
13497     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isUnattendedManagedKiosk()13498     public boolean isUnattendedManagedKiosk() {
13499         throwIfParentInstance("isUnattendedManagedKiosk");
13500         if (mService != null) {
13501             try {
13502                 return mService.isUnattendedManagedKiosk();
13503             } catch (RemoteException e) {
13504                 throw e.rethrowFromSystemServer();
13505             }
13506         }
13507         return false;
13508     }
13509 
13510     /**
13511      * Starts an activity to view calendar events in the managed profile.
13512      *
13513      * @param eventId the id of the event to be viewed
13514      * @param start the start time of the event
13515      * @param end the end time of the event
13516      * @param allDay if the event is an all-day event
13517      * @param flags flags to be set for the intent
13518      * @return {@code true} if the activity is started successfully, {@code false} otherwise
13519      *
13520      * @see CalendarContract#startViewCalendarEventInManagedProfile(Context, String, long, long,
13521      * long, boolean, int)
13522      *
13523      * @hide
13524      */
startViewCalendarEventInManagedProfile(long eventId, long start, long end, boolean allDay, int flags)13525     public boolean startViewCalendarEventInManagedProfile(long eventId, long start, long end,
13526             boolean allDay, int flags) {
13527         throwIfParentInstance("startViewCalendarEventInManagedProfile");
13528         if (mService != null) {
13529             try {
13530                 return mService.startViewCalendarEventInManagedProfile(mContext.getPackageName(),
13531                         eventId, start, end, allDay, flags);
13532             } catch (RemoteException e) {
13533                 throw e.rethrowFromSystemServer();
13534             }
13535         }
13536         return false;
13537     }
13538 
13539     /**
13540      * Called by Device owner to disable user control over apps. User will not be able to clear
13541      * app data or force-stop packages.
13542      *
13543      * @param admin which {@link DeviceAdminReceiver} this request is associated with
13544      * @param packages The package names for the apps.
13545      * @throws SecurityException if {@code admin} is not a device owner.
13546      */
setUserControlDisabledPackages(@onNull ComponentName admin, @NonNull List<String> packages)13547     public void setUserControlDisabledPackages(@NonNull ComponentName admin,
13548             @NonNull List<String> packages) {
13549         throwIfParentInstance("setUserControlDisabledPackages");
13550         if (mService != null) {
13551             try {
13552                 mService.setUserControlDisabledPackages(admin, packages);
13553             } catch (RemoteException re) {
13554                 throw re.rethrowFromSystemServer();
13555             }
13556         }
13557     }
13558 
13559     /**
13560      * Returns the list of packages over which user control is disabled by the device owner.
13561      *
13562      * @param admin which {@link DeviceAdminReceiver} this request is associated with
13563      * @throws SecurityException if {@code admin} is not a device owner.
13564      */
getUserControlDisabledPackages(@onNull ComponentName admin)13565     public @NonNull List<String> getUserControlDisabledPackages(@NonNull ComponentName admin) {
13566         throwIfParentInstance("getUserControlDisabledPackages");
13567         if (mService != null) {
13568             try {
13569                 return mService.getUserControlDisabledPackages(admin);
13570             } catch (RemoteException re) {
13571                 throw re.rethrowFromSystemServer();
13572             }
13573         }
13574         return Collections.emptyList();
13575     }
13576 
13577     /**
13578      * Called by device owner or profile owner of an organization-owned managed profile to toggle
13579      * Common Criteria mode for the device. When the device is in Common Criteria mode,
13580      * certain device functionalities are tuned to meet the higher
13581      * security level required by Common Criteria certification. For example:
13582      * <ul>
13583      * <li> Bluetooth long term key material is additionally integrity-protected with AES-GCM. </li>
13584      * <li> WiFi configuration store is additionally integrity-protected with AES-GCM. </li>
13585      * </ul>
13586      * Common Criteria mode is disabled by default.
13587      *
13588      * <p><em>Note:</em> if Common Critera mode is turned off after being enabled previously,
13589      * all existing WiFi configurations will be lost.
13590      *
13591      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
13592      * @param enabled whether Common Criteria mode should be enabled or not.
13593      */
setCommonCriteriaModeEnabled(@onNull ComponentName admin, boolean enabled)13594     public void setCommonCriteriaModeEnabled(@NonNull ComponentName admin, boolean enabled) {
13595         throwIfParentInstance("setCommonCriteriaModeEnabled");
13596         if (mService != null) {
13597             try {
13598                 mService.setCommonCriteriaModeEnabled(admin, enabled);
13599             } catch (RemoteException e) {
13600                 throw e.rethrowFromSystemServer();
13601             }
13602         }
13603     }
13604 
13605     /**
13606      * Returns whether Common Criteria mode is currently enabled. Device owner and profile owner of
13607      * an organization-owned managed profile can query its own Common Criteria mode setting by
13608      * calling this method with its admin {@link ComponentName}. Any caller can obtain the
13609      * aggregated device-wide Common Criteria mode state by passing {@code null} as the
13610      * {@code admin} argument.
13611      *
13612      * @param admin which {@link DeviceAdminReceiver} this request is associated with, or
13613      *     {@code null} if the caller is not a device admin.
13614      * @return {@code true} if Common Criteria mode is enabled, {@code false} otherwise.
13615      */
isCommonCriteriaModeEnabled(@ullable ComponentName admin)13616     public boolean isCommonCriteriaModeEnabled(@Nullable ComponentName admin) {
13617         throwIfParentInstance("isCommonCriteriaModeEnabled");
13618         if (mService != null) {
13619             try {
13620                 return mService.isCommonCriteriaModeEnabled(admin);
13621             } catch (RemoteException e) {
13622                 throw e.rethrowFromSystemServer();
13623             }
13624         }
13625         return false;
13626     }
13627 
13628     /**
13629      * Called by profile owner of an organization-owned managed profile to check whether
13630      * personal apps are suspended.
13631      *
13632      * @return a bitmask of reasons for personal apps suspension or
13633      *     {@link #PERSONAL_APPS_NOT_SUSPENDED} if apps are not suspended.
13634      * @see #setPersonalAppsSuspended
13635      */
getPersonalAppsSuspendedReasons( @onNull ComponentName admin)13636     public @PersonalAppsSuspensionReason int getPersonalAppsSuspendedReasons(
13637             @NonNull ComponentName admin) {
13638         throwIfParentInstance("getPersonalAppsSuspendedReasons");
13639         if (mService != null) {
13640             try {
13641                 return mService.getPersonalAppsSuspendedReasons(admin);
13642             } catch (RemoteException re) {
13643                 throw re.rethrowFromSystemServer();
13644             }
13645         }
13646         return 0;
13647     }
13648 
13649     /**
13650      * Called by a profile owner of an organization-owned managed profile to suspend personal
13651      * apps on the device. When personal apps are suspended the device can only be used for calls.
13652      *
13653      * <p>When personal apps are suspended, an ongoing notification about that is shown to the user.
13654      * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE}
13655      * in the profile owner package. Profile owner implementation that uses personal apps suspension
13656      * must handle this intent.
13657      *
13658      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
13659      * @param suspended Whether personal apps should be suspended.
13660      * @throws IllegalStateException if the profile owner doesn't have an activity that handles
13661      *        {@link #ACTION_CHECK_POLICY_COMPLIANCE}
13662      */
setPersonalAppsSuspended(@onNull ComponentName admin, boolean suspended)13663     public void setPersonalAppsSuspended(@NonNull ComponentName admin, boolean suspended) {
13664         throwIfParentInstance("setPersonalAppsSuspended");
13665         if (mService != null) {
13666             try {
13667                 mService.setPersonalAppsSuspended(admin, suspended);
13668             } catch (RemoteException re) {
13669                 throw re.rethrowFromSystemServer();
13670             }
13671         }
13672     }
13673 
13674     /**
13675      * Called by a profile owner of an organization-owned managed profile to set maximum time
13676      * the profile is allowed to be turned off. If the profile is turned off for longer, personal
13677      * apps are suspended on the device.
13678      *
13679      * <p>When personal apps are suspended, an ongoing notification about that is shown to the user.
13680      * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE}
13681      * in the profile owner package. Profile owner implementation that uses personal apps suspension
13682      * must handle this intent.
13683      *
13684      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
13685      * @param timeoutMillis Maximum time the profile is allowed to be off in milliseconds or 0 if
13686      *        not limited. The minimum non-zero value corresponds to 72 hours. If an admin sets a
13687      *        smaller non-zero vaulue, 72 hours will be set instead.
13688      * @throws IllegalStateException if the profile owner doesn't have an activity that handles
13689      *        {@link #ACTION_CHECK_POLICY_COMPLIANCE}
13690      * @see #setPersonalAppsSuspended
13691      */
setManagedProfileMaximumTimeOff(@onNull ComponentName admin, long timeoutMillis)13692     public void setManagedProfileMaximumTimeOff(@NonNull ComponentName admin, long timeoutMillis) {
13693         throwIfParentInstance("setManagedProfileMaximumTimeOff");
13694         if (mService != null) {
13695             try {
13696                 mService.setManagedProfileMaximumTimeOff(admin, timeoutMillis);
13697             } catch (RemoteException re) {
13698                 throw re.rethrowFromSystemServer();
13699             }
13700         }
13701     }
13702 
13703      /**
13704      * Called by a profile owner of an organization-owned managed profile to get maximum time
13705      * the profile is allowed to be turned off.
13706      *
13707      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
13708      * @return Maximum time the profile is allowed to be off in milliseconds or 0 if not limited.
13709      * @see #setPersonalAppsSuspended
13710      */
getManagedProfileMaximumTimeOff(@onNull ComponentName admin)13711     public long getManagedProfileMaximumTimeOff(@NonNull ComponentName admin) {
13712         throwIfParentInstance("getManagedProfileMaximumTimeOff");
13713         if (mService != null) {
13714             try {
13715                 return mService.getManagedProfileMaximumTimeOff(admin);
13716             } catch (RemoteException re) {
13717                 throw re.rethrowFromSystemServer();
13718             }
13719         }
13720         return 0;
13721     }
13722 
13723     /**
13724      * Called by a profile owner of an organization-owned managed profile to acknowledge that the
13725      * device is compliant and the user can turn the profile off if needed according to the maximum
13726      * time off policy.
13727      *
13728      * This method should be called when the device is deemed compliant after getting
13729      * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)} callback in
13730      * case it is overridden. Before this method is called the user is still free to turn the
13731      * profile off, but the timer won't be reset, so personal apps will be suspended sooner.
13732      *
13733      * DPCs only need acknowledging device compliance if they override
13734      * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)}, otherwise
13735      * compliance is acknowledged automatically.
13736      *
13737      * @throws IllegalStateException if the user isn't unlocked
13738      * @see #isComplianceAcknowledgementRequired()
13739      * @see #setManagedProfileMaximumTimeOff(ComponentName, long)
13740      * @see DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)
13741      */
acknowledgeDeviceCompliant()13742     public void acknowledgeDeviceCompliant() {
13743         throwIfParentInstance("acknowledgeDeviceCompliant");
13744         if (mService != null) {
13745             try {
13746                 mService.acknowledgeDeviceCompliant();
13747             } catch (RemoteException re) {
13748                 throw re.rethrowFromSystemServer();
13749             }
13750         }
13751     }
13752 
13753     /**
13754      * Called by a profile owner of an organization-owned managed profile to query whether it needs
13755      * to acknowledge device compliance to allow the user to turn the profile off if needed
13756      * according to the maximum profile time off policy.
13757      *
13758      * Normally when acknowledgement is needed the DPC gets a
13759      * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)} callback.
13760      * But if the callback was not delivered or handled for some reason, this method can be used to
13761      * verify if acknowledgement is needed.
13762      *
13763      * @throws IllegalStateException if the user isn't unlocked
13764      * @see #acknowledgeDeviceCompliant()
13765      * @see #setManagedProfileMaximumTimeOff(ComponentName, long)
13766      * @see DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)
13767      */
isComplianceAcknowledgementRequired()13768     public boolean isComplianceAcknowledgementRequired() {
13769         throwIfParentInstance("isComplianceAcknowledgementRequired");
13770         if (mService != null) {
13771             try {
13772                 return mService.isComplianceAcknowledgementRequired();
13773             } catch (RemoteException re) {
13774                 throw re.rethrowFromSystemServer();
13775             }
13776         }
13777         return false;
13778     }
13779 
13780     /**
13781      * Returns {@code true} when {@code userId} has a profile owner that is capable of resetting
13782      * password in RUNNING_LOCKED state. For that it should have at least one direct boot aware
13783      * component and have an active password reset token. Can only be called by the system.
13784      * @hide
13785      */
canProfileOwnerResetPasswordWhenLocked(int userId)13786     public boolean canProfileOwnerResetPasswordWhenLocked(int userId) {
13787         if (mService != null) {
13788             try {
13789                 return mService.canProfileOwnerResetPasswordWhenLocked(userId);
13790             } catch (RemoteException re) {
13791                 throw re.rethrowFromSystemServer();
13792             }
13793         }
13794         return false;
13795     }
13796 
13797     /**
13798      * Used by CTS to set the result of the next safety operation check.
13799      *
13800      * @hide
13801      */
13802     @TestApi
13803     @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
setNextOperationSafety(@evicePolicyOperation int operation, @OperationSafetyReason int reason)13804     public void setNextOperationSafety(@DevicePolicyOperation int operation,
13805             @OperationSafetyReason int reason) {
13806         if (mService != null) {
13807             try {
13808                 mService.setNextOperationSafety(operation, reason);
13809             } catch (RemoteException re) {
13810                 throw re.rethrowFromSystemServer();
13811             }
13812         }
13813     }
13814 
13815     /**
13816      * Returns an enrollment-specific identifier of this device, which is guaranteed to be the same
13817      * value for the same device, enrolled into the same organization by the same managing app.
13818      * This identifier is high-entropy, useful for uniquely identifying individual devices within
13819      * the same organisation.
13820      * It is available both in a work profile and on a fully-managed device.
13821      * The identifier would be consistent even if the work profile is removed and enrolled again
13822      * (to the same organization), or the device is factory reset and re-enrolled.
13823      *
13824      * Can only be called by the Profile Owner or Device Owner, if the
13825      * {@link #setOrganizationId(String)} was previously called.
13826      * If {@link #setOrganizationId(String)} was not called, then the returned value will be an
13827      * empty string.
13828      *
13829      * <p>Note about access to device identifiers: a device owner, a profile owner of an
13830      * organization-owned device or the delegated certificate installer (holding the
13831      * {@link #DELEGATION_CERT_INSTALL} delegation) on such a device can still obtain hardware
13832      * identifiers by calling e.g. {@link android.os.Build#getSerial()}, in addition to using
13833      * this method. However, a profile owner on a personal (non organization-owned) device, or the
13834      * delegated certificate installer on such a device, cannot obtain hardware identifiers anymore
13835      * and must switch to using this method.
13836      *
13837      * @return A stable, enrollment-specific identifier.
13838      * @throws SecurityException if the caller is not a profile owner or device owner.
13839      */
getEnrollmentSpecificId()13840     @NonNull public String getEnrollmentSpecificId() {
13841         throwIfParentInstance("getEnrollmentSpecificId");
13842         if (mService == null) {
13843             return "";
13844         }
13845 
13846         try {
13847             return mService.getEnrollmentSpecificId(mContext.getPackageName());
13848         } catch (RemoteException re) {
13849             throw re.rethrowFromSystemServer();
13850         }
13851     }
13852 
13853     /**
13854      * Sets the Enterprise ID for the work profile or managed device. This is a requirement for
13855      * generating an enrollment-specific ID for the device, see {@link #getEnrollmentSpecificId()}.
13856      *
13857      * It is recommended that the Enterprise ID is at least 6 characters long, and no more than
13858      * 64 characters.
13859      *
13860      * @param enterpriseId An identifier of the organization this work profile or device is
13861      *                     enrolled into.
13862      */
setOrganizationId(@onNull String enterpriseId)13863     public void setOrganizationId(@NonNull String enterpriseId) {
13864         throwIfParentInstance("setOrganizationId");
13865         setOrganizationIdForUser(mContext.getPackageName(), enterpriseId, myUserId());
13866     }
13867 
13868     /**
13869      * Sets the Enterprise ID for the work profile or managed device. This is a requirement for
13870      * generating an enrollment-specific ID for the device, see
13871      * {@link #getEnrollmentSpecificId()}.
13872      *
13873      * @hide
13874      */
setOrganizationIdForUser(@onNull String packageName, @NonNull String enterpriseId, @UserIdInt int userId)13875     public void setOrganizationIdForUser(@NonNull String packageName,
13876             @NonNull String enterpriseId, @UserIdInt int userId) {
13877         if (mService == null) {
13878             return;
13879         }
13880         try {
13881             mService.setOrganizationIdForUser(packageName, enterpriseId, userId);
13882         } catch (RemoteException re) {
13883             throw re.rethrowFromSystemServer();
13884         }
13885     }
13886 
13887     /**
13888      * Clears organization ID set by the DPC and resets the precomputed enrollment specific ID.
13889      * @hide
13890      */
13891     @TestApi
13892     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
clearOrganizationId()13893     public void clearOrganizationId() {
13894         if (mService == null) {
13895             return;
13896         }
13897         try {
13898             mService.clearOrganizationIdForUser(myUserId());
13899         } catch (RemoteException re) {
13900             throw re.rethrowFromSystemServer();
13901         }
13902     }
13903 
13904     /**
13905      * Creates and provisions a managed profile and sets the
13906      * {@link ManagedProfileProvisioningParams#getProfileAdminComponentName()} as the profile
13907      * owner.
13908      *
13909      * <p>The method {@link #checkProvisioningPreCondition} must be returning {@link #CODE_OK}
13910      * before calling this method.
13911      *
13912      * @param provisioningParams Params required to provision a managed profile,
13913      * see {@link ManagedProfileProvisioningParams}.
13914      * @return The {@link UserHandle} of the created profile or {@code null} if the service is
13915      * not available.
13916      * @throws SecurityException if the caller does not hold
13917      * {@link android.Manifest.permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
13918      * @throws ProvisioningException if an error occurred during provisioning.
13919      * @hide
13920      */
13921     @Nullable
13922     @TestApi
createAndProvisionManagedProfile( @onNull ManagedProfileProvisioningParams provisioningParams)13923     public UserHandle createAndProvisionManagedProfile(
13924             @NonNull ManagedProfileProvisioningParams provisioningParams)
13925             throws ProvisioningException {
13926         if (mService == null) {
13927             return null;
13928         }
13929         try {
13930             return mService.createAndProvisionManagedProfile(
13931                     provisioningParams, mContext.getPackageName());
13932         } catch (ServiceSpecificException e) {
13933             throw new ProvisioningException(e, e.errorCode);
13934         } catch (RemoteException e) {
13935             throw e.rethrowFromSystemServer();
13936         }
13937     }
13938 
13939     /**
13940      * Provisions a managed device and sets the {@code deviceAdminComponentName} as the device
13941      * owner.
13942      *
13943      * <p>The method {@link #checkProvisioningPreCondition} must be returning {@link #CODE_OK}
13944      * before calling this method.
13945      *
13946      * @param provisioningParams Params required to provision a fully managed device,
13947      * see {@link FullyManagedDeviceProvisioningParams}.
13948      *
13949      * @throws SecurityException if the caller does not hold
13950      * {@link android.Manifest.permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
13951      * @throws ProvisioningException if an error occurred during provisioning.
13952      *
13953      * @hide
13954      */
13955     @TestApi
13956     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
provisionFullyManagedDevice( @onNull FullyManagedDeviceProvisioningParams provisioningParams)13957     public void provisionFullyManagedDevice(
13958             @NonNull FullyManagedDeviceProvisioningParams provisioningParams)
13959             throws ProvisioningException {
13960         if (mService != null) {
13961             try {
13962                 mService.provisionFullyManagedDevice(provisioningParams, mContext.getPackageName());
13963             } catch (ServiceSpecificException e) {
13964                 throw new ProvisioningException(e, e.errorCode);
13965             } catch (RemoteException re) {
13966                 throw re.rethrowFromSystemServer();
13967             }
13968         }
13969     }
13970 
13971     /**
13972      * Resets the default cross profile intent filters that were set during
13973      * {@link #createAndProvisionManagedProfile} between {@code userId} and all it's managed
13974      * profiles if any.
13975      *
13976      * @hide
13977      */
13978     @TestApi
13979     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
resetDefaultCrossProfileIntentFilters(@serIdInt int userId)13980     public void resetDefaultCrossProfileIntentFilters(@UserIdInt int userId) {
13981         if (mService != null) {
13982             try {
13983                 mService.resetDefaultCrossProfileIntentFilters(userId);
13984             } catch (RemoteException re) {
13985                 throw re.rethrowFromSystemServer();
13986             }
13987         }
13988     }
13989 
13990     /**
13991      * Returns true if the caller is running on a device where the admin can grant
13992      * permissions related to device sensors.
13993      * This is a signal that the device is a fully-managed device where personal usage is
13994      * discouraged.
13995      * The list of permissions is listed in
13996      * {@link #setPermissionGrantState(ComponentName, String, String, int)}.
13997      *
13998      * May be called by any app.
13999      * @return true if the app can grant device sensors-related permissions, false otherwise.
14000      */
canAdminGrantSensorsPermissions()14001     public boolean canAdminGrantSensorsPermissions() {
14002         throwIfParentInstance("canAdminGrantSensorsPermissions");
14003         if (mService == null) {
14004             return false;
14005         }
14006         try {
14007             return mService.canAdminGrantSensorsPermissionsForUser(myUserId());
14008         } catch (RemoteException re) {
14009             throw re.rethrowFromSystemServer();
14010         }
14011     }
14012 
14013     /**
14014      * Sets the device owner type for a managed device (e.g. financed device).
14015      *
14016      * @param admin The {@link DeviceAdminReceiver} that is the device owner.
14017      * @param deviceOwnerType The device owner type is set to. Use
14018      * {@link #DEVICE_OWNER_TYPE_DEFAULT} for the default device owner type. Use
14019      * {@link #DEVICE_OWNER_TYPE_FINANCED} for the financed device owner type.
14020      *
14021      * @throws IllegalStateException When admin is not the device owner, or there is no device
14022      *     owner, or attempting to set the device owner type again for the same admin.
14023      * @throws SecurityException If the caller does not have the permission
14024      *     {@link permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
14025      *
14026      * @hide
14027      */
setDeviceOwnerType(@onNull ComponentName admin, @DeviceOwnerType int deviceOwnerType)14028     public void setDeviceOwnerType(@NonNull ComponentName admin,
14029             @DeviceOwnerType int deviceOwnerType) {
14030         throwIfParentInstance("setDeviceOwnerType");
14031         if (mService != null) {
14032             try {
14033                 mService.setDeviceOwnerType(admin, deviceOwnerType);
14034             } catch (RemoteException re) {
14035                 throw re.rethrowFromSystemServer();
14036             }
14037         }
14038     }
14039 
14040     /**
14041      * Returns the device owner type for the admin used in
14042      * {@link #setDeviceOwnerType(ComponentName, int)}. {@link #DEVICE_OWNER_TYPE_DEFAULT}
14043      * would be returned when the device owner type is not set for the device owner admin.
14044      *
14045      * @param admin The {@link DeviceAdminReceiver} that is the device owner.
14046      *
14047      * @throws IllegalStateException When admin is not the device owner or there is no device owner.
14048      *
14049      * @hide
14050      */
14051     @DeviceOwnerType
getDeviceOwnerType(@onNull ComponentName admin)14052     public int getDeviceOwnerType(@NonNull ComponentName admin) {
14053         throwIfParentInstance("getDeviceOwnerType");
14054         if (mService != null) {
14055             try {
14056                 return mService.getDeviceOwnerType(admin);
14057             } catch (RemoteException re) {
14058                 throw re.rethrowFromSystemServer();
14059             }
14060         }
14061         return DEVICE_OWNER_TYPE_DEFAULT;
14062     }
14063 
14064     /**
14065      * Called by device owner or profile owner of an organization-owned managed profile to
14066      * enable or disable USB data signaling for the device. When disabled, USB data connections
14067      * (except from charging functions) are prohibited.
14068      *
14069      * <p> This API is not supported on all devices, the caller should call
14070      * {@link #canUsbDataSignalingBeDisabled()} to check whether enabling or disabling USB data
14071      * signaling is supported on the device.
14072      *
14073      * @param enabled whether USB data signaling should be enabled or not.
14074      * @throws SecurityException if the caller is not a device owner or a profile owner on
14075      *         an organization-owned managed profile.
14076      * @throws IllegalStateException if disabling USB data signaling is not supported or
14077      *         if USB data signaling fails to be enabled/disabled.
14078      */
setUsbDataSignalingEnabled(boolean enabled)14079     public void setUsbDataSignalingEnabled(boolean enabled) {
14080         throwIfParentInstance("setUsbDataSignalingEnabled");
14081         if (mService != null) {
14082             try {
14083                 mService.setUsbDataSignalingEnabled(mContext.getPackageName(), enabled);
14084             } catch (RemoteException e) {
14085                 throw e.rethrowFromSystemServer();
14086             }
14087         }
14088     }
14089 
14090     /**
14091      * Returns whether USB data signaling is currently enabled.
14092      *
14093      * <p> When called by a device owner or profile owner of an organization-owned managed profile,
14094      * this API returns whether USB data signaling is currently enabled by that admin. When called
14095      * by any other app, returns whether USB data signaling is currently enabled on the device.
14096      *
14097      * @return {@code true} if USB data signaling is enabled, {@code false} otherwise.
14098      */
isUsbDataSignalingEnabled()14099     public boolean isUsbDataSignalingEnabled() {
14100         throwIfParentInstance("isUsbDataSignalingEnabled");
14101         if (mService != null) {
14102             try {
14103                 return mService.isUsbDataSignalingEnabled(mContext.getPackageName());
14104             } catch (RemoteException e) {
14105                 throw e.rethrowFromSystemServer();
14106             }
14107         }
14108         return true;
14109     }
14110 
14111     /**
14112      * Called by the system to check whether USB data signaling is currently enabled for this user.
14113      *
14114      * @param userId which user to check for.
14115      * @return {@code true} if USB data signaling is enabled, {@code false} otherwise.
14116      * @hide
14117      */
isUsbDataSignalingEnabledForUser(@serIdInt int userId)14118     public boolean isUsbDataSignalingEnabledForUser(@UserIdInt int userId) {
14119         throwIfParentInstance("isUsbDataSignalingEnabledForUser");
14120         if (mService != null) {
14121             try {
14122                 return mService.isUsbDataSignalingEnabledForUser(userId);
14123             } catch (RemoteException e) {
14124                 throw e.rethrowFromSystemServer();
14125             }
14126         }
14127         return true;
14128     }
14129 
14130     /**
14131      * Returns whether enabling or disabling USB data signaling is supported on the device.
14132      *
14133      * @return {@code true} if the device supports enabling and disabling USB data signaling.
14134      */
canUsbDataSignalingBeDisabled()14135     public boolean canUsbDataSignalingBeDisabled() {
14136         throwIfParentInstance("canUsbDataSignalingBeDisabled");
14137         if (mService != null) {
14138             try {
14139                 return mService.canUsbDataSignalingBeDisabled();
14140             } catch (RemoteException re) {
14141                 throw re.rethrowFromSystemServer();
14142             }
14143         }
14144         return false;
14145     }
14146 
14147     /**
14148      * Gets the list of {@link #isAffiliatedUser() affiliated} users running on foreground.
14149      *
14150      * @return list of {@link #isAffiliatedUser() affiliated} users running on foreground.
14151      *
14152      * @throws SecurityException if the calling application is not a device owner
14153      */
14154     @NonNull
listForegroundAffiliatedUsers()14155     public List<UserHandle> listForegroundAffiliatedUsers() {
14156         if (mService == null) return Collections.emptyList();
14157 
14158         try {
14159             return mService.listForegroundAffiliatedUsers();
14160         } catch (RemoteException re) {
14161             throw re.rethrowFromSystemServer();
14162         }
14163     }
14164 
14165     /**
14166      * Lists apps that are exempt from policies (such as
14167      * {@link #setPackagesSuspended(ComponentName, String[], boolean)}).
14168      *
14169      * @hide
14170      */
14171     @TestApi
14172     @RequiresPermission(value = android.Manifest.permission.MANAGE_DEVICE_ADMINS)
getPolicyExemptApps()14173     public @NonNull Set<String> getPolicyExemptApps() {
14174         if (mService == null) return Collections.emptySet();
14175 
14176         try {
14177             return new HashSet<>(mService.listPolicyExemptApps());
14178         } catch (RemoteException e) {
14179             throw e.rethrowFromSystemServer();
14180         }
14181     }
14182 }
14183