• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.app.admin;
18 
19 import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
20 
21 import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
22 
23 import android.Manifest.permission;
24 import android.accounts.Account;
25 import android.annotation.CallbackExecutor;
26 import android.annotation.ColorInt;
27 import android.annotation.IntDef;
28 import android.annotation.NonNull;
29 import android.annotation.Nullable;
30 import android.annotation.RequiresFeature;
31 import android.annotation.RequiresPermission;
32 import android.annotation.SdkConstant;
33 import android.annotation.SdkConstant.SdkConstantType;
34 import android.annotation.StringDef;
35 import android.annotation.SuppressLint;
36 import android.annotation.SystemApi;
37 import android.annotation.SystemService;
38 import android.annotation.TestApi;
39 import android.annotation.UserHandleAware;
40 import android.annotation.UserIdInt;
41 import android.annotation.WorkerThread;
42 import android.app.Activity;
43 import android.app.IServiceConnection;
44 import android.app.KeyguardManager;
45 import android.app.admin.SecurityLog.SecurityEvent;
46 import android.compat.annotation.UnsupportedAppUsage;
47 import android.content.ComponentName;
48 import android.content.Context;
49 import android.content.Intent;
50 import android.content.IntentFilter;
51 import android.content.ServiceConnection;
52 import android.content.pm.ApplicationInfo;
53 import android.content.pm.IPackageDataObserver;
54 import android.content.pm.PackageManager;
55 import android.content.pm.PackageManager.NameNotFoundException;
56 import android.content.pm.ParceledListSlice;
57 import android.content.pm.UserInfo;
58 import android.graphics.Bitmap;
59 import android.graphics.drawable.Drawable;
60 import android.net.PrivateDnsConnectivityChecker;
61 import android.net.ProxyInfo;
62 import android.net.Uri;
63 import android.nfc.NfcAdapter;
64 import android.os.Binder;
65 import android.os.Build;
66 import android.os.Bundle;
67 import android.os.IpcDataCache;
68 import android.os.ParcelFileDescriptor;
69 import android.os.Parcelable;
70 import android.os.PersistableBundle;
71 import android.os.Process;
72 import android.os.RemoteCallback;
73 import android.os.RemoteException;
74 import android.os.ServiceSpecificException;
75 import android.os.UserHandle;
76 import android.os.UserManager;
77 import android.os.UserManager.UserOperationException;
78 import android.os.UserManager.UserOperationResult;
79 import android.provider.CalendarContract;
80 import android.provider.ContactsContract.Directory;
81 import android.provider.Settings;
82 import android.security.AttestedKeyPair;
83 import android.security.Credentials;
84 import android.security.KeyChain;
85 import android.security.KeyChainException;
86 import android.security.keymaster.KeymasterCertificateChain;
87 import android.security.keystore.AttestationUtils;
88 import android.security.keystore.KeyAttestationException;
89 import android.security.keystore.KeyGenParameterSpec;
90 import android.security.keystore.ParcelableKeyGenParameterSpec;
91 import android.security.keystore.StrongBoxUnavailableException;
92 import android.service.restrictions.RestrictionsReceiver;
93 import android.telephony.TelephonyManager;
94 import android.telephony.data.ApnSetting;
95 import android.text.TextUtils;
96 import android.util.ArraySet;
97 import android.util.DebugUtils;
98 import android.util.Log;
99 import android.util.Pair;
100 
101 import com.android.internal.annotations.VisibleForTesting;
102 import com.android.internal.infra.AndroidFuture;
103 import com.android.internal.net.NetworkUtilsInternal;
104 import com.android.internal.os.BackgroundThread;
105 import com.android.internal.util.Preconditions;
106 import com.android.org.conscrypt.TrustedCertificateStore;
107 
108 import java.io.ByteArrayInputStream;
109 import java.io.FileNotFoundException;
110 import java.io.IOException;
111 import java.lang.annotation.Retention;
112 import java.lang.annotation.RetentionPolicy;
113 import java.net.InetSocketAddress;
114 import java.net.Proxy;
115 import java.security.KeyFactory;
116 import java.security.KeyPair;
117 import java.security.NoSuchAlgorithmException;
118 import java.security.PrivateKey;
119 import java.security.cert.Certificate;
120 import java.security.cert.CertificateException;
121 import java.security.cert.CertificateFactory;
122 import java.security.cert.X509Certificate;
123 import java.security.spec.InvalidKeySpecException;
124 import java.security.spec.PKCS8EncodedKeySpec;
125 import java.util.ArrayList;
126 import java.util.Arrays;
127 import java.util.Collections;
128 import java.util.HashSet;
129 import java.util.List;
130 import java.util.Map;
131 import java.util.Objects;
132 import java.util.Set;
133 import java.util.concurrent.CompletableFuture;
134 import java.util.concurrent.ExecutionException;
135 import java.util.concurrent.Executor;
136 import java.util.function.Consumer;
137 
138 // TODO(b/172376923) - add CarDevicePolicyManager examples below (or remove reference to it).
139 /**
140  * Public interface for managing policies enforced on a device. Most clients of this class must be
141  * registered with the system as a <a href="{@docRoot}guide/topics/admin/device-admin.html">device
142  * administrator</a>. Additionally, a device administrator may be registered as either a profile or
143  * device owner. A given method is accessible to all device administrators unless the documentation
144  * for that method specifies that it is restricted to either device or profile owners. Any
145  * application calling an api may only pass as an argument a device administrator component it
146  * owns. Otherwise, a {@link SecurityException} will be thrown.
147  *
148  * <p><b>Note: </b>on
149  * {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, some methods can
150  * throw an {@link UnsafeStateException} exception (for example, if the vehicle is moving), so
151  * callers running on automotive builds should wrap every method call under the methods provided by
152  * {@code android.car.admin.CarDevicePolicyManager}.
153  *
154  * <div class="special reference">
155  * <h3>Developer Guides</h3>
156  * <p>
157  * For more information about managing policies for device administration, read the <a href=
158  * "{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a> developer
159  * guide. </div>
160  */
161 @SystemService(Context.DEVICE_POLICY_SERVICE)
162 @RequiresFeature(PackageManager.FEATURE_DEVICE_ADMIN)
163 @SuppressLint("UseIcu")
164 public class DevicePolicyManager {
165 
166     private static String TAG = "DevicePolicyManager";
167 
168     private final Context mContext;
169     private final IDevicePolicyManager mService;
170     private final boolean mParentInstance;
171     private final DevicePolicyResourcesManager mResourcesManager;
172 
173     /** @hide */
DevicePolicyManager(Context context, IDevicePolicyManager service)174     public DevicePolicyManager(Context context, IDevicePolicyManager service) {
175         this(context, service, false);
176     }
177 
178     /** @hide */
179     @VisibleForTesting
DevicePolicyManager(Context context, IDevicePolicyManager service, boolean parentInstance)180     protected DevicePolicyManager(Context context, IDevicePolicyManager service,
181             boolean parentInstance) {
182         mContext = context;
183         mService = service;
184         mParentInstance = parentInstance;
185         mResourcesManager = new DevicePolicyResourcesManager(context, service);
186     }
187 
188     /**
189      * Fetch the current value of mService.  This is used in the binder cache lambda
190      * expressions.
191      */
getService()192     private final IDevicePolicyManager getService() {
193         return mService;
194     }
195 
196     /**
197      * Fetch the current value of mParentInstance.  This is used in the binder cache
198      * lambda expressions.
199      */
isParentInstance()200     private final boolean isParentInstance() {
201         return mParentInstance;
202     }
203 
204     /**
205      * Fetch the current value of mContext.  This is used in the binder cache lambda
206      * expressions.
207      */
getContext()208     private final Context getContext() {
209         return mContext;
210     }
211 
212     /** @hide test will override it. */
213     @VisibleForTesting
myUserId()214     protected int myUserId() {
215         return mContext.getUserId();
216     }
217 
218     /**
219      * Activity action: Starts the provisioning flow which sets up a managed profile.
220      *
221      * <p>A managed profile allows data separation for example for the usage of a
222      * device as a personal and corporate device. The user which provisioning is started from and
223      * the managed profile share a launcher.
224      *
225      * <p>This intent will typically be sent by a mobile device management application (MDM).
226      * Provisioning adds a managed profile and sets the MDM as the profile owner who has full
227      * control over the profile.
228      *
229      * <p>It is possible to check if provisioning is allowed or not by querying the method
230      * {@link #isProvisioningAllowed(String)}.
231      *
232      * <p>In version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this intent must contain the
233      * extra {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}.
234      * As of {@link android.os.Build.VERSION_CODES#M}, it should contain the extra
235      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead, although specifying only
236      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported.
237      *
238      * <p>The intent may also contain the following extras:
239      * <ul>
240      * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, optional </li>
241      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional, supported from
242      * {@link android.os.Build.VERSION_CODES#N}</li>
243      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
244      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
245      * <li>{@link #EXTRA_PROVISIONING_SKIP_USER_CONSENT}, optional</li>
246      * <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION}, optional</li>
247      * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
248      * </ul>
249      *
250      * <p>When managed provisioning has completed, broadcasts are sent to the application specified
251      * in the provisioning intent. The
252      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the
253      * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in
254      * the primary profile.
255      *
256      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when managed provisioning has
257      * completed, along with the above broadcast, activity intent
258      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the profile owner.
259      *
260      * <p>If provisioning fails, the managedProfile is removed so the device returns to its
261      * previous state.
262      *
263      * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
264      * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
265      * the provisioning flow was successful, although this doesn't guarantee the full flow will
266      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
267      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
268      *
269      * <p>If a device policy management role holder (DPMRH) updater is present on the device, an
270      * internet connection attempt must be made prior to launching this intent. If internet
271      * connection could not be established, provisioning will fail unless {@link
272      * #EXTRA_PROVISIONING_ALLOW_OFFLINE} is explicitly set to {@code true}, in which case
273      * provisioning will continue without using the DPMRH. If an internet connection has been
274      * established, the DPMRH updater will be launched, which will update the DPMRH if it's not
275      * present on the device, or if it's present and not valid.
276      *
277      * <p>If a DPMRH is present on the device and valid, the provisioning flow will be deferred to
278      * it.
279      */
280     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
281     public static final String ACTION_PROVISION_MANAGED_PROFILE
282         = "android.app.action.PROVISION_MANAGED_PROFILE";
283 
284     /**
285      * Activity action: Starts the provisioning flow which sets up a managed user.
286      *
287      * <p>This intent will typically be sent by a mobile device management application (MDM).
288      * Provisioning configures the user as managed user and sets the MDM as the profile
289      * owner who has full control over the user. Provisioning can only happen before user setup has
290      * been completed. Use {@link #isProvisioningAllowed(String)} to check if provisioning is
291      * allowed.
292      *
293      * <p>The intent contains the following extras:
294      * <ul>
295      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
296      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
297      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
298      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
299      * </ul>
300      *
301      * <p>If provisioning fails, the device returns to its previous state.
302      *
303      * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
304      * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
305      * the provisioning flow was successful, although this doesn't guarantee the full flow will
306      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
307      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
308      *
309      * @hide
310      */
311     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
312     public static final String ACTION_PROVISION_MANAGED_USER
313         = "android.app.action.PROVISION_MANAGED_USER";
314 
315     /**
316      * Activity action: Starts the provisioning flow which sets up a managed device.
317      * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
318      *
319      * <p> During device owner provisioning a device admin app is set as the owner of the device.
320      * A device owner has full control over the device. The device owner can not be modified by the
321      * user.
322      *
323      * <p> A typical use case would be a device that is owned by a company, but used by either an
324      * employee or client.
325      *
326      * <p> An intent with this action can be sent only on an unprovisioned device.
327      * It is possible to check if provisioning is allowed or not by querying the method
328      * {@link #isProvisioningAllowed(String)}.
329      *
330      * <p>The intent contains the following extras:
331      * <ul>
332      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
333      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
334      * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
335      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
336      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
337      * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
338      * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional</li>
339      * </ul>
340      *
341      * <p>When device owner provisioning has completed, an intent of the type
342      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
343      * device owner.
344      *
345      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
346      * completed, along with the above broadcast, activity intent
347      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
348      *
349      * <p>If provisioning fails, the device is factory reset.
350      *
351      * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
352      * of the provisioning flow was successful, although this doesn't guarantee the full flow will
353      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
354      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
355      *
356      * @deprecated to support {@link android.os.Build.VERSION_CODES#S} and later, admin apps must
357      * implement activities with intent filters for the {@link #ACTION_GET_PROVISIONING_MODE} and
358      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} intent actions; using {@link
359      * #ACTION_PROVISION_MANAGED_DEVICE} to start provisioning will cause the provisioning to fail;
360      * to additionally support pre-{@link android.os.Build.VERSION_CODES#S}, admin apps must also
361      * continue to use this constant.
362      */
363     @Deprecated
364     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
365     public static final String ACTION_PROVISION_MANAGED_DEVICE
366         = "android.app.action.PROVISION_MANAGED_DEVICE";
367 
368     /**
369      * Activity action: launch when user provisioning completed, i.e.
370      * {@link #getUserProvisioningState()} returns one of the complete state.
371      *
372      * <p> Please note that the API behavior is not necessarily consistent across various releases,
373      * and devices, as it's contract between SetupWizard and ManagedProvisioning. The default
374      * implementation is that ManagedProvisioning launches SetupWizard in NFC provisioning only.
375      *
376      * <p> The activity must be protected by permission
377      * {@link android.Manifest.permission#BIND_DEVICE_ADMIN}, and the process must hold
378      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE} to be launched.
379      * Only one {@link ComponentName} in the entire system should be enabled, and the rest of the
380      * components are not started by this intent.
381      *
382      * @deprecated Starting from Android T, the system no longer launches an intent with this action
383      * when user provisioning completes.
384      * @hide
385      */
386     @Deprecated
387     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
388     @SystemApi
389     public static final String ACTION_STATE_USER_SETUP_COMPLETE =
390             "android.app.action.STATE_USER_SETUP_COMPLETE";
391 
392     /**
393      * Activity action: Starts the provisioning flow which sets up a managed device.
394      *
395      * <p>During device owner provisioning, a device admin app is downloaded and set as the owner of
396      * the device. A device owner has full control over the device. The device owner can not be
397      * modified by the user and the only way of resetting the device is via factory reset.
398      *
399      * <p>From version {@link android.os.Build.VERSION_CODES#Q}, the admin app can choose
400      * whether to set up a fully managed device or a managed profile. For the admin app to support
401      * this, it must have an activity with intent filter {@link #ACTION_GET_PROVISIONING_MODE} and
402      * another one with intent filter {@link #ACTION_ADMIN_POLICY_COMPLIANCE}. For example:
403      * <pre>
404      * &lt;activity
405      *     android:name=".GetProvisioningModeActivity"
406      *     android:label="@string/app_name"
407      *     android:permission="android.permission.BIND_DEVICE_ADMIN"&gt;
408      *     &lt;intent-filter&gt;
409      *         &lt;action
410      *             android:name="android.app.action.GET_PROVISIONING_MODE" /&gt;
411      *         &lt;category android:name="android.intent.category.DEFAULT" /&gt;
412      *     &lt;/intent-filter&gt;
413      * &lt;/activity&gt;
414      *
415      * &lt;activity
416      *     android:name=".PolicyComplianceActivity"
417      *     android:label="@string/app_name"
418      *     android:permission="android.permission.BIND_DEVICE_ADMIN"&gt;
419      *     &lt;intent-filter&gt;
420      *         &lt;action
421      *             android:name="android.app.action.ADMIN_POLICY_COMPLIANCE" /&gt;
422      *         &lt;category android:name="android.intent.category.DEFAULT" /&gt;
423      *     &lt;/intent-filter&gt;
424      * &lt;/activity&gt;</pre>
425      *
426      * <p>A typical use case would be a device that is owned by a company, but used by either an
427      * employee or client.
428      *
429      * <p>The provisioning message should be sent to an unprovisioned device.
430      *
431      * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
432      * by a privileged app with the permission
433      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
434      *
435      * <p>If a device policy management role holder (DPMRH) updater is present on the device, an
436      * internet connection attempt must be made prior to launching this intent. If internet
437      * connection could not be established, provisioning will fail unless {@link
438      * #EXTRA_PROVISIONING_ALLOW_OFFLINE} is explicitly set to {@code true}, in which case
439      * provisioning will continue without using the DPMRH. If an internet connection has been
440      * established, the DPMRH updater will be launched via {@link
441      * #ACTION_UPDATE_DEVICE_MANAGEMENT_ROLE_HOLDER}, which will update the DPMRH if it's not
442      * present on the device, or if it's present and not valid.
443      *
444      * <p>A DPMRH is considered valid if it has intent filters for {@link
445      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}, {@link
446      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} and {@link
447      * #ACTION_ROLE_HOLDER_PROVISION_FINALIZATION}.
448      *
449      * <p>If a DPMRH is present on the device and valid, the provisioning flow will be deferred to
450      * it via the {@link #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent.
451      *
452      * <p>The provisioning intent contains the following properties:
453      * <ul>
454      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
455      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
456      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
457      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
458      * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
459      * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
460      * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
461      * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
462      * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
463      * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
464      * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
465      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
466      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
467      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
468      * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
469      * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
470      * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
471      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
472      * <li>{@link #EXTRA_PROVISIONING_USE_MOBILE_DATA}, optional </li>
473      * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional - when not used for
474      * cloud enrollment, NFC or QR provisioning</li>
475      * </ul>
476      *
477      * @hide
478      */
479     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
480     @SystemApi
481     public static final String ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
482             "android.app.action.PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
483 
484     /**
485      * Activity action: Starts the provisioning flow which sets up a financed device.
486      *
487      * <p>During financed device provisioning, a device admin app is downloaded and set as the owner
488      * of the device. A device owner has full control over the device. The device owner can not be
489      * modified by the user.
490      *
491      * <p>A typical use case would be a device that is bought from the reseller through financing
492      * program.
493      *
494      * <p>An intent with this action can be sent only on an unprovisioned device.
495      *
496      * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
497      * by a privileged app with the permission
498      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
499      *
500      * <p>The provisioning intent contains the following properties:
501      * <ul>
502      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
503      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
504      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
505      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
506      * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
507      * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
508      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
509      * </ul>
510      *
511      * <p>Once the device admin app is set as the device owner, the following APIs are available for
512      * managing polices on the device:
513      * <ul>
514      * <li>{@link #isDeviceManaged()}</li>
515      * <li>{@link #isUninstallBlocked(ComponentName, String)}</li>
516      * <li>{@link #setUninstallBlocked(ComponentName, String, boolean)}</li>
517      * <li>{@link #setUserControlDisabledPackages(ComponentName, List)}</li>
518      * <li>{@link #getUserControlDisabledPackages(ComponentName)}</li>
519      * <li>{@link #setOrganizationName(ComponentName, CharSequence)}</li>
520      * <li>{@link #getOrganizationName(ComponentName)} </li>
521      * <li>{@link #setShortSupportMessage(ComponentName, CharSequence)}</li>
522      * <li>{@link #getShortSupportMessage(ComponentName)}</li>
523      * <li>{@link #isBackupServiceEnabled(ComponentName)}</li>
524      * <li>{@link #setBackupServiceEnabled(ComponentName, boolean)}</li>
525      * <li>{@link #isLockTaskPermitted(String)}</li>
526      * <li>{@link #setLockTaskFeatures(ComponentName, int)}, where the following lock task features
527      * can be set (otherwise a {@link SecurityException} will be thrown):</li>
528      * <ul>
529      *     <li>{@link #LOCK_TASK_FEATURE_SYSTEM_INFO}</li>
530      *     <li>{@link #LOCK_TASK_FEATURE_KEYGUARD}</li>
531      *     <li>{@link #LOCK_TASK_FEATURE_HOME}</li>
532      *     <li>{@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}</li>
533      *     <li>{@link #LOCK_TASK_FEATURE_NOTIFICATIONS}</li>
534      * </ul>
535      * <li>{@link #getLockTaskFeatures(ComponentName)}</li>
536      * <li>{@link #setLockTaskPackages(ComponentName, String[])}</li>
537      * <li>{@link #getLockTaskPackages(ComponentName)}</li>
538      * <li>{@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}</li>
539      * <li>{@link #clearPackagePersistentPreferredActivities(ComponentName, String)} </li>
540      * <li>{@link #wipeData(int)}</li>
541      * <li>{@link #isDeviceOwnerApp(String)}</li>
542      * <li>{@link #clearDeviceOwnerApp(String)}</li>
543      * <li>{@link #setPermissionGrantState(ComponentName, String, String, int)}, where
544      * {@link permission#READ_PHONE_STATE} is the <b>only</b> permission that can be
545      * {@link #PERMISSION_GRANT_STATE_GRANTED}, {@link #PERMISSION_GRANT_STATE_DENIED}, or
546      * {@link #PERMISSION_GRANT_STATE_DEFAULT} and can <b>only</b> be applied to the device admin
547      * app (otherwise a {@link SecurityException} will be thrown)</li>
548      * <li>{@link #getPermissionGrantState(ComponentName, String, String)}, where
549      * {@link permission#READ_PHONE_STATE} is the <b>only</b> permission that can be
550      * used and device admin app is the only package that can be used to retrieve the permission
551      * permission grant state for (otherwise a {@link SecurityException} will be thrown)</li>
552      * <li>{@link #addUserRestriction(ComponentName, String)}, where the following user restrictions
553      * are permitted (otherwise a {@link SecurityException} will be thrown):</li>
554      * <ul>
555      *     <li>{@link UserManager#DISALLOW_ADD_USER}</li>
556      *     <li>{@link UserManager#DISALLOW_DEBUGGING_FEATURES}</li>
557      *     <li>{@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}</li>
558      *     <li>{@link UserManager#DISALLOW_SAFE_BOOT}</li>
559      *     <li>{@link UserManager#DISALLOW_CONFIG_DATE_TIME}</li>
560      *     <li>{@link UserManager#DISALLOW_OUTGOING_CALLS}</li>
561      * </ul>
562      * <li>{@link #getUserRestrictions(ComponentName)}</li>
563      * <li>{@link #clearUserRestriction(ComponentName, String)}, where the following user
564      * restrictions are permitted (otherwise a {@link SecurityException} will be thrown):</li>
565      * <ul>
566      *     <li>{@link UserManager#DISALLOW_ADD_USER}</li>
567      *     <li>{@link UserManager#DISALLOW_DEBUGGING_FEATURES}</li>
568      *     <li>{@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}</li>
569      *     <li>{@link UserManager#DISALLOW_SAFE_BOOT}</li>
570      *     <li>{@link UserManager#DISALLOW_CONFIG_DATE_TIME}</li>
571      *     <li>{@link UserManager#DISALLOW_OUTGOING_CALLS}</li>
572      * </ul>
573      * </ul>
574      *
575      * @hide
576      */
577     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
578     @SystemApi
579     public static final String ACTION_PROVISION_FINANCED_DEVICE =
580             "android.app.action.PROVISION_FINANCED_DEVICE";
581 
582     /**
583      * Activity action: Finalizes management provisioning, should be used after user-setup
584      * has been completed and {@link #getUserProvisioningState()} returns one of:
585      * <ul>
586      * <li>{@link #STATE_USER_SETUP_INCOMPLETE}</li>
587      * <li>{@link #STATE_USER_SETUP_COMPLETE}</li>
588      * <li>{@link #STATE_USER_PROFILE_COMPLETE}</li>
589      * </ul>
590      *
591      * <p>If a device policy management role holder (DPMRH) is present on the device and
592      * valid, the provisioning flow will be deferred to it via the {@link
593      * #ACTION_ROLE_HOLDER_PROVISION_FINALIZATION} intent.
594      *
595      * @hide
596      */
597     @SystemApi
598     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
599     public static final String ACTION_PROVISION_FINALIZATION
600             = "android.app.action.PROVISION_FINALIZATION";
601 
602     /**
603      * Activity action: starts the managed profile provisioning flow inside the device policy
604      * management role holder.
605      *
606      * <p>During the managed profile provisioning flow, the platform-provided provisioning handler
607      * will delegate provisioning to the device policy management role holder, by firing this
608      * intent. Third-party mobile device management applications attempting to fire this intent will
609      * receive a {@link SecurityException}.
610      *
611      * <p>Device policy management role holders are required to have a handler for this intent
612      * action.
613      *
614      * <p>If {@link #EXTRA_ROLE_HOLDER_STATE} is supplied to this intent, it is the responsibility
615      * of the role holder to restore its state from this extra. This is the same {@link Bundle}
616      * which the role holder returns alongside {@link #RESULT_UPDATE_ROLE_HOLDER}.
617      *
618      * <p>A result code of {@link Activity#RESULT_OK} implies that managed profile provisioning
619      * finished successfully. If it did not, a result code of {@link Activity#RESULT_CANCELED}
620      * is used instead.
621      *
622      * @see #ACTION_PROVISION_MANAGED_PROFILE
623      *
624      * @hide
625      */
626     @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP)
627     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
628     @SystemApi
629     public static final String ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE =
630             "android.app.action.ROLE_HOLDER_PROVISION_MANAGED_PROFILE";
631 
632     /**
633      * Result code that can be returned by the {@link
634      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link
635      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent handlers if a work
636      * profile has been created.
637      *
638      * @hide
639      */
640     @SystemApi
641     public static final int RESULT_WORK_PROFILE_CREATED = 122;
642 
643     /**
644      * Result code that can be returned by the {@link
645      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link
646      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent handlers if the
647      * device owner was set.
648      *
649      * @hide
650      */
651     @SystemApi
652     public static final int RESULT_DEVICE_OWNER_SET = 123;
653 
654     /**
655      * Activity action: starts the trusted source provisioning flow inside the device policy
656      * management role holder.
657      *
658      * <p>During the trusted source provisioning flow, the platform-provided provisioning handler
659      * will delegate provisioning to the device policy management role holder, by firing this
660      * intent. Third-party mobile device management applications attempting to fire this intent will
661      * receive a {@link SecurityException}.
662      *
663      * <p>Device policy management role holders are required to have a handler for this intent
664      * action.
665      *
666      * <p>If {@link #EXTRA_ROLE_HOLDER_STATE} is supplied to this intent, it is the responsibility
667      * of the role holder to restore its state from this extra. This is the same {@link Bundle}
668      * which the role holder returns alongside {@link #RESULT_UPDATE_ROLE_HOLDER}.
669      *
670      * <p>The result codes can be either {@link #RESULT_WORK_PROFILE_CREATED}, {@link
671      * #RESULT_DEVICE_OWNER_SET} or {@link Activity#RESULT_CANCELED} if provisioning failed.
672      *
673      * @see #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE
674      *
675      * @hide
676      */
677     @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP)
678     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
679     @SystemApi
680     public static final String ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
681             "android.app.action.ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
682 
683     /**
684      * Activity action: starts the provisioning finalization flow inside the device policy
685      * management role holder.
686      *
687      * <p>During the provisioning finalization flow, the platform-provided provisioning handler
688      * will delegate provisioning to the device policy management role holder, by firing this
689      * intent. Third-party mobile device management applications attempting to fire this intent will
690      * receive a {@link SecurityException}.
691      *
692      * <p>Device policy management role holders are required to have a handler for this intent
693      * action.
694      *
695      * <p>This handler forwards the result from the admin app's {@link
696      * #ACTION_ADMIN_POLICY_COMPLIANCE} handler. Result code {@link Activity#RESULT_CANCELED}
697      * implies the provisioning finalization flow has failed.
698      *
699      * @see #ACTION_PROVISION_FINALIZATION
700      *
701      * @hide
702      */
703     @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP)
704     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
705     @SystemApi
706     public static final String ACTION_ROLE_HOLDER_PROVISION_FINALIZATION =
707             "android.app.action.ROLE_HOLDER_PROVISION_FINALIZATION";
708 
709     /**
710      * {@link Activity} result code which can be returned by {@link
711      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} and {@link
712      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} to signal that an update
713      * to the role holder is required.
714      *
715      * <p>This result code can be accompanied by {@link #EXTRA_ROLE_HOLDER_STATE}.
716      *
717      * @hide
718      */
719     @SystemApi
720     public static final int RESULT_UPDATE_ROLE_HOLDER = 2;
721 
722     /**
723      * A {@link PersistableBundle} extra which the role holder can use to describe its own state
724      * when it returns {@link #RESULT_UPDATE_ROLE_HOLDER}.
725      *
726      * <p>If {@link #RESULT_UPDATE_ROLE_HOLDER} was accompanied by this extra, after the update
727      * completes, the role holder's {@link #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} or {@link
728      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent will be relaunched,
729      * which will contain this extra. It is the role holder's responsibility to restore its
730      * state from this extra.
731      *
732      * <p>The content of this {@link PersistableBundle} is entirely up to the role holder. It
733      * should contain anything the role holder needs to restore its original state when it gets
734      * restarted.
735      *
736      * @hide
737      */
738     @SystemApi
739     public static final String EXTRA_ROLE_HOLDER_STATE = "android.app.extra.ROLE_HOLDER_STATE";
740 
741     /**
742      * A {@code boolean} extra which determines whether to force a role holder update, regardless
743      * of any internal conditions {@link #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} might
744      * have.
745      *
746      * <p>This extra can be provided to intents with action {@link
747      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER}.
748      *
749      * @hide
750      */
751     @SystemApi
752     public static final String EXTRA_FORCE_UPDATE_ROLE_HOLDER =
753             "android.app.extra.FORCE_UPDATE_ROLE_HOLDER";
754 
755     /**
756      * A boolean extra indicating whether offline provisioning is allowed.
757      *
758      * <p>For the online provisioning flow, there will be an attempt to download and install
759      * the latest version of the device policy management role holder. The platform will then
760      * delegate provisioning to the device policy management role holder via role holder-specific
761      * provisioning actions.
762      *
763      * <p>For the offline provisioning flow, the provisioning flow will always be handled by
764      * the platform.
765      *
766      * <p>If this extra is set to {@code false}, the provisioning flow will enforce that an
767      * internet connection is established, which will start the online provisioning flow. If an
768      * internet connection cannot be established, provisioning will fail.
769      *
770      * <p>If this extra is set to {@code true}, the provisioning flow will still try to connect to
771      * the internet, but if it fails it will start the offline provisioning flow.
772      *
773      * <p>For T if this extra is set to {@code true}, the provisioning flow will be forced through
774      * the platform and there will be no attempt to download and install the device policy
775      * management role holder.
776      *
777      * <p>The default value is {@code false}.
778      *
779      * <p>This extra is respected when provided via the provisioning intent actions such as {@link
780      * #ACTION_PROVISION_MANAGED_PROFILE}.
781      */
782     public static final String EXTRA_PROVISIONING_ALLOW_OFFLINE =
783             "android.app.extra.PROVISIONING_ALLOW_OFFLINE";
784 
785     /**
786      * A String extra holding a url that specifies the download location of the device policy
787      * management role holder package.
788      *
789      * <p>This is only meant to be used in cases when a specific variant of the role holder package
790      * is needed (such as a debug variant). If not provided, the default variant of the device
791      * manager role holder package is downloaded.
792      *
793      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
794      * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
795      * provisioning via an NFC bump.
796      *
797      * @hide
798      */
799     @SystemApi
800     public static final String EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION =
801             "android.app.extra.PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION";
802 
803     /**
804      * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
805      * android package archive at the download location specified in {@link
806      * #EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION}.
807      *
808      * <p>The signatures of an android package archive can be obtained using
809      * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
810      * {@link android.content.pm.PackageManager#GET_SIGNING_CERTIFICATES}.
811      *
812      * <p>If {@link #EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION} is provided, it must
813      * be accompanied by this extra. The provided checksum must match the checksum of any signature
814      * of the file at the download location. If the checksum does not match an error will be shown
815      * to the user and the user will be asked to factory reset the device.
816      *
817      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
818      * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
819      * provisioning via an NFC bump.
820      *
821      * @hide
822      */
823     @SystemApi
824     public static final String EXTRA_PROVISIONING_ROLE_HOLDER_SIGNATURE_CHECKSUM =
825             "android.app.extra.PROVISIONING_ROLE_HOLDER_SIGNATURE_CHECKSUM";
826 
827     /**
828      * A String extra holding a http cookie header which should be used in the http request to the
829      * url specified in {@link #EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION}.
830      *
831      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
832      * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
833      * provisioning via an NFC bump.
834      *
835      * @hide
836      */
837     @SystemApi
838     public static final String EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_COOKIE_HEADER =
839             "android.app.extra.PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_COOKIE_HEADER";
840 
841     /**
842      * An extra of type {@link android.os.PersistableBundle} that allows the provisioning initiator
843      * to pass data to the device policy management role holder.
844      *
845      * <p>The device policy management role holder will receive this extra via the {@link
846      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent.
847      *
848      * <p>The contents of this extra are up to the contract between the provisioning initiator
849      * and the device policy management role holder.
850      *
851      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
852      * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
853      * provisioning via an NFC bump.
854      *
855      * @hide
856      */
857     @SystemApi
858     public static final String EXTRA_PROVISIONING_ROLE_HOLDER_EXTRAS_BUNDLE =
859             "android.app.extra.PROVISIONING_ROLE_HOLDER_EXTRAS_BUNDLE";
860 
861     /**
862      * A String extra containing the package name of the provisioning initiator.
863      *
864      * <p>Use in an intent with action {@link
865      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}.
866      *
867      * @hide
868      */
869     @SystemApi
870     public static final String EXTRA_ROLE_HOLDER_PROVISIONING_INITIATOR_PACKAGE =
871             "android.app.extra.ROLE_HOLDER_PROVISIONING_INITIATOR_PACKAGE";
872 
873     /**
874      * An {@link Intent} result extra specifying the {@link Intent} to be launched after
875      * provisioning is finalized.
876      *
877      * <p>If {@link #EXTRA_PROVISIONING_SHOULD_LAUNCH_RESULT_INTENT} is set to {@code false},
878      * this result will be supplied as part of the result {@link Intent} for provisioning actions
879      * such as {@link #ACTION_PROVISION_MANAGED_PROFILE}. This result will also be supplied as
880      * part of the result {@link Intent} for the device policy management role holder provisioning
881      * actions.
882      */
883     public static final String EXTRA_RESULT_LAUNCH_INTENT =
884             "android.app.extra.RESULT_LAUNCH_INTENT";
885 
886     /**
887      * A boolean extra that determines whether the provisioning flow should launch the resulting
888      * launch intent, if one is supplied by the device policy management role holder via {@link
889      * #EXTRA_RESULT_LAUNCH_INTENT}. Default value is {@code false}.
890      *
891      * <p>If {@code true}, the resulting intent will be launched by the provisioning flow, if one
892      * is supplied by the device policy management role holder.
893      *
894      * <p>If {@code false}, the resulting intent will be returned as {@link
895      * #EXTRA_RESULT_LAUNCH_INTENT} to the provisioning initiator, if one is supplied by the device
896      * manager role holder. It will be the responsibility of the provisioning initiator to launch
897      * this {@link Intent} after provisioning completes.
898      *
899      * <p>This extra is respected when provided via the provisioning intent actions such as {@link
900      * #ACTION_PROVISION_MANAGED_PROFILE}.
901      */
902     public static final String EXTRA_PROVISIONING_SHOULD_LAUNCH_RESULT_INTENT =
903             "android.app.extra.PROVISIONING_SHOULD_LAUNCH_RESULT_INTENT";
904 
905     /**
906      * Action: Bugreport sharing with device owner has been accepted by the user.
907      *
908      * @hide
909      */
910     public static final String ACTION_BUGREPORT_SHARING_ACCEPTED =
911             "com.android.server.action.REMOTE_BUGREPORT_SHARING_ACCEPTED";
912 
913     /**
914      * Action: Bugreport sharing with device owner has been declined by the user.
915      *
916      * @hide
917      */
918     public static final String ACTION_BUGREPORT_SHARING_DECLINED =
919             "com.android.server.action.REMOTE_BUGREPORT_SHARING_DECLINED";
920 
921     /**
922      * Action: Bugreport has been collected and is dispatched to {@code DevicePolicyManagerService}.
923      *
924      * @hide
925      */
926     public static final String ACTION_REMOTE_BUGREPORT_DISPATCH =
927             "android.intent.action.REMOTE_BUGREPORT_DISPATCH";
928 
929     /**
930      * Extra for shared bugreport's SHA-256 hash.
931      *
932      * @hide
933      */
934     public static final String EXTRA_REMOTE_BUGREPORT_HASH =
935             "android.intent.extra.REMOTE_BUGREPORT_HASH";
936 
937     /**
938      * Extra for shared bugreport's nonce in long integer type.
939      *
940      * @hide
941      */
942     public static final String EXTRA_REMOTE_BUGREPORT_NONCE =
943             "android.intent.extra.REMOTE_BUGREPORT_NONCE";
944 
945     /**
946      * Extra for remote bugreport notification shown type.
947      *
948      * @hide
949      */
950     public static final String EXTRA_BUGREPORT_NOTIFICATION_TYPE =
951             "android.app.extra.bugreport_notification_type";
952 
953     /**
954      * Default value for preferential network service enabling.
955      *
956      * @hide
957      */
958     public static final boolean PREFERENTIAL_NETWORK_SERVICE_ENABLED_DEFAULT = false;
959 
960     /**
961      * Notification type for a started remote bugreport flow.
962      *
963      * @hide
964      */
965     public static final int NOTIFICATION_BUGREPORT_STARTED = 1;
966 
967     /**
968      * Notification type for a bugreport that has already been accepted to be shared, but is still
969      * being taken.
970      *
971      * @hide
972      */
973     public static final int NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED = 2;
974 
975     /**
976      * Notification type for a bugreport that has been taken and can be shared or declined.
977      *
978      * @hide
979      */
980     public static final int NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED = 3;
981 
982     /**
983      * Default and maximum timeout in milliseconds after which unlocking with weak auth times out,
984      * i.e. the user has to use a strong authentication method like password, PIN or pattern.
985      *
986      * @hide
987      */
988     public static final long DEFAULT_STRONG_AUTH_TIMEOUT_MS = 72 * 60 * 60 * 1000; // 72h
989 
990     /**
991      * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that
992      * allows a mobile device management application or NFC programmer application which starts
993      * managed provisioning to pass data to the management application instance after provisioning.
994      * <p>
995      * If used with {@link #ACTION_PROVISION_MANAGED_PROFILE} it can be used by the application that
996      * sends the intent to pass data to itself on the newly created profile.
997      * If used with {@link #ACTION_PROVISION_MANAGED_DEVICE} it allows passing data to the same
998      * instance of the app on the primary user.
999      * Starting from {@link android.os.Build.VERSION_CODES#M}, if used with
1000      * {@link #MIME_TYPE_PROVISIONING_NFC} as part of NFC managed device provisioning, the NFC
1001      * message should contain a stringified {@link java.util.Properties} instance, whose string
1002      * properties will be converted into a {@link android.os.PersistableBundle} and passed to the
1003      * management application after provisioning.
1004      *
1005      * <p>Admin apps will receive this extra in their {@link #ACTION_GET_PROVISIONING_MODE} and
1006      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} intent handlers. Additionally, {@link
1007      * #ACTION_GET_PROVISIONING_MODE} may also return this extra which will then be sent over to
1008      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE}, alongside the original values that were passed to
1009      * {@link #ACTION_GET_PROVISIONING_MODE}.
1010      *
1011      * <p>
1012      * In both cases the application receives the data in
1013      * {@link DeviceAdminReceiver#onProfileProvisioningComplete} via an intent with the action
1014      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}. The bundle is not changed
1015      * during the managed provisioning.
1016      */
1017     public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE =
1018             "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE";
1019 
1020     /**
1021      * A String extra holding the package name of the mobile device management application that
1022      * will be set as the profile owner or device owner.
1023      *
1024      * <p>If an application starts provisioning directly via an intent with action
1025      * {@link #ACTION_PROVISION_MANAGED_PROFILE} this package has to match the package name of the
1026      * application that started provisioning. The package will be set as profile owner in that case.
1027      *
1028      * <p>This package is set as device owner when device owner provisioning is started by an NFC
1029      * message containing an NFC record with MIME type {@link #MIME_TYPE_PROVISIONING_NFC}.
1030      *
1031      * <p> When this extra is set, the application must have exactly one device admin receiver.
1032      * This receiver will be set as the profile or device owner and active admin.
1033      *
1034      * @see DeviceAdminReceiver
1035      * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}. This extra is still
1036      * supported, but only if there is only one device admin receiver in the package that requires
1037      * the permission {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
1038      */
1039     @Deprecated
1040     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME
1041         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME";
1042 
1043     /**
1044      * A ComponentName extra indicating the device admin receiver of the mobile device management
1045      * application that will be set as the profile owner or device owner and active admin.
1046      *
1047      * <p>If an application starts provisioning directly via an intent with action
1048      * {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1049      * {@link #ACTION_PROVISION_MANAGED_DEVICE} the package name of this
1050      * component has to match the package name of the application that started provisioning.
1051      *
1052      * <p>This component is set as device owner and active admin when device owner provisioning is
1053      * started by an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or by an NFC
1054      * message containing an NFC record with MIME type
1055      * {@link #MIME_TYPE_PROVISIONING_NFC}. For the NFC record, the component name must be
1056      * flattened to a string, via {@link ComponentName#flattenToShortString()}.
1057      *
1058      * @see DeviceAdminReceiver
1059      */
1060     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME
1061         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME";
1062 
1063     /**
1064      * An {@link android.accounts.Account} extra holding the account to migrate during managed
1065      * profile provisioning. If the account supplied is present in the primary user, it will be
1066      * copied, along with its credentials to the managed profile and removed from the primary user.
1067      *
1068      * Use with {@link #ACTION_PROVISION_MANAGED_PROFILE}, with managed account provisioning, or
1069      * return as an extra to the intent result from the {@link #ACTION_GET_PROVISIONING_MODE}
1070      * activity.
1071      */
1072 
1073     public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
1074         = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE";
1075 
1076     /**
1077      * Boolean extra to indicate that the migrated account should be kept. This is used in
1078      * conjunction with {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}. If it's set to {@code true},
1079      * the account will not be removed from the primary user after it is migrated to the newly
1080      * created user or profile.
1081      *
1082      * <p> Defaults to {@code false}
1083      *
1084      * <p> Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or set as an extra to the
1085      * intent result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
1086      *
1087      * @see #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
1088      */
1089     public static final String EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION
1090             = "android.app.extra.PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION";
1091 
1092     /**
1093      * @deprecated From {@link android.os.Build.VERSION_CODES#O}, never used while provisioning the
1094      * device.
1095      */
1096     @Deprecated
1097     public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
1098         = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
1099 
1100     /**
1101      * A integer extra indicating the predominant color to show during the provisioning.
1102      * Refer to {@link android.graphics.Color} for how the color is represented.
1103      *
1104      * <p>Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1105      * {@link #ACTION_PROVISION_MANAGED_DEVICE}.
1106      *
1107      * @deprecated Color customization is no longer supported in the provisioning flow.
1108      */
1109     @Deprecated
1110     public static final String EXTRA_PROVISIONING_MAIN_COLOR =
1111              "android.app.extra.PROVISIONING_MAIN_COLOR";
1112 
1113     /**
1114      * A Boolean extra that can be used by the mobile device management application to skip the
1115      * disabling of system apps during provisioning when set to {@code true}.
1116      *
1117      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC}, an intent with action
1118      * {@link #ACTION_PROVISION_MANAGED_PROFILE} that starts profile owner provisioning or
1119      * set as an extra to the intent result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
1120      */
1121     public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED =
1122             "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED";
1123 
1124     /**
1125      * A String extra holding the time zone {@link android.app.AlarmManager} that the device
1126      * will be set to.
1127      *
1128      * <p>Use only for device owner provisioning. This extra can be returned by the admin app when
1129      * performing the admin-integrated provisioning flow as a result of the {@link
1130      * #ACTION_GET_PROVISIONING_MODE} activity.
1131      *
1132      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1133      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1134      */
1135     public static final String EXTRA_PROVISIONING_TIME_ZONE
1136         = "android.app.extra.PROVISIONING_TIME_ZONE";
1137 
1138     /**
1139      * A Long extra holding the wall clock time (in milliseconds) to be set on the device's
1140      * {@link android.app.AlarmManager}.
1141      *
1142      * <p>Use only for device owner provisioning. This extra can be returned by the admin app when
1143      * performing the admin-integrated provisioning flow as a result of the {@link
1144      * #ACTION_GET_PROVISIONING_MODE} activity.
1145      *
1146      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1147      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1148      */
1149     public static final String EXTRA_PROVISIONING_LOCAL_TIME
1150         = "android.app.extra.PROVISIONING_LOCAL_TIME";
1151 
1152     /**
1153      * A String extra holding the {@link java.util.Locale} that the device will be set to.
1154      * Format: xx_yy, where xx is the language code, and yy the country code.
1155      *
1156      * <p>Use only for device owner provisioning. This extra can be returned by the admin app when
1157      * performing the admin-integrated provisioning flow as a result of the {@link
1158      * #ACTION_GET_PROVISIONING_MODE} activity.
1159      *
1160      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1161      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1162      */
1163     public static final String EXTRA_PROVISIONING_LOCALE
1164         = "android.app.extra.PROVISIONING_LOCALE";
1165 
1166     /**
1167      * A String extra holding the ssid of the wifi network that should be used during nfc device
1168      * owner provisioning for downloading the mobile device management application.
1169      *
1170      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1171      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1172      */
1173     public static final String EXTRA_PROVISIONING_WIFI_SSID
1174         = "android.app.extra.PROVISIONING_WIFI_SSID";
1175 
1176     /**
1177      * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
1178      * is hidden or not.
1179      *
1180      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1181      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1182      */
1183     public static final String EXTRA_PROVISIONING_WIFI_HIDDEN
1184         = "android.app.extra.PROVISIONING_WIFI_HIDDEN";
1185 
1186     /**
1187      * A String extra indicating the security type of the wifi network in
1188      * {@link #EXTRA_PROVISIONING_WIFI_SSID} and could be one of {@code NONE}, {@code WPA},
1189      * {@code WEP} or {@code EAP}.
1190      *
1191      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1192      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1193      */
1194     public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE
1195         = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE";
1196 
1197     /**
1198      * A String extra holding the password of the wifi network in
1199      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1200      *
1201      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1202      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1203      */
1204     public static final String EXTRA_PROVISIONING_WIFI_PASSWORD =
1205             "android.app.extra.PROVISIONING_WIFI_PASSWORD";
1206 
1207     /**
1208      * The EAP method of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
1209      * and could be one of {@code PEAP}, {@code TLS}, {@code TTLS}, {@code PWD}, {@code SIM},
1210      * {@code AKA} or {@code AKA_PRIME}. This is only used if the
1211      * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1212      *
1213      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1214      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1215      */
1216     public static final String EXTRA_PROVISIONING_WIFI_EAP_METHOD =
1217             "android.app.extra.PROVISIONING_WIFI_EAP_METHOD";
1218 
1219     /**
1220      * The phase 2 authentication of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
1221      * and could be one of {@code NONE}, {@code PAP}, {@code MSCHAP}, {@code MSCHAPV2}, {@code GTC},
1222      * {@code SIM}, {@code AKA} or {@code AKA_PRIME}. This is only used if the
1223      * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1224      *
1225      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1226      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1227      */
1228     public static final String EXTRA_PROVISIONING_WIFI_PHASE2_AUTH =
1229             "android.app.extra.PROVISIONING_WIFI_PHASE2_AUTH";
1230 
1231     /**
1232      * The CA certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This should
1233      * be an X.509 certificate Base64 encoded DER format, ie. PEM representation of a certificate
1234      * without header, footer and line breaks. <a href=
1235      * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only
1236      * used if the {@link
1237      * #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1238      *
1239      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1240      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1241      */
1242     public static final String EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE =
1243             "android.app.extra.PROVISIONING_WIFI_CA_CERTIFICATE";
1244 
1245     /**
1246      * The user certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This
1247      * should be an X.509 certificate and private key Base64 encoded DER format, ie. PEM
1248      * representation of a certificate and key without header, footer and line breaks. <a href=
1249      * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only
1250      * used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1251      *
1252      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1253      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1254      */
1255     public static final String EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE =
1256             "android.app.extra.PROVISIONING_WIFI_USER_CERTIFICATE";
1257 
1258     /**
1259      * The identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used
1260      * if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1261      *
1262      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1263      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1264      */
1265     public static final String EXTRA_PROVISIONING_WIFI_IDENTITY =
1266             "android.app.extra.PROVISIONING_WIFI_IDENTITY";
1267 
1268     /**
1269      * The anonymous identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is
1270      * only used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1271      *
1272      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1273      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1274      */
1275 
1276     public static final String EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY =
1277             "android.app.extra.PROVISIONING_WIFI_ANONYMOUS_IDENTITY";
1278     /**
1279      * The domain of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used if
1280      * the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1281      *
1282      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1283      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1284      */
1285     public static final String EXTRA_PROVISIONING_WIFI_DOMAIN =
1286             "android.app.extra.PROVISIONING_WIFI_DOMAIN";
1287 
1288     /**
1289      * A String extra holding the proxy host for the wifi network in
1290      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1291      *
1292      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1293      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1294      */
1295     public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST
1296         = "android.app.extra.PROVISIONING_WIFI_PROXY_HOST";
1297 
1298     /**
1299      * An int extra holding the proxy port for the wifi network in
1300      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1301      *
1302      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1303      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1304      */
1305     public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT
1306         = "android.app.extra.PROVISIONING_WIFI_PROXY_PORT";
1307 
1308     /**
1309      * A String extra holding the proxy bypass for the wifi network in
1310      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1311      *
1312      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1313      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1314      */
1315     public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS
1316         = "android.app.extra.PROVISIONING_WIFI_PROXY_BYPASS";
1317 
1318     /**
1319      * A String extra holding the proxy auto-config (PAC) URL for the wifi network in
1320      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1321      *
1322      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1323      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1324      */
1325     public static final String EXTRA_PROVISIONING_WIFI_PAC_URL
1326         = "android.app.extra.PROVISIONING_WIFI_PAC_URL";
1327 
1328     /**
1329      * A String extra holding a url that specifies the download location of the device admin
1330      * package. When not provided it is assumed that the device admin package is already installed.
1331      *
1332      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1333      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1334      */
1335     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION
1336         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION";
1337 
1338     /**
1339      * A String extra holding the localized name of the organization under management.
1340      *
1341      * The name is displayed only during provisioning.
1342      *
1343      * <p>Use in an intent with action {@link #ACTION_PROVISION_FINANCED_DEVICE}
1344      *
1345      * @hide
1346      */
1347     @SystemApi
1348     public static final String EXTRA_PROVISIONING_ORGANIZATION_NAME =
1349             "android.app.extra.PROVISIONING_ORGANIZATION_NAME";
1350 
1351     /**
1352      * A String extra holding a url to the website of the device provider so the user can open it
1353      * during provisioning. If the url is not HTTPS, an error will be shown.
1354      *
1355      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
1356      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
1357      *
1358      * @hide
1359      */
1360     @SystemApi
1361     public static final String EXTRA_PROVISIONING_SUPPORT_URL =
1362             "android.app.extra.PROVISIONING_SUPPORT_URL";
1363 
1364     /**
1365      * A String extra holding the localized name of the device admin package. It should be the same
1366      * as the app label of the package.
1367      *
1368      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
1369      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
1370      *
1371      * @deprecated This extra is no longer respected in the provisioning flow.
1372      * @hide
1373      */
1374     @Deprecated
1375     @SystemApi
1376     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL =
1377             "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL";
1378 
1379     /**
1380      * A {@link Uri} extra pointing to the app icon of device admin package. This image will be
1381      * shown during the provisioning.
1382      * <h5>The following URI schemes are accepted:</h5>
1383      * <ul>
1384      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1385      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1386      * </ul>
1387      *
1388      * <p> It is the responsibility of the caller to provide an image with a reasonable
1389      * pixel density for the device.
1390      *
1391      * <p> If a content: URI is passed, the intent should have the flag
1392      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1393      * {@link android.content.ClipData} of the intent too.
1394      *
1395      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
1396      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
1397      *
1398      * @deprecated This extra is no longer respected in the provisioning flow.
1399      * @hide
1400      */
1401     @SystemApi
1402     @Deprecated
1403     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI =
1404             "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI";
1405 
1406     /**
1407      * An int extra holding a minimum required version code for the device admin package. If the
1408      * device admin is already installed on the device, it will only be re-downloaded from
1409      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION} if the version of the
1410      * installed package is less than this version code.
1411      *
1412      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1413      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1414      */
1415     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE
1416         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE";
1417 
1418     /**
1419      * A String extra holding a http cookie header which should be used in the http request to the
1420      * url specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
1421      *
1422      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1423      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1424      */
1425     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER
1426         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER";
1427 
1428     /**
1429      * A String extra holding the URL-safe base64 encoded SHA-256 hash of the file at download
1430      * location specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
1431      *
1432      * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM} must be
1433      * present. The provided checksum must match the checksum of the file at the download
1434      * location. If the checksum doesn't match an error will be shown to the user and the user will
1435      * be asked to factory reset the device.
1436      *
1437      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1438      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1439      *
1440      * <p><strong>Note:</strong> for devices running {@link android.os.Build.VERSION_CODES#LOLLIPOP}
1441      * and {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} only SHA-1 hash is supported.
1442      * Starting from {@link android.os.Build.VERSION_CODES#M}, this parameter accepts SHA-256 in
1443      * addition to SHA-1. From {@link android.os.Build.VERSION_CODES#Q}, only SHA-256 hash is
1444      * supported.
1445      */
1446     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM
1447         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM";
1448 
1449     /**
1450      * A boolean extra indicating the admin of a fully-managed device opts out of controlling
1451      * permission grants for sensor-related permissions,
1452      * see {@link #setPermissionGrantState(ComponentName, String, String, int)}.
1453      *
1454      * The default for this extra is {@code false} - by default, the admin of a fully-managed
1455      * device has the ability to grant sensors-related permissions.
1456      *
1457      * <p>Use only for device owner provisioning. This extra can be returned by the
1458      * admin app when performing the admin-integrated provisioning flow as a result of the
1459      * {@link #ACTION_GET_PROVISIONING_MODE} activity.
1460      *
1461      * <p>This extra may also be provided to the admin app via an intent extra for {@link
1462      * #ACTION_GET_PROVISIONING_MODE}.
1463      *
1464      * @see #ACTION_GET_PROVISIONING_MODE
1465      */
1466     public static final String EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT =
1467             "android.app.extra.PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT";
1468 
1469     /**
1470      * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
1471      * android package archive at the download location specified in {@link
1472      * #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
1473      *
1474      * <p>The signatures of an android package archive can be obtained using
1475      * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
1476      * {@link android.content.pm.PackageManager#GET_SIGNATURES}.
1477      *
1478      * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM} must be
1479      * present. The provided checksum must match the checksum of any signature of the file at
1480      * the download location. If the checksum does not match an error will be shown to the user and
1481      * the user will be asked to factory reset the device.
1482      *
1483      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1484      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1485      */
1486     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM
1487         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM";
1488 
1489     /**
1490      * Broadcast Action: This broadcast is sent to indicate that provisioning of a managed profile
1491      * has completed successfully.
1492      *
1493      * <p>The broadcast is limited to the primary profile, to the app specified in the provisioning
1494      * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
1495      *
1496      * <p>This intent will contain the following extras
1497      * <ul>
1498      * <li>{@link Intent#EXTRA_USER}, corresponds to the {@link UserHandle} of the managed
1499      * profile.</li>
1500      * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, corresponds to the account requested to
1501      * be migrated at provisioning time, if any.</li>
1502      * </ul>
1503      */
1504     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1505     public static final String ACTION_MANAGED_PROFILE_PROVISIONED
1506         = "android.app.action.MANAGED_PROFILE_PROVISIONED";
1507 
1508     /**
1509      * Activity action: This activity action is sent to indicate that provisioning of a managed
1510      * profile or managed device has completed successfully. It'll be sent at the same time as
1511      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast but this will be
1512      * delivered faster as it's an activity intent.
1513      *
1514      * <p>The intent is only sent to the new device or profile owner.
1515      *
1516      * @see #ACTION_PROVISION_MANAGED_PROFILE
1517      * @see #ACTION_PROVISION_MANAGED_DEVICE
1518      */
1519     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1520     public static final String ACTION_PROVISIONING_SUCCESSFUL =
1521             "android.app.action.PROVISIONING_SUCCESSFUL";
1522 
1523     /**
1524      * A boolean extra indicating whether device encryption can be skipped as part of device owner
1525      * or managed profile provisioning.
1526      *
1527      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
1528      * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
1529      *
1530      * <p>From {@link android.os.Build.VERSION_CODES#N} onwards, this is also supported for an
1531      * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
1532      *
1533      * <p>This extra can also be returned by the admin app when performing the admin-integrated
1534      * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
1535      */
1536     public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION =
1537              "android.app.extra.PROVISIONING_SKIP_ENCRYPTION";
1538 
1539     /**
1540      * A {@link Uri} extra pointing to a logo image. This image will be shown during the
1541      * provisioning. If this extra is not passed, a default image will be shown.
1542      * <h5>The following URI schemes are accepted:</h5>
1543      * <ul>
1544      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1545      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1546      * </ul>
1547      *
1548      * <p> It is the responsibility of the caller to provide an image with a reasonable
1549      * pixel density for the device.
1550      *
1551      * <p> If a content: URI is passed, the intent should have the flag
1552      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1553      * {@link android.content.ClipData} of the intent too.
1554      *
1555      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1556      * {@link #ACTION_PROVISION_MANAGED_DEVICE}
1557      *
1558      * @deprecated Logo customization is no longer supported in the provisioning flow.
1559      */
1560     @Deprecated
1561     public static final String EXTRA_PROVISIONING_LOGO_URI =
1562             "android.app.extra.PROVISIONING_LOGO_URI";
1563 
1564     /**
1565      * A {@link Bundle}[] extra consisting of list of disclaimer headers and disclaimer contents.
1566      * Each {@link Bundle} must have both {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}
1567      * as disclaimer header, and {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} as disclaimer
1568      * content.
1569      *
1570      * <p> The extra typically contains one disclaimer from the company of mobile device
1571      * management application (MDM), and one disclaimer from the organization.
1572      *
1573      * <p> Call {@link Bundle#putParcelableArray(String, Parcelable[])} to put the {@link Bundle}[]
1574      *
1575      * <p> Maximum 3 key-value pairs can be specified. The rest will be ignored.
1576      *
1577      * <p> Can be used in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}. This
1578      * extra can also be returned by the admin app when performing the admin-integrated
1579      * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
1580      */
1581     public static final String EXTRA_PROVISIONING_DISCLAIMERS =
1582             "android.app.extra.PROVISIONING_DISCLAIMERS";
1583 
1584     /**
1585      * A String extra of localized disclaimer header.
1586      *
1587      * <p> The extra is typically the company name of mobile device management application (MDM)
1588      * or the organization name.
1589      *
1590      * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
1591      *
1592      * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
1593      * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
1594      * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT}. Here is the example:
1595      *
1596      * <pre>
1597      *  &lt;meta-data
1598      *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_HEADER"
1599      *      android:resource="@string/disclaimer_header"
1600      * /&gt;</pre>
1601      */
1602     public static final String EXTRA_PROVISIONING_DISCLAIMER_HEADER =
1603             "android.app.extra.PROVISIONING_DISCLAIMER_HEADER";
1604 
1605     /**
1606      * A {@link Uri} extra pointing to disclaimer content.
1607      *
1608      * <h5>The following URI schemes are accepted:</h5>
1609      * <ul>
1610      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1611      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1612      * </ul>
1613      *
1614      * <p> Styled text is supported in the disclaimer content. The content is parsed by
1615      * {@link android.text.Html#fromHtml(String)} and displayed in a
1616      * {@link android.widget.TextView}.
1617      *
1618      * <p> If a <code>content:</code> URI is passed, URI is passed, the intent should have the flag
1619      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1620      * {@link android.content.ClipData} of the intent too.
1621      *
1622      * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
1623      *
1624      * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
1625      * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
1626      * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}. Here is the example:
1627      *
1628      * <pre>
1629      *  &lt;meta-data
1630      *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_CONTENT"
1631      *      android:resource="@string/disclaimer_content"
1632      * /&gt;</pre>
1633      */
1634     public static final String EXTRA_PROVISIONING_DISCLAIMER_CONTENT =
1635             "android.app.extra.PROVISIONING_DISCLAIMER_CONTENT";
1636 
1637     /**
1638      * A boolean extra indicating if the user consent steps from the provisioning flow should be
1639      * skipped. If unspecified, defaults to {@code false}.
1640      *
1641      * It can only be used by an existing device owner trying to create a managed profile via
1642      * {@link #ACTION_PROVISION_MANAGED_PROFILE}. Otherwise it is ignored.
1643      *
1644      * @deprecated this extra is no longer relevant as device owners cannot create managed profiles
1645      */
1646     @Deprecated
1647     public static final String EXTRA_PROVISIONING_SKIP_USER_CONSENT =
1648             "android.app.extra.PROVISIONING_SKIP_USER_CONSENT";
1649 
1650     /**
1651      * A boolean extra indicating if the education screens from the provisioning flow should be
1652      * skipped. If unspecified, defaults to {@code false}.
1653      *
1654      * <p>This extra can be set in the following ways:
1655      * <ul>
1656      * <li>By the admin app when performing the admin-integrated
1657      * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity</li>
1658      * <li>For managed account enrollment</li>
1659      * </ul>
1660      *
1661      * <p>If the education screens are skipped, it is the admin application's responsibility
1662      * to display its own user education screens.
1663      */
1664     public static final String EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS =
1665             "android.app.extra.PROVISIONING_SKIP_EDUCATION_SCREENS";
1666 
1667     /**
1668      * A boolean extra indicating if mobile data should be used during the provisioning flow
1669      * for downloading the admin app. If {@link #EXTRA_PROVISIONING_WIFI_SSID} is also specified,
1670      * wifi network will be used instead.
1671      *
1672      * <p>Default value is {@code false}.
1673      *
1674      * <p>If this extra is set to {@code true} and {@link #EXTRA_PROVISIONING_WIFI_SSID} is not
1675      * specified, this extra has different behaviour depending on the way provisioning is triggered:
1676      * <ul>
1677      * <li>
1678      *     For provisioning started via a QR code or an NFC tag, mobile data is always used for
1679      *     downloading the admin app.
1680      * </li>
1681      * <li>
1682      *     For all other provisioning methods, a mobile data connection check is made at the start
1683      *     of provisioning. If mobile data is connected at that point, the admin app download will
1684      *     happen using mobile data. If mobile data is not connected at that point, the end-user
1685      *     will be asked to pick a wifi network and the admin app download will proceed over wifi.
1686      * </li>
1687      * </ul>
1688      */
1689     public static final String EXTRA_PROVISIONING_USE_MOBILE_DATA =
1690             "android.app.extra.PROVISIONING_USE_MOBILE_DATA";
1691 
1692     /**
1693      * Possible values for {@link #EXTRA_PROVISIONING_TRIGGER}.
1694      *
1695      * @hide
1696      */
1697     @IntDef(prefix = { "PROVISIONING_TRIGGER_" }, value = {
1698             PROVISIONING_TRIGGER_UNSPECIFIED,
1699             PROVISIONING_TRIGGER_CLOUD_ENROLLMENT,
1700             PROVISIONING_TRIGGER_QR_CODE,
1701             PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER,
1702             PROVISIONING_TRIGGER_MANAGED_ACCOUNT,
1703             PROVISIONING_TRIGGER_NFC
1704     })
1705     @Retention(RetentionPolicy.SOURCE)
1706     public @interface ProvisioningTrigger {}
1707 
1708     /**
1709      * Flags for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES}.
1710      *
1711      * @hide
1712      */
1713     @IntDef(flag = true, prefix = { "FLAG_SUPPORTED_MODES_" }, value = {
1714             FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED,
1715             FLAG_SUPPORTED_MODES_PERSONALLY_OWNED,
1716             FLAG_SUPPORTED_MODES_DEVICE_OWNER
1717     })
1718     @Retention(RetentionPolicy.SOURCE)
1719     public @interface ProvisioningConfiguration {}
1720 
1721     /**
1722      * An int extra holding the provisioning trigger. It could be one of
1723      * {@link #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT}, {@link #PROVISIONING_TRIGGER_QR_CODE},
1724      * {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} or {@link
1725      * #PROVISIONING_TRIGGER_UNSPECIFIED}.
1726      *
1727      * <p>Use in an intent with action {@link
1728      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}.
1729      * @hide
1730      */
1731     @SystemApi
1732     public static final String EXTRA_PROVISIONING_TRIGGER =
1733             "android.app.extra.PROVISIONING_TRIGGER";
1734 
1735     /**
1736      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1737      * trigger has not been specified.
1738      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1739      * @see #PROVISIONING_TRIGGER_QR_CODE
1740      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1741      * @see #PROVISIONING_TRIGGER_NFC
1742      * @hide
1743      */
1744     @SystemApi
1745     public static final int PROVISIONING_TRIGGER_UNSPECIFIED = 0;
1746 
1747     /**
1748      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1749      * trigger is cloud enrollment.
1750      * @see #PROVISIONING_TRIGGER_QR_CODE
1751      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1752      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1753      * @see #PROVISIONING_TRIGGER_NFC
1754      * @hide
1755      */
1756     @SystemApi
1757     public static final int PROVISIONING_TRIGGER_CLOUD_ENROLLMENT = 1;
1758 
1759     /**
1760      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1761      * trigger is the QR code scanner.
1762      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1763      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1764      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1765      * @see #PROVISIONING_TRIGGER_NFC
1766      * @hide
1767      */
1768     @SystemApi
1769     public static final int PROVISIONING_TRIGGER_QR_CODE = 2;
1770 
1771     /**
1772      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1773      * trigger is persistent device owner enrollment.
1774      * <p>This constant is meant to represent a specific type of managed account provisioning which
1775      * provisions a device to a device owner by invoking the standard provisioning flow (where
1776      * the ManagedProvisioning component downloads and installs the admin app), as opposed to
1777      * relying on the provisioning trigger to handle download and install of the admin app.
1778      * <p>As of {@link android.os.Build.VERSION_CODES#S}, this constant is no longer used in favor
1779      * of the more general {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} which handles all managed
1780      * account provisioning types.
1781      * @deprecated Use the broader {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} instead
1782      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1783      * @see #PROVISIONING_TRIGGER_QR_CODE
1784      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1785      * @see #PROVISIONING_TRIGGER_NFC
1786      * @hide
1787      */
1788     @SystemApi
1789     @Deprecated
1790     public static final int PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER = 3;
1791 
1792     /**
1793      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1794      * trigger is managed account enrollment.
1795      * <p>
1796      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1797      * @see #PROVISIONING_TRIGGER_QR_CODE
1798      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1799      * @see #PROVISIONING_TRIGGER_NFC
1800      * @hide
1801      */
1802     @SystemApi
1803     public static final int PROVISIONING_TRIGGER_MANAGED_ACCOUNT = 4;
1804 
1805     /**
1806      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning is
1807      * triggered by tapping an NFC tag.
1808      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1809      * @see #PROVISIONING_TRIGGER_QR_CODE
1810      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1811      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1812      * @hide
1813      */
1814     @SystemApi
1815     public static final int PROVISIONING_TRIGGER_NFC = 5;
1816 
1817     /**
1818      * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that provisioning is
1819      * organization-owned.
1820      *
1821      * <p>Using this value indicates the admin app can only be provisioned in either a
1822      * fully-managed device or a corporate-owned work profile. This will cause the admin app's
1823      * {@link #ACTION_GET_PROVISIONING_MODE} activity to have the {@link
1824      * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
1825      * #PROVISIONING_MODE_MANAGED_PROFILE} and {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}.
1826      *
1827      * <p>This flag can be combined with {@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}. In
1828      * that case, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity will have
1829      * the {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
1830      * #PROVISIONING_MODE_MANAGED_PROFILE}, {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE} and
1831      * {@link #PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE}.
1832      *
1833      * @hide
1834      */
1835     @SystemApi
1836     public static final int FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED = 1;
1837 
1838     /**
1839      * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that provisioning
1840      * is personally-owned.
1841      *
1842      * <p>Using this flag will cause the admin app's {@link #ACTION_GET_PROVISIONING_MODE}
1843      * activity to have the {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra
1844      * contain only {@link #PROVISIONING_MODE_MANAGED_PROFILE}.
1845      *
1846      * <p>Also, if this flag is set, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity
1847      * will not receive the {@link #EXTRA_PROVISIONING_IMEI} and {@link
1848      * #EXTRA_PROVISIONING_SERIAL_NUMBER} extras.
1849      *
1850      * <p>This flag can be combined with {@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}. In
1851      * that case, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity will have the
1852      * {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
1853      * #PROVISIONING_MODE_MANAGED_PROFILE}, {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE} and
1854      * {@link #PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE}.
1855      *
1856      * @hide
1857      */
1858     @SystemApi
1859     public static final int FLAG_SUPPORTED_MODES_PERSONALLY_OWNED = 1 << 1;
1860 
1861     /**
1862      * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that the only
1863      * supported provisioning mode is device owner.
1864      *
1865      * @hide
1866      */
1867     @SystemApi
1868     public static final int FLAG_SUPPORTED_MODES_DEVICE_OWNER = 1 << 2;
1869 
1870     /**
1871      * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and
1872      * {@link #setMinimumRequiredWifiSecurityLevel(int)}: no minimum security level.
1873      *
1874      * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant
1875      * represents the current minimum security level required.
1876      * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the
1877      * minimum security level a Wi-Fi network must meet.
1878      *
1879      * @see #WIFI_SECURITY_PERSONAL
1880      * @see #WIFI_SECURITY_ENTERPRISE_EAP
1881      * @see #WIFI_SECURITY_ENTERPRISE_192
1882      */
1883     public static final int WIFI_SECURITY_OPEN = 0;
1884 
1885     /**
1886      * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and
1887      * {@link #setMinimumRequiredWifiSecurityLevel(int)}: personal network such as WEP, WPA2-PSK.
1888      *
1889      * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant
1890      * represents the current minimum security level required.
1891      * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the
1892      * minimum security level a Wi-Fi network must meet.
1893      *
1894      * @see #WIFI_SECURITY_OPEN
1895      * @see #WIFI_SECURITY_ENTERPRISE_EAP
1896      * @see #WIFI_SECURITY_ENTERPRISE_192
1897      */
1898     public static final int WIFI_SECURITY_PERSONAL = 1;
1899 
1900     /**
1901      * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and
1902      * {@link #setMinimumRequiredWifiSecurityLevel(int)}: enterprise EAP network.
1903      *
1904      * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant
1905      * represents the current minimum security level required.
1906      * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the
1907      * minimum security level a Wi-Fi network must meet.
1908      *
1909      * @see #WIFI_SECURITY_OPEN
1910      * @see #WIFI_SECURITY_PERSONAL
1911      * @see #WIFI_SECURITY_ENTERPRISE_192
1912      */
1913     public static final int WIFI_SECURITY_ENTERPRISE_EAP = 2;
1914 
1915     /**
1916      * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and
1917      * {@link #setMinimumRequiredWifiSecurityLevel(int)}: enterprise 192 bit network.
1918      *
1919      * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant
1920      * represents the current minimum security level required.
1921      * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the
1922      * minimum security level a Wi-Fi network must meet.
1923      *
1924      * @see #WIFI_SECURITY_OPEN
1925      * @see #WIFI_SECURITY_PERSONAL
1926      * @see #WIFI_SECURITY_ENTERPRISE_EAP
1927      */
1928     public static final int WIFI_SECURITY_ENTERPRISE_192 = 3;
1929 
1930     /**
1931      * Possible Wi-Fi minimum security levels
1932      *
1933      * @hide */
1934     @Retention(RetentionPolicy.SOURCE)
1935     @IntDef(prefix = {"WIFI_SECURITY_"}, value = {
1936             WIFI_SECURITY_OPEN,
1937             WIFI_SECURITY_PERSONAL,
1938             WIFI_SECURITY_ENTERPRISE_EAP,
1939             WIFI_SECURITY_ENTERPRISE_192})
1940     public @interface WifiSecurity {}
1941 
1942     /**
1943      * This MIME type is used for starting the device owner provisioning.
1944      *
1945      * <p>During device owner provisioning a device admin app is set as the owner of the device.
1946      * A device owner has full control over the device. The device owner can not be modified by the
1947      * user and the only way of resetting the device is if the device owner app calls a factory
1948      * reset.
1949      *
1950      * <p> A typical use case would be a device that is owned by a company, but used by either an
1951      * employee or client.
1952      *
1953      * <p> The NFC message must be sent to an unprovisioned device.
1954      *
1955      * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
1956      * contains the following properties:
1957      * <ul>
1958      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
1959      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
1960      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
1961      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
1962      * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
1963      * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
1964      * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
1965      * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
1966      * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
1967      * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
1968      * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
1969      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
1970      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
1971      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
1972      * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
1973      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional, supported from {@link
1974      * android.os.Build.VERSION_CODES#M} </li>
1975      * <li>{@link #EXTRA_PROVISIONING_WIFI_EAP_METHOD}, optional, supported from {@link
1976      * android.os.Build.VERSION_CODES#Q}</li>
1977      * <li>{@link #EXTRA_PROVISIONING_WIFI_PHASE2_AUTH}, optional, supported from {@link
1978      * android.os.Build.VERSION_CODES#Q}</li>
1979      * <li>{@link #EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE}, optional, supported from {@link
1980      * android.os.Build.VERSION_CODES#Q}</li>
1981      * <li>{@link #EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE}, optional, supported from {@link
1982      * android.os.Build.VERSION_CODES#Q}</li>
1983      * <li>{@link #EXTRA_PROVISIONING_WIFI_IDENTITY}, optional, supported from {@link
1984      * android.os.Build.VERSION_CODES#Q}</li>
1985      * <li>{@link #EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY}, optional, supported from {@link
1986      * android.os.Build.VERSION_CODES#Q}</li>
1987      * <li>{@link #EXTRA_PROVISIONING_WIFI_DOMAIN}, optional, supported from {@link
1988      * android.os.Build.VERSION_CODES#Q}</li></ul>
1989      *
1990      * <p>
1991      * As of {@link android.os.Build.VERSION_CODES#M}, the properties should contain
1992      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of
1993      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only
1994      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported).
1995      */
1996     public static final String MIME_TYPE_PROVISIONING_NFC
1997         = "application/com.android.managedprovisioning";
1998 
1999     /**
2000      * Activity action: ask the user to add a new device administrator to the system.
2001      * The desired policy is the ComponentName of the policy in the
2002      * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
2003      * bring the user through adding the device administrator to the system (or
2004      * allowing them to reject it).
2005      *
2006      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
2007      * field to provide the user with additional explanation (in addition
2008      * to your component's description) about what is being added.
2009      *
2010      * <p>If your administrator is already active, this will ordinarily return immediately (without
2011      * user intervention).  However, if your administrator has been updated and is requesting
2012      * additional uses-policy flags, the user will be presented with the new list.  New policies
2013      * will not be available to the updated administrator until the user has accepted the new list.
2014      */
2015     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
2016     public static final String ACTION_ADD_DEVICE_ADMIN
2017             = "android.app.action.ADD_DEVICE_ADMIN";
2018 
2019     /**
2020      * @hide
2021      * Activity action: ask the user to add a new device administrator as the profile owner
2022      * for this user. Only system apps can launch this intent.
2023      *
2024      * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN}
2025      * extra field. This will invoke a UI to bring the user through adding the profile owner admin
2026      * to remotely control restrictions on the user.
2027      *
2028      * <p>The intent must be invoked via {@link Activity#startActivityForResult} to receive the
2029      * result of whether or not the user approved the action. If approved, the result will
2030      * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well
2031      * as a profile owner.
2032      *
2033      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
2034      * field to provide the user with additional explanation (in addition
2035      * to your component's description) about what is being added.
2036      *
2037      * <p>If there is already a profile owner active or the caller is not a system app, the
2038      * operation will return a failure result.
2039      */
2040     @SystemApi
2041     public static final String ACTION_SET_PROFILE_OWNER
2042             = "android.app.action.SET_PROFILE_OWNER";
2043 
2044     /**
2045      * @hide
2046      * Name of the profile owner admin that controls the user.
2047      */
2048     @SystemApi
2049     public static final String EXTRA_PROFILE_OWNER_NAME
2050             = "android.app.extra.PROFILE_OWNER_NAME";
2051 
2052     /**
2053      * Broadcast action: send when any policy admin changes a policy.
2054      * This is generally used to find out when a new policy is in effect.
2055      *
2056      * If the profile owner of an organization-owned managed profile changes some user
2057      * restriction explicitly on the parent user, this broadcast will <em>not</em> be
2058      * sent to the parent user.
2059      * @hide
2060      */
2061     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2062     public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
2063             = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
2064 
2065     /**
2066      * Broadcast action: sent when the device owner is set, changed or cleared.
2067      *
2068      * This broadcast is sent only to the primary user.
2069      * @see #ACTION_PROVISION_MANAGED_DEVICE
2070      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
2071      */
2072     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2073     public static final String ACTION_DEVICE_OWNER_CHANGED
2074             = "android.app.action.DEVICE_OWNER_CHANGED";
2075 
2076     /**
2077      * Broadcast action: sent when the factory reset protection (FRP) policy is changed.
2078      *
2079      * @see #setFactoryResetProtectionPolicy
2080      * @hide
2081      */
2082     @RequiresPermission(android.Manifest.permission.MANAGE_FACTORY_RESET_PROTECTION)
2083     @SystemApi
2084     public static final String ACTION_RESET_PROTECTION_POLICY_CHANGED =
2085             "android.app.action.RESET_PROTECTION_POLICY_CHANGED";
2086 
2087     /**
2088      * Broadcast action: sent when there is a location update on a device in lost mode. This
2089      * broadcast is explicitly sent to the device policy controller app only.
2090      *
2091      * @see DevicePolicyManager#sendLostModeLocationUpdate
2092      * @hide
2093      */
2094     @SystemApi
2095     public static final String ACTION_LOST_MODE_LOCATION_UPDATE =
2096             "android.app.action.LOST_MODE_LOCATION_UPDATE";
2097 
2098     /**
2099      * Extra used with {@link #ACTION_LOST_MODE_LOCATION_UPDATE} to send the location of a device
2100      * in lost mode. Value is {@code Location}.
2101      *
2102      * @see DevicePolicyManager#sendLostModeLocationUpdate
2103      * @hide
2104      */
2105     @SystemApi
2106     public static final String EXTRA_LOST_MODE_LOCATION =
2107             "android.app.extra.LOST_MODE_LOCATION";
2108 
2109     /**
2110      * The ComponentName of the administrator component.
2111      *
2112      * @see #ACTION_ADD_DEVICE_ADMIN
2113      */
2114     public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
2115 
2116     /**
2117      * An optional CharSequence providing additional explanation for why the
2118      * admin is being added.
2119      *
2120      * @see #ACTION_ADD_DEVICE_ADMIN
2121      */
2122     public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
2123 
2124     /**
2125      * Constant to indicate the feature of disabling the camera. Used as argument to
2126      * {@link #createAdminSupportIntent(String)}.
2127      * @see #setCameraDisabled(ComponentName, boolean)
2128      */
2129     public static final String POLICY_DISABLE_CAMERA = "policy_disable_camera";
2130 
2131     /**
2132      * Constant to indicate the feature of disabling screen captures. Used as argument to
2133      * {@link #createAdminSupportIntent(String)}.
2134      * @see #setScreenCaptureDisabled(ComponentName, boolean)
2135      */
2136     public static final String POLICY_DISABLE_SCREEN_CAPTURE = "policy_disable_screen_capture";
2137 
2138     /**
2139      * Constant to indicate the feature of suspending app. Use it as the value of
2140      * {@link #EXTRA_RESTRICTION}.
2141      * @hide
2142      */
2143     public static final String POLICY_SUSPEND_PACKAGES = "policy_suspend_packages";
2144 
2145     /**
2146      * A String indicating a specific restricted feature. Can be a user restriction from the
2147      * {@link UserManager}, e.g. {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the values
2148      * {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
2149      * @see #createAdminSupportIntent(String)
2150      * @hide
2151      */
2152     @SystemApi
2153     public static final String EXTRA_RESTRICTION = "android.app.extra.RESTRICTION";
2154 
2155     /**
2156      * Activity action: have the user enter a new password.
2157      *
2158      * <p>For admin apps, this activity should be launched after using {@link
2159      * #setPasswordQuality(ComponentName, int)}, or {@link
2160      * #setPasswordMinimumLength(ComponentName, int)} to have the user enter a new password that
2161      * meets the current requirements. You can use {@link #isActivePasswordSufficient()} to
2162      * determine whether you need to have the user select a new password in order to meet the
2163      * current constraints. Upon being resumed from this activity, you can check the new
2164      * password characteristics to see if they are sufficient.
2165      *
2166      * <p>Non-admin apps can use {@link #getPasswordComplexity()} to check the current screen lock
2167      * complexity, and use this activity with extra {@link #EXTRA_PASSWORD_COMPLEXITY} to suggest
2168      * to users how complex the app wants the new screen lock to be. Note that both {@link
2169      * #getPasswordComplexity()} and the extra {@link #EXTRA_PASSWORD_COMPLEXITY} require the
2170      * calling app to have the permission {@link permission#REQUEST_PASSWORD_COMPLEXITY}.
2171      *
2172      * <p>If the intent is launched from within a managed profile with a profile
2173      * owner built against {@link android.os.Build.VERSION_CODES#M} or before,
2174      * this will trigger entering a new password for the parent of the profile.
2175      * For all other cases it will trigger entering a new password for the user
2176      * or profile it is launched from.
2177      *
2178      * @see #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
2179      */
2180     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
2181     public static final String ACTION_SET_NEW_PASSWORD
2182             = "android.app.action.SET_NEW_PASSWORD";
2183 
2184     /**
2185      * An integer indicating the complexity level of the new password an app would like the user to
2186      * set when launching the action {@link #ACTION_SET_NEW_PASSWORD}.
2187      *
2188      * <p>Must be one of
2189      * <ul>
2190      *     <li>{@link #PASSWORD_COMPLEXITY_HIGH}
2191      *     <li>{@link #PASSWORD_COMPLEXITY_MEDIUM}
2192      *     <li>{@link #PASSWORD_COMPLEXITY_LOW}
2193      *     <li>{@link #PASSWORD_COMPLEXITY_NONE}
2194      * </ul>
2195      *
2196      * <p>If an invalid value is used, it will be treated as {@link #PASSWORD_COMPLEXITY_NONE}.
2197      */
2198     @RequiresPermission(android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY)
2199     public static final String EXTRA_PASSWORD_COMPLEXITY =
2200             "android.app.extra.PASSWORD_COMPLEXITY";
2201 
2202     /**
2203      * Constant for {@link #getPasswordComplexity()} and
2204      * {@link #setRequiredPasswordComplexity(int)}: no password.
2205      *
2206      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
2207      * the exact complexity band the password is in.
2208      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
2209      * band which the password must meet.
2210      */
2211     public static final int PASSWORD_COMPLEXITY_NONE = 0;
2212 
2213     /**
2214      * Constant for {@link #getPasswordComplexity()} and
2215      * {@link #setRequiredPasswordComplexity(int)}.
2216      * Define the low password complexity band as:
2217      * <ul>
2218      * <li>pattern
2219      * <li>PIN with repeating (4444) or ordered (1234, 4321, 2468) sequences
2220      * </ul>
2221      *
2222      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
2223      * the exact complexity band the password is in.
2224      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
2225      * band which the password must meet.
2226      *
2227      * @see #PASSWORD_QUALITY_SOMETHING
2228      * @see #PASSWORD_QUALITY_NUMERIC
2229      */
2230     public static final int PASSWORD_COMPLEXITY_LOW = 0x10000;
2231 
2232     /**
2233      * Constant for {@link #getPasswordComplexity()} and
2234      * {@link #setRequiredPasswordComplexity(int)}.
2235      * Define the medium password complexity band as:
2236      * <ul>
2237      * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
2238      * least 4
2239      * <li>alphabetic, length at least 4
2240      * <li>alphanumeric, length at least 4
2241      * </ul>
2242      *
2243      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
2244      * the exact complexity band the password is in.
2245      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
2246      * band which the password must meet.
2247      *
2248      * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX
2249      * @see #PASSWORD_QUALITY_ALPHABETIC
2250      * @see #PASSWORD_QUALITY_ALPHANUMERIC
2251      */
2252     public static final int PASSWORD_COMPLEXITY_MEDIUM = 0x30000;
2253 
2254     /**
2255      * Constant for {@link #getPasswordComplexity()} and
2256      * {@link #setRequiredPasswordComplexity(int)}.
2257      * Define the high password complexity band as:
2258      * <ul>
2259      * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
2260      * least 8
2261      * <li>alphabetic, length at least 6
2262      * <li>alphanumeric, length at least 6
2263      * </ul>
2264      *
2265      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
2266      * the exact complexity band the password is in.
2267      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
2268      * band which the password must meet.
2269      *
2270      * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX
2271      * @see #PASSWORD_QUALITY_ALPHABETIC
2272      * @see #PASSWORD_QUALITY_ALPHANUMERIC
2273      */
2274     public static final int PASSWORD_COMPLEXITY_HIGH = 0x50000;
2275 
2276     /**
2277      * A boolean extra for {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} requesting that only
2278      * device password requirement is enforced during the parent profile password enrolment flow.
2279      * <p> Normally when enrolling password for the parent profile, both the device-wide password
2280      * requirement (requirement set via {@link #getParentProfileInstance(ComponentName)} instance)
2281      * and the profile password requirement are enforced, if the profile currently does not have a
2282      * separate work challenge. By setting this to {@code true}, profile password requirement is
2283      * explicitly disregarded.
2284      *
2285      * @see #isActivePasswordSufficientForDeviceRequirement()
2286      */
2287     public static final String EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY =
2288             "android.app.extra.DEVICE_PASSWORD_REQUIREMENT_ONLY";
2289 
2290     /**
2291      * @hide
2292      */
2293     @Retention(RetentionPolicy.SOURCE)
2294     @IntDef(prefix = {"PASSWORD_COMPLEXITY_"}, value = {
2295             PASSWORD_COMPLEXITY_NONE,
2296             PASSWORD_COMPLEXITY_LOW,
2297             PASSWORD_COMPLEXITY_MEDIUM,
2298             PASSWORD_COMPLEXITY_HIGH,
2299     })
2300     public @interface PasswordComplexity {}
2301 
2302     /**
2303      * Indicates that nearby streaming is not controlled by policy, which means nearby streaming is
2304      * allowed.
2305      */
2306     public static final int NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY = 0;
2307 
2308     /** Indicates that nearby streaming is disabled. */
2309     public static final int NEARBY_STREAMING_DISABLED = 1;
2310 
2311     /** Indicates that nearby streaming is enabled. */
2312     public static final int NEARBY_STREAMING_ENABLED = 2;
2313 
2314     /**
2315      * Indicates that nearby streaming is enabled only to devices offering a comparable level of
2316      * security, with the same authenticated managed account.
2317      */
2318     public static final int NEARBY_STREAMING_SAME_MANAGED_ACCOUNT_ONLY = 3;
2319 
2320     /**
2321      * @hide
2322      */
2323     @Retention(RetentionPolicy.SOURCE)
2324     @IntDef(prefix = {"NEARBY_STREAMING_"}, value = {
2325         NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY,
2326         NEARBY_STREAMING_DISABLED,
2327         NEARBY_STREAMING_ENABLED,
2328         NEARBY_STREAMING_SAME_MANAGED_ACCOUNT_ONLY,
2329     })
2330     public @interface NearbyStreamingPolicy {}
2331 
2332     /**
2333      * Activity action: have the user enter a new password for the parent profile.
2334      * If the intent is launched from within a managed profile, this will trigger
2335      * entering a new password for the parent of the profile. The caller can optionally
2336      * set {@link #EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY} to only enforce device-wide
2337      * password requirement. In all other cases the behaviour is identical to
2338      * {@link #ACTION_SET_NEW_PASSWORD}.
2339      */
2340     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
2341     public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
2342             = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD";
2343 
2344     /**
2345      * Broadcast action: Tell the status bar to open the device monitoring dialog, e.g. when
2346      * Network logging was enabled and the user tapped the notification.
2347      * <p class="note">This is a protected intent that can only be sent by the system.</p>
2348      * @hide
2349      */
2350     public static final String ACTION_SHOW_DEVICE_MONITORING_DIALOG
2351             = "android.app.action.SHOW_DEVICE_MONITORING_DIALOG";
2352 
2353     /**
2354      * Broadcast Action: Sent after application delegation scopes are changed. The new delegation
2355      * scopes will be sent in an {@code ArrayList<String>} extra identified by the
2356      * {@link #EXTRA_DELEGATION_SCOPES} key.
2357      *
2358      * <p class="note"><b>Note:</b> This is a protected intent that can only be sent by the
2359      * system.</p>
2360      */
2361     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2362     public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED =
2363             "android.app.action.APPLICATION_DELEGATION_SCOPES_CHANGED";
2364 
2365     /**
2366      * An {@code ArrayList<String>} corresponding to the delegation scopes given to an app in the
2367      * {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} broadcast.
2368      */
2369     public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES";
2370 
2371     /**
2372      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
2373      * the parent profile to access intents sent from the managed profile.
2374      * That is, when an app in the managed profile calls
2375      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
2376      * matching activity in the parent profile.
2377      */
2378     public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
2379 
2380     /**
2381      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
2382      * the managed profile to access intents sent from the parent profile.
2383      * That is, when an app in the parent profile calls
2384      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
2385      * matching activity in the managed profile.
2386      */
2387     public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
2388 
2389     /**
2390      * Broadcast action: notify that a new local system update policy has been set by the device
2391      * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
2392      */
2393     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2394     public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
2395             = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
2396 
2397     /**
2398      * Broadcast action from ManagedProvisioning to notify that the latest change to
2399      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has been successfully
2400      * applied (cross profile intent filters updated). Only usesd for CTS tests.
2401      * @hide
2402      */
2403     @TestApi
2404     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2405     public static final String ACTION_DATA_SHARING_RESTRICTION_APPLIED =
2406             "android.app.action.DATA_SHARING_RESTRICTION_APPLIED";
2407 
2408     /**
2409      * Broadcast action: notify that a value of {@link Settings.Global#DEVICE_POLICY_CONSTANTS}
2410      * has been changed.
2411      * @hide
2412      */
2413     @TestApi
2414     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2415     public static final String ACTION_DEVICE_POLICY_CONSTANTS_CHANGED =
2416             "android.app.action.DEVICE_POLICY_CONSTANTS_CHANGED";
2417 
2418     /**
2419      * Permission policy to prompt user for new permission requests for runtime permissions.
2420      * Already granted or denied permissions are not affected by this.
2421      */
2422     public static final int PERMISSION_POLICY_PROMPT = 0;
2423 
2424     /**
2425      * Permission policy to always grant new permission requests for runtime permissions.
2426      * Already granted or denied permissions are not affected by this.
2427      */
2428     public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
2429 
2430     /**
2431      * Permission policy to always deny new permission requests for runtime permissions.
2432      * Already granted or denied permissions are not affected by this.
2433      */
2434     public static final int PERMISSION_POLICY_AUTO_DENY = 2;
2435 
2436     /**
2437      * Possible policy values for permissions.
2438      *
2439      * @hide
2440      */
2441     @IntDef(prefix = { "PERMISSION_GRANT_STATE_" }, value = {
2442             PERMISSION_GRANT_STATE_DEFAULT,
2443             PERMISSION_GRANT_STATE_GRANTED,
2444             PERMISSION_GRANT_STATE_DENIED
2445     })
2446     @Retention(RetentionPolicy.SOURCE)
2447     public @interface PermissionGrantState {}
2448 
2449     /**
2450      * Runtime permission state: The user can manage the permission
2451      * through the UI.
2452      */
2453     public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
2454 
2455     /**
2456      * Runtime permission state: The permission is granted to the app
2457      * and the user cannot manage the permission through the UI.
2458      */
2459     public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
2460 
2461     /**
2462      * Runtime permission state: The permission is denied to the app
2463      * and the user cannot manage the permission through the UI.
2464      */
2465     public static final int PERMISSION_GRANT_STATE_DENIED = 2;
2466 
2467     /**
2468      * Delegation of certificate installation and management. This scope grants access to the
2469      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
2470      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair} APIs.
2471      * This scope also grants the ability to read identifiers that the delegating device owner or
2472      * profile owner can obtain. See {@link #getEnrollmentSpecificId()}.
2473      */
2474     public static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
2475 
2476     /**
2477      * Delegation of application restrictions management. This scope grants access to the
2478      * {@link #setApplicationRestrictions} and {@link #getApplicationRestrictions} APIs.
2479      */
2480     public static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions";
2481 
2482     /**
2483      * Delegation of application uninstall block. This scope grants access to the
2484      * {@link #setUninstallBlocked} API.
2485      */
2486     public static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall";
2487 
2488     /**
2489      * Delegation of permission policy and permission grant state. This scope grants access to the
2490      * {@link #setPermissionPolicy}, {@link #getPermissionGrantState},
2491      * and {@link #setPermissionGrantState} APIs.
2492      */
2493     public static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant";
2494 
2495     /**
2496      * Delegation of package access state. This scope grants access to the
2497      * {@link #isApplicationHidden}, {@link #setApplicationHidden}, {@link #isPackageSuspended}, and
2498      * {@link #setPackagesSuspended} APIs.
2499      */
2500     public static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
2501 
2502     /**
2503      * Delegation for enabling system apps. This scope grants access to the {@link #enableSystemApp}
2504      * API.
2505      */
2506     public static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app";
2507 
2508     /**
2509      * Delegation for installing existing packages. This scope grants access to the
2510      * {@link #installExistingPackage} API.
2511      */
2512     public static final String DELEGATION_INSTALL_EXISTING_PACKAGE =
2513             "delegation-install-existing-package";
2514 
2515     /**
2516      * Delegation of management of uninstalled packages. This scope grants access to the
2517      * {@link #setKeepUninstalledPackages} and {@link #getKeepUninstalledPackages} APIs.
2518      */
2519     public static final String DELEGATION_KEEP_UNINSTALLED_PACKAGES =
2520             "delegation-keep-uninstalled-packages";
2521 
2522     /**
2523      * Grants access to {@link #setNetworkLoggingEnabled}, {@link #isNetworkLoggingEnabled} and
2524      * {@link #retrieveNetworkLogs}. Once granted the delegated app will start receiving
2525      * DelegatedAdminReceiver.onNetworkLogsAvailable() callback, and Device owner or Profile Owner
2526      * will no longer receive the DeviceAdminReceiver.onNetworkLogsAvailable() callback.
2527      * There can be at most one app that has this delegation.
2528      * If another app already had delegated network logging access,
2529      * it will lose the delegation when a new app is delegated.
2530      *
2531      * <p> Device Owner can grant this access since Android 10. Profile Owner of a managed profile
2532      * can grant this access since Android 12.
2533      */
2534     public static final String DELEGATION_NETWORK_LOGGING = "delegation-network-logging";
2535 
2536     /**
2537      * Grants access to selection of KeyChain certificates on behalf of requesting apps.
2538      * Once granted the app will start receiving
2539      * {@link DelegatedAdminReceiver#onChoosePrivateKeyAlias}. The caller (PO/DO) will
2540      * no longer receive {@link DeviceAdminReceiver#onChoosePrivateKeyAlias}.
2541      * There can be at most one app that has this delegation.
2542      * If another app already had delegated certificate selection access,
2543      * it will lose the delegation when a new app is delegated.
2544      * <p> The delegaetd app can also call {@link #grantKeyPairToApp} and
2545      * {@link #revokeKeyPairFromApp} to directly grant KeyCain keys to other apps.
2546      * <p> Can be granted by Device Owner or Profile Owner.
2547      */
2548     public static final String DELEGATION_CERT_SELECTION = "delegation-cert-selection";
2549 
2550     /**
2551      * Grants access to {@link #setSecurityLoggingEnabled}, {@link #isSecurityLoggingEnabled},
2552      * {@link #retrieveSecurityLogs}, and {@link #retrievePreRebootSecurityLogs}. Once granted the
2553      * delegated app will start receiving {@link DelegatedAdminReceiver#onSecurityLogsAvailable}
2554      * callback, and Device owner or Profile Owner will no longer receive the
2555      * {@link DeviceAdminReceiver#onSecurityLogsAvailable} callback. There can be at most one app
2556      * that has this delegation. If another app already had delegated security logging access, it
2557      * will lose the delegation when a new app is delegated.
2558      *
2559      * <p> Can only be granted by Device Owner or Profile Owner of an organization-owned
2560      * managed profile.
2561      */
2562     public static final String DELEGATION_SECURITY_LOGGING = "delegation-security-logging";
2563 
2564     /**
2565      * No management for current user in-effect. This is the default.
2566      * @hide
2567      */
2568     @SystemApi
2569     public static final int STATE_USER_UNMANAGED = 0;
2570 
2571     /**
2572      * Management partially setup, user setup needs to be completed.
2573      * @hide
2574      */
2575     @SystemApi
2576     public static final int STATE_USER_SETUP_INCOMPLETE = 1;
2577 
2578     /**
2579      * Management partially setup, user setup completed.
2580      * @hide
2581      */
2582     @SystemApi
2583     public static final int STATE_USER_SETUP_COMPLETE = 2;
2584 
2585     /**
2586      * Management setup and active on current user.
2587      * @hide
2588      */
2589     @SystemApi
2590     public static final int STATE_USER_SETUP_FINALIZED = 3;
2591 
2592     /**
2593      * Management partially setup on a managed profile.
2594      * @hide
2595      */
2596     @SystemApi
2597     public static final int STATE_USER_PROFILE_COMPLETE = 4;
2598 
2599     /**
2600      * Management setup on a managed profile.
2601      * <p>This is used as an intermediate state after {@link #STATE_USER_PROFILE_COMPLETE} once the
2602      * work profile has been created.
2603      * @hide
2604      */
2605     @SystemApi
2606     public static final int STATE_USER_PROFILE_FINALIZED = 5;
2607 
2608     /**
2609      * @hide
2610      */
2611     @IntDef(prefix = { "STATE_USER_" }, value = {
2612             STATE_USER_UNMANAGED,
2613             STATE_USER_SETUP_INCOMPLETE,
2614             STATE_USER_SETUP_COMPLETE,
2615             STATE_USER_SETUP_FINALIZED,
2616             STATE_USER_PROFILE_COMPLETE,
2617             STATE_USER_PROFILE_FINALIZED
2618     })
2619     @Retention(RetentionPolicy.SOURCE)
2620     public @interface UserProvisioningState {}
2621 
2622     /**
2623      * Result code for {@link #checkProvisioningPrecondition}.
2624      *
2625      * <p>Unknown error code returned  for {@link #ACTION_PROVISION_MANAGED_DEVICE},
2626      * {@link #ACTION_PROVISION_MANAGED_PROFILE} and {@link #ACTION_PROVISION_MANAGED_USER}.
2627      *
2628      * @hide
2629      */
2630     @SystemApi
2631     public static final int STATUS_UNKNOWN_ERROR = -1;
2632 
2633     /**
2634      * Result code for {@link #checkProvisioningPrecondition}.
2635      *
2636      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
2637      * {@link #ACTION_PROVISION_MANAGED_PROFILE} and {@link #ACTION_PROVISION_MANAGED_USER}
2638      * when provisioning is allowed.
2639      *
2640      * @hide
2641      */
2642     @SystemApi
2643     public static final int STATUS_OK = 0;
2644 
2645     /**
2646      * Result code for {@link #checkProvisioningPrecondition}.
2647      *
2648      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the device already has a
2649      * device owner.
2650      *
2651      * @hide
2652      */
2653     @SystemApi
2654     public static final int STATUS_HAS_DEVICE_OWNER = 1;
2655 
2656     /**
2657      * Result code for {@link #checkProvisioningPrecondition}.
2658      *
2659      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the user has a profile owner
2660      *  and for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the profile owner is already set.
2661      *
2662      * @hide
2663      */
2664     @SystemApi
2665     public static final int STATUS_USER_HAS_PROFILE_OWNER = 2;
2666 
2667     /**
2668      * Result code for {@link #checkProvisioningPrecondition}.
2669      *
2670      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the user isn't running.
2671      *
2672      * @hide
2673      */
2674     @SystemApi
2675     public static final int STATUS_USER_NOT_RUNNING = 3;
2676 
2677     /**
2678      * Result code for {@link #checkProvisioningPrecondition}.
2679      *
2680      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} if the device has already been
2681      * setup and for {@link #ACTION_PROVISION_MANAGED_USER} if the user has already been setup.
2682      *
2683      * @hide
2684      */
2685     @SystemApi
2686     public static final int STATUS_USER_SETUP_COMPLETED = 4;
2687 
2688     /**
2689      * Code used to indicate that the device also has a user other than the system user.
2690      *
2691      * @hide
2692      */
2693     @SystemApi
2694     public static final int STATUS_NONSYSTEM_USER_EXISTS = 5;
2695 
2696     /**
2697      * Code used to indicate that device has an account that prevents provisioning.
2698      *
2699      * @hide
2700      */
2701     @SystemApi
2702     public static final int STATUS_ACCOUNTS_NOT_EMPTY = 6;
2703 
2704     /**
2705      * Result code for {@link #checkProvisioningPrecondition}.
2706      *
2707      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} if the user is not a system user.
2708      *
2709      * @hide
2710      */
2711     @SystemApi
2712     public static final int STATUS_NOT_SYSTEM_USER = 7;
2713 
2714     /**
2715      * Result code for {@link #checkProvisioningPrecondition}.
2716      *
2717      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
2718      * {@link #ACTION_PROVISION_MANAGED_USER} when the device is a watch and is already paired.
2719      *
2720      * @hide
2721      */
2722     @SystemApi
2723     public static final int STATUS_HAS_PAIRED = 8;
2724 
2725     /**
2726      * Result code for {@link #checkProvisioningPrecondition}.
2727      *
2728      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} and
2729      * {@link #ACTION_PROVISION_MANAGED_USER} on devices which do not support managed users.
2730      *
2731      * @see {@link PackageManager#FEATURE_MANAGED_USERS}
2732      * @hide
2733      */
2734     @SystemApi
2735     public static final int STATUS_MANAGED_USERS_NOT_SUPPORTED = 9;
2736 
2737     /**
2738      * Result code for {@link #checkProvisioningPrecondition}.
2739      *
2740      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} if the user is a system user and
2741      * for {@link #ACTION_PROVISION_MANAGED_DEVICE} on devices running headless system user mode
2742      * and the user is a system user.
2743      *
2744      * @hide
2745      */
2746     @SystemApi
2747     public static final int STATUS_SYSTEM_USER = 10;
2748 
2749     /**
2750      * Result code for {@link #checkProvisioningPrecondition}.
2751      *
2752      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the user cannot have more
2753      * managed profiles.
2754      *
2755      * @hide
2756      */
2757     @SystemApi
2758     public static final int STATUS_CANNOT_ADD_MANAGED_PROFILE = 11;
2759 
2760     /**
2761      * Result code for {@link #checkProvisioningPrecondition}.
2762      *
2763      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
2764      * {@link #ACTION_PROVISION_MANAGED_PROFILE} on devices which do not support device
2765      * admins.
2766      *
2767      * @hide
2768      */
2769     @SystemApi
2770     public static final int STATUS_DEVICE_ADMIN_NOT_SUPPORTED = 13;
2771 
2772     /**
2773      * TODO (b/137101239): clean up split system user codes
2774      * Result code for {@link #checkProvisioningPrecondition}.
2775      *
2776      * @hide
2777      * @deprecated not used anymore but can't be removed since it's a @TestApi.
2778      */
2779     @Deprecated
2780     @TestApi
2781     public static final int STATUS_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER = 14;
2782 
2783     /**
2784      * Result code for {@link #checkProvisioningPrecondition}.
2785      *
2786      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
2787      * {@link #ACTION_PROVISION_MANAGED_PROFILE} on devices which do not support provisioning.
2788      *
2789      * @hide
2790      */
2791     @SystemApi
2792     public static final int STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS = 15;
2793 
2794     /**
2795      * Result codes for {@link #checkProvisioningPrecondition} indicating all the provisioning pre
2796      * conditions.
2797      *
2798      * @hide
2799      */
2800     @Retention(RetentionPolicy.SOURCE)
2801     @IntDef(prefix = { "STATUS_" }, value = {
2802             STATUS_UNKNOWN_ERROR, STATUS_OK, STATUS_HAS_DEVICE_OWNER, STATUS_USER_HAS_PROFILE_OWNER,
2803             STATUS_USER_NOT_RUNNING, STATUS_USER_SETUP_COMPLETED, STATUS_NOT_SYSTEM_USER,
2804             STATUS_HAS_PAIRED, STATUS_MANAGED_USERS_NOT_SUPPORTED, STATUS_SYSTEM_USER,
2805             STATUS_CANNOT_ADD_MANAGED_PROFILE, STATUS_DEVICE_ADMIN_NOT_SUPPORTED,
2806             STATUS_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER,
2807             STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS
2808     })
2809     public @interface ProvisioningPrecondition {}
2810 
2811     /**
2812      * Disable all configurable SystemUI features during LockTask mode. This includes,
2813      * <ul>
2814      *     <li>system info area in the status bar (connectivity icons, clock, etc.)
2815      *     <li>notifications (including alerts, icons, and the notification shade)
2816      *     <li>Home button
2817      *     <li>Recents button and UI
2818      *     <li>global actions menu (i.e. power button menu)
2819      *     <li>keyguard
2820      * </ul>
2821      *
2822      * @see #setLockTaskFeatures(ComponentName, int)
2823      */
2824     public static final int LOCK_TASK_FEATURE_NONE = 0;
2825 
2826     /**
2827      * Enable the system info area in the status bar during LockTask mode. The system info area
2828      * usually occupies the right side of the status bar (although this can differ across OEMs). It
2829      * includes all system information indicators, such as date and time, connectivity, battery,
2830      * vibration mode, etc.
2831      *
2832      * @see #setLockTaskFeatures(ComponentName, int)
2833      */
2834     public static final int LOCK_TASK_FEATURE_SYSTEM_INFO = 1;
2835 
2836     /**
2837      * Enable notifications during LockTask mode. This includes notification icons on the status
2838      * bar, heads-up notifications, and the expandable notification shade. Note that the Quick
2839      * Settings panel remains disabled. This feature flag can only be used in combination with
2840      * {@link #LOCK_TASK_FEATURE_HOME}. {@link #setLockTaskFeatures(ComponentName, int)}
2841      * throws an {@link IllegalArgumentException} if this feature flag is defined without
2842      * {@link #LOCK_TASK_FEATURE_HOME}.
2843      *
2844      * @see #setLockTaskFeatures(ComponentName, int)
2845      */
2846     public static final int LOCK_TASK_FEATURE_NOTIFICATIONS = 1 << 1;
2847 
2848     /**
2849      * Enable the Home button during LockTask mode. Note that if a custom launcher is used, it has
2850      * to be registered as the default launcher with
2851      * {@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}, and its
2852      * package needs to be allowlisted for LockTask with
2853      * {@link #setLockTaskPackages(ComponentName, String[])}.
2854      *
2855      * @see #setLockTaskFeatures(ComponentName, int)
2856      */
2857     public static final int LOCK_TASK_FEATURE_HOME = 1 << 2;
2858 
2859     /**
2860      * Enable the Overview button and the Overview screen during LockTask mode. This feature flag
2861      * can only be used in combination with {@link #LOCK_TASK_FEATURE_HOME}, and
2862      * {@link #setLockTaskFeatures(ComponentName, int)} will throw an
2863      * {@link IllegalArgumentException} if this feature flag is defined without
2864      * {@link #LOCK_TASK_FEATURE_HOME}.
2865      *
2866      * @see #setLockTaskFeatures(ComponentName, int)
2867      */
2868     public static final int LOCK_TASK_FEATURE_OVERVIEW = 1 << 3;
2869 
2870     /**
2871      * Enable the global actions dialog during LockTask mode. This is the dialog that shows up when
2872      * the user long-presses the power button, for example. Note that the user may not be able to
2873      * power off the device if this flag is not set.
2874      *
2875      * <p>This flag is enabled by default until {@link #setLockTaskFeatures(ComponentName, int)} is
2876      * called for the first time.
2877      *
2878      * @see #setLockTaskFeatures(ComponentName, int)
2879      */
2880     public static final int LOCK_TASK_FEATURE_GLOBAL_ACTIONS = 1 << 4;
2881 
2882     /**
2883      * Enable the keyguard during LockTask mode. Note that if the keyguard is already disabled with
2884      * {@link #setKeyguardDisabled(ComponentName, boolean)}, setting this flag will have no effect.
2885      * If this flag is not set, the keyguard will not be shown even if the user has a lock screen
2886      * credential.
2887      *
2888      * @see #setLockTaskFeatures(ComponentName, int)
2889      */
2890     public static final int LOCK_TASK_FEATURE_KEYGUARD = 1 << 5;
2891 
2892     /**
2893      * Enable blocking of non-allowlisted activities from being started into a locked task.
2894      *
2895      * @see #setLockTaskFeatures(ComponentName, int)
2896      */
2897     public static final int LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK = 1 << 6;
2898 
2899     /**
2900      * Flags supplied to {@link #setLockTaskFeatures(ComponentName, int)}.
2901      *
2902      * @hide
2903      */
2904     @Retention(RetentionPolicy.SOURCE)
2905     @IntDef(flag = true, prefix = { "LOCK_TASK_FEATURE_" }, value = {
2906             LOCK_TASK_FEATURE_NONE,
2907             LOCK_TASK_FEATURE_SYSTEM_INFO,
2908             LOCK_TASK_FEATURE_NOTIFICATIONS,
2909             LOCK_TASK_FEATURE_HOME,
2910             LOCK_TASK_FEATURE_OVERVIEW,
2911             LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
2912             LOCK_TASK_FEATURE_KEYGUARD,
2913             LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK
2914     })
2915     public @interface LockTaskFeature {}
2916 
2917     /**
2918      * Service action: Action for a service that device owner and profile owner can optionally
2919      * own.  If a device owner or a profile owner has such a service, the system tries to keep
2920      * a bound connection to it, in order to keep their process always running.
2921      * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN}
2922      * permission.
2923      */
2924     @SdkConstant(SdkConstantType.SERVICE_ACTION)
2925     public static final String ACTION_DEVICE_ADMIN_SERVICE
2926             = "android.app.action.DEVICE_ADMIN_SERVICE";
2927 
2928     /** @hide */
2929     @Retention(RetentionPolicy.SOURCE)
2930     @IntDef(flag = true, prefix = {"ID_TYPE_"}, value = {
2931         ID_TYPE_BASE_INFO,
2932         ID_TYPE_SERIAL,
2933         ID_TYPE_IMEI,
2934         ID_TYPE_MEID,
2935         ID_TYPE_INDIVIDUAL_ATTESTATION
2936     })
2937     public @interface AttestationIdType {}
2938 
2939     /**
2940      * Specifies that the device should attest its manufacturer details. For use with
2941      * {@link #generateKeyPair}.
2942      *
2943      * @see #generateKeyPair
2944      */
2945     public static final int ID_TYPE_BASE_INFO = 1;
2946 
2947     /**
2948      * Specifies that the device should attest its serial number. For use with
2949      * {@link #generateKeyPair}.
2950      *
2951      * @see #generateKeyPair
2952      */
2953     public static final int ID_TYPE_SERIAL = 2;
2954 
2955     /**
2956      * Specifies that the device should attest its IMEI. For use with {@link #generateKeyPair}.
2957      *
2958      * @see #generateKeyPair
2959      */
2960     public static final int ID_TYPE_IMEI = 4;
2961 
2962     /**
2963      * Specifies that the device should attest its MEID. For use with {@link #generateKeyPair}.
2964      *
2965      * @see #generateKeyPair
2966      */
2967     public static final int ID_TYPE_MEID = 8;
2968 
2969     /**
2970      * Specifies that the device should attest using an individual attestation certificate.
2971      * For use with {@link #generateKeyPair}.
2972      *
2973      * @see #generateKeyPair
2974      */
2975     public static final int ID_TYPE_INDIVIDUAL_ATTESTATION = 16;
2976 
2977     /**
2978      * Service-specific error code for {@link #generateKeyPair}:
2979      * Indicates the call has failed due to StrongBox unavailability.
2980      * @hide
2981      */
2982     public static final int KEY_GEN_STRONGBOX_UNAVAILABLE = 1;
2983 
2984     /**
2985      * Specifies that the calling app should be granted access to the installed credentials
2986      * immediately. Otherwise, access to the credentials will be gated by user approval.
2987      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
2988      *
2989      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
2990      */
2991     public static final int INSTALLKEY_REQUEST_CREDENTIALS_ACCESS = 1;
2992 
2993     /**
2994      * Specifies that a user can select the key via the Certificate Selection prompt.
2995      * If this flag is not set when calling {@link #installKeyPair}, the key can only be granted
2996      * access by implementing {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
2997      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
2998      *
2999      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
3000      */
3001     public static final int INSTALLKEY_SET_USER_SELECTABLE = 2;
3002 
3003     /**
3004      * Broadcast action: sent when the profile owner is set, changed or cleared.
3005      *
3006      * This broadcast is sent only to the user managed by the new profile owner.
3007      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
3008      */
3009     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3010     public static final String ACTION_PROFILE_OWNER_CHANGED =
3011             "android.app.action.PROFILE_OWNER_CHANGED";
3012 
3013     /** @hide */
3014     @Retention(RetentionPolicy.SOURCE)
3015     @IntDef(prefix = {"PRIVATE_DNS_MODE_"}, value = {
3016             PRIVATE_DNS_MODE_UNKNOWN,
3017             PRIVATE_DNS_MODE_OFF,
3018             PRIVATE_DNS_MODE_OPPORTUNISTIC,
3019             PRIVATE_DNS_MODE_PROVIDER_HOSTNAME
3020     })
3021     public @interface PrivateDnsMode {}
3022 
3023     /**
3024      * Specifies that the Private DNS setting is in an unknown state.
3025      */
3026     public static final int PRIVATE_DNS_MODE_UNKNOWN = 0;
3027 
3028     /**
3029      * Specifies that Private DNS was turned off completely.
3030      */
3031     public static final int PRIVATE_DNS_MODE_OFF = 1;
3032 
3033     /**
3034      * Specifies that the device owner requested opportunistic DNS over TLS
3035      */
3036     public static final int PRIVATE_DNS_MODE_OPPORTUNISTIC = 2;
3037 
3038     /**
3039      * Specifies that the device owner configured a specific host to use for Private DNS.
3040      */
3041     public static final int PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = 3;
3042 
3043     /**
3044      * Callback used in {@link #installSystemUpdate} to indicate that there was an error while
3045      * trying to install an update.
3046      */
3047     public abstract static class InstallSystemUpdateCallback {
3048         /** Represents an unknown error while trying to install an update. */
3049         public static final int UPDATE_ERROR_UNKNOWN = 1;
3050 
3051         /** Represents the update file being intended for different OS version. */
3052         public static final int UPDATE_ERROR_INCORRECT_OS_VERSION = 2;
3053 
3054         /**
3055          * Represents the update file being wrong; e.g. payloads are mismatched, or the wrong
3056          * compression method is used.
3057          */
3058         public static final int UPDATE_ERROR_UPDATE_FILE_INVALID = 3;
3059 
3060         /** Represents that the file could not be found. */
3061         public static final int UPDATE_ERROR_FILE_NOT_FOUND = 4;
3062 
3063         /** Represents the battery being too low to apply an update. */
3064         public static final int UPDATE_ERROR_BATTERY_LOW = 5;
3065 
3066         /**
3067          * Method invoked when there was an error while installing an update.
3068          *
3069          * <p>The given error message is not intended to be user-facing. It is intended to be
3070          * reported back to the IT admin to be read.
3071          */
onInstallUpdateError( @nstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage)3072         public void onInstallUpdateError(
3073                 @InstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage) {
3074         }
3075     }
3076 
3077     /**
3078      * @hide
3079      */
3080     @IntDef(prefix = { "UPDATE_ERROR_" }, value = {
3081             InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN,
3082             InstallSystemUpdateCallback.UPDATE_ERROR_INCORRECT_OS_VERSION,
3083             InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
3084             InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
3085             InstallSystemUpdateCallback.UPDATE_ERROR_BATTERY_LOW
3086     })
3087     @Retention(RetentionPolicy.SOURCE)
3088     public @interface InstallUpdateCallbackErrorConstants {}
3089 
3090     /**
3091      * The selected mode has been set successfully. If the mode is
3092      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} then it implies the supplied host is valid
3093      * and reachable.
3094      */
3095     public static final int PRIVATE_DNS_SET_NO_ERROR = 0;
3096 
3097     /**
3098      * If the {@code privateDnsHost} provided was of a valid hostname but that host was found
3099      * to not support DNS-over-TLS.
3100      */
3101     public static final int PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING = 1;
3102 
3103     /**
3104      * General failure to set the Private DNS mode, not due to one of the reasons listed above.
3105      */
3106     public static final int PRIVATE_DNS_SET_ERROR_FAILURE_SETTING = 2;
3107 
3108     /**
3109      * @hide
3110      */
3111     @IntDef(prefix = {"PRIVATE_DNS_SET_"}, value = {
3112             PRIVATE_DNS_SET_NO_ERROR,
3113             PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING,
3114             PRIVATE_DNS_SET_ERROR_FAILURE_SETTING
3115     })
3116     @Retention(RetentionPolicy.SOURCE)
3117     public @interface PrivateDnsModeErrorCodes {}
3118 
3119     /**
3120      * Activity action: Starts the administrator to get the mode for the provisioning.
3121      * This intent may contain the following extras:
3122      * <ul>
3123      *     <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}</li>
3124      *     <li>{@link #EXTRA_PROVISIONING_IMEI}</li>
3125      *     <li>{@link #EXTRA_PROVISIONING_SERIAL_NUMBER}</li>
3126      *     <li>{@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES}</li>
3127      *     <li>{@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT}</li>
3128      * </ul>
3129      *
3130      * <p>The target activity should return one of the following values in
3131      * {@link #EXTRA_PROVISIONING_MODE} as result:
3132      * <ul>
3133      *     <li>{@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}</li>
3134      *     <li>{@link #PROVISIONING_MODE_MANAGED_PROFILE}</li>
3135      * </ul>
3136      *
3137      * <p>If performing fully-managed device provisioning and the admin app desires to show its
3138      * own education screens, the target activity can additionally return
3139      * {@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS} set to <code>true</code>.
3140      *
3141      * <p>The target activity may also return the account that needs to be migrated from primary
3142      * user to managed profile in case of a profile owner provisioning in
3143      * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE} as result.
3144      *
3145      * <p>The target activity may also include the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}
3146      * extra in the intent result. The values of this {@link android.os.PersistableBundle} will be
3147      * sent as an intent extra of the same name to the {@link #ACTION_ADMIN_POLICY_COMPLIANCE}
3148      * activity, along with the values of the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE} extra
3149      * that are already supplied to this activity.
3150      *
3151      * <p>Other extras the target activity may include in the intent result:
3152      * <ul>
3153      *     <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}</li>
3154      *     <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}</li>
3155      *     <li>{@link #EXTRA_PROVISIONING_KEEP_SCREEN_ON}</li>
3156      *     <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION} for work profile
3157      *     provisioning</li>
3158      *     <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED} for work profile
3159      *     provisioning</li>
3160      *     <li>{@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT} for fully-managed
3161      *     device provisioning</li>
3162      *     <li>{@link #EXTRA_PROVISIONING_LOCALE} for fully-managed device provisioning</li>
3163      *     <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} for fully-managed device provisioning</li>
3164      *     <li>{@link #EXTRA_PROVISIONING_TIME_ZONE} for fully-managed device provisioning</li>
3165      * </ul>
3166      *
3167      * @see #ACTION_ADMIN_POLICY_COMPLIANCE
3168      */
3169     public static final String ACTION_GET_PROVISIONING_MODE =
3170             "android.app.action.GET_PROVISIONING_MODE";
3171 
3172     /**
3173      * A string extra holding the IMEI (International Mobile Equipment Identity) of the device.
3174      */
3175     public static final String EXTRA_PROVISIONING_IMEI = "android.app.extra.PROVISIONING_IMEI";
3176 
3177     /**
3178      * A string extra holding the serial number of the device.
3179      */
3180     public static final String EXTRA_PROVISIONING_SERIAL_NUMBER =
3181             "android.app.extra.PROVISIONING_SERIAL_NUMBER";
3182 
3183     /**
3184      * An intent extra holding the provisioning mode returned by the administrator.
3185      * The value of this extra must be one of the values provided in {@link
3186      * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES}, which is provided as an intent extra to
3187      * the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity.
3188      *
3189      * @see #PROVISIONING_MODE_FULLY_MANAGED_DEVICE
3190      * @see #PROVISIONING_MODE_MANAGED_PROFILE
3191      */
3192     public static final String EXTRA_PROVISIONING_MODE =
3193             "android.app.extra.PROVISIONING_MODE";
3194 
3195     /**
3196      * An integer extra indication what provisioning modes should be available for the admin app
3197      * to pick.
3198      *
3199      * <p>The default value is {@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}.
3200      *
3201      * <p>The value of this extra will determine the contents of the {@link
3202      * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array that is passed to the admin app as an
3203      * extra to its {@link #ACTION_GET_PROVISIONING_MODE} activity.
3204      *
3205      * <p>If one of the possible admin app choices is a personally-owned work profile, then the
3206      * IMEI and serial number will not be passed to the admin app's {@link
3207      * #ACTION_GET_PROVISIONING_MODE} activity via the {@link #EXTRA_PROVISIONING_IMEI} and {@link
3208      * #EXTRA_PROVISIONING_SERIAL_NUMBER} respectively.
3209      *
3210      * <p>The allowed flag combinations are:
3211      * <ul>
3212      *     <li>{@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}</li>
3213      *     <li>{@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}</li>
3214      *     <li>{@link #FLAG_SUPPORTED_MODES_DEVICE_OWNER}</li>
3215      *     <li>{@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}
3216      *             | {@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}</li>
3217      * </ul>
3218      *
3219      * <p>This extra is only respected when provided alongside the {@link
3220      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
3221      *
3222      * @see #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED
3223      * @see #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED
3224      * @see #FLAG_SUPPORTED_MODES_DEVICE_OWNER
3225      * @hide
3226      */
3227     @SystemApi
3228     public static final String EXTRA_PROVISIONING_SUPPORTED_MODES =
3229             "android.app.extra.PROVISIONING_SUPPORTED_MODES";
3230 
3231     /**
3232      * A boolean extra which determines whether to skip the ownership disclaimer screen during the
3233      * provisioning flow. The default value is {@code false}.
3234      *
3235      * If the value is {@code true}, the provisioning initiator must display a device ownership
3236      * disclaimer screen similar to that provided in AOSP.
3237      *
3238      * <p>This extra is only respected when provided alongside the {@link
3239      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
3240      *
3241      * @hide
3242      */
3243     @SystemApi
3244     public static final String EXTRA_PROVISIONING_SKIP_OWNERSHIP_DISCLAIMER =
3245             "android.app.extra.PROVISIONING_SKIP_OWNERSHIP_DISCLAIMER";
3246 
3247     /**
3248      * An {@link ArrayList} of {@link Integer} extra specifying the allowed provisioning modes.
3249      * <p>This extra will be passed to the admin app's {@link #ACTION_GET_PROVISIONING_MODE}
3250      * activity, whose result intent must contain {@link #EXTRA_PROVISIONING_MODE} set to one of
3251      * the values in this array.
3252      * <p>If the value set to {@link #EXTRA_PROVISIONING_MODE} is not in the array,
3253      * provisioning will fail.
3254      * @see #PROVISIONING_MODE_MANAGED_PROFILE
3255      * @see #PROVISIONING_MODE_FULLY_MANAGED_DEVICE
3256      */
3257     public static final String EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES =
3258             "android.app.extra.PROVISIONING_ALLOWED_PROVISIONING_MODES";
3259 
3260     /**
3261      * The provisioning mode for fully managed device.
3262      */
3263     public static final int PROVISIONING_MODE_FULLY_MANAGED_DEVICE = 1;
3264 
3265     /**
3266      * The provisioning mode for managed profile.
3267      */
3268     public static final int PROVISIONING_MODE_MANAGED_PROFILE = 2;
3269 
3270     /**
3271      * The provisioning mode for a managed profile on a personal device.
3272      * <p>This mode is only available when the provisioning initiator has explicitly instructed the
3273      * provisioning flow to support managed profile on a personal device provisioning. In that case,
3274      * {@link #PROVISIONING_MODE_MANAGED_PROFILE} corresponds to an organization-owned managed
3275      * profile, whereas this constant corresponds to a personally-owned managed profile.
3276      *
3277      * @see #EXTRA_PROVISIONING_MODE
3278      */
3279     public static final int PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE = 3;
3280 
3281     /**
3282      * A {@code boolean} flag that indicates whether the provisioning flow should return before
3283      * starting the admin app's {@link #ACTION_ADMIN_POLICY_COMPLIANCE} handler. The default value
3284      * is {@code true}.
3285      *
3286      * <p>If this extra is set to {@code true}, then when the provisioning flow returns back to the
3287      * provisioning initiator, provisioning will not be complete. The provisioning initiator can
3288      * use this opportunity to do its own preparatory steps prior to the launch of the admin app's
3289      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} handler. It is the responsibility of the
3290      * provisioning initiator to ensure that the provisioning flow is then resumed and completed.
3291      *
3292      * <p>If this extra is set to {@code false}, then when the provisioning flow returns back to
3293      * the provisioning initiator, provisioning will be complete. Note that device owner
3294      * provisioning is not currently supported for the this scenario.
3295      *
3296      * <p>This extra is only respected when provided alongside the {@link
3297      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
3298      *
3299      * @hide
3300      */
3301     @SystemApi
3302     public static final String EXTRA_PROVISIONING_RETURN_BEFORE_POLICY_COMPLIANCE =
3303             "android.app.extra.PROVISIONING_RETURN_BEFORE_POLICY_COMPLIANCE";
3304 
3305     /**
3306      * A {@code boolean} flag that indicates whether the screen should be on throughout the
3307      * provisioning flow.
3308      *
3309      * <p>The default value is {@code false}.
3310      *
3311      * <p>This extra can either be passed as an extra to the {@link
3312      * #ACTION_PROVISION_MANAGED_PROFILE} intent, or it can be returned by the
3313      * admin app when performing the admin-integrated provisioning flow as a result of the
3314      * {@link #ACTION_GET_PROVISIONING_MODE} activity.
3315      */
3316     public static final String EXTRA_PROVISIONING_KEEP_SCREEN_ON =
3317             "android.app.extra.PROVISIONING_KEEP_SCREEN_ON";
3318 
3319     /**
3320      * Activity action: Starts the administrator to show policy compliance for the provisioning.
3321      * This action is used any time that the administrator has an opportunity to show policy
3322      * compliance before the end of setup wizard. This could happen as part of the admin-integrated
3323      * provisioning flow (in which case this gets sent after {@link #ACTION_GET_PROVISIONING_MODE}),
3324      * or it could happen during provisioning finalization if the administrator supports
3325      * finalization during setup wizard.
3326      *
3327      * <p>Intents with this action may also be supplied with the {@link
3328      * #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE} extra.
3329      *
3330      * @see #ACTION_GET_PROVISIONING_MODE
3331      */
3332     public static final String ACTION_ADMIN_POLICY_COMPLIANCE =
3333             "android.app.action.ADMIN_POLICY_COMPLIANCE";
3334 
3335     /**
3336      * Activity action: Starts the device policy management role holder updater.
3337      *
3338      * <p>The activity must handle the device policy management role holder update and set the
3339      * intent result. This can include {@link Activity#RESULT_OK} if the update was successful,
3340      * {@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_RECOVERABLE_ERROR} if
3341      * it encounters a problem that may be solved by relaunching it again, {@link
3342      * #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_PROVISIONING_DISABLED} if role holder
3343      * provisioning is disabled, or {@link
3344      * #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR} if it encounters
3345      * any other problem that will not be solved by relaunching it again.
3346      *
3347      * <p>If this activity has additional internal conditions which are not met, it should return
3348      * {@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR}.
3349      *
3350      * @hide
3351      */
3352     @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP)
3353     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3354     @SystemApi
3355     public static final String ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER =
3356             "android.app.action.UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER";
3357 
3358     /**
3359      * Result code that can be returned by the {@link
3360      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} handler if it encounters a problem
3361      * that may be solved by relaunching it again.
3362      *
3363      * @hide
3364      */
3365     @SystemApi
3366     public static final int RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_RECOVERABLE_ERROR =
3367             1;
3368 
3369     /**
3370      * Result code that can be returned by the {@link
3371      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} handler if it encounters a problem that
3372      * will not be solved by relaunching it again.
3373      *
3374      * @hide
3375      */
3376     @SystemApi
3377     public static final int RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR =
3378             2;
3379 
3380     /**
3381      * Result code that can be returned by the {@link
3382      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} handler if role holder provisioning
3383      * is disabled.
3384      *
3385      * @hide
3386      */
3387     @SystemApi
3388     public static final int
3389             RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_PROVISIONING_DISABLED = 3;
3390 
3391     /**
3392      * An {@code int} extra that specifies one of {@link
3393      * #ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING} or {@link
3394      * #ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FALLBACK_TO_PLATFORM_PROVISIONING}.
3395      *
3396      * <p>The failure strategy specifies how the platform should handle a failed device policy
3397      * management role holder update via {@link
3398      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} when {@link
3399      * #EXTRA_PROVISIONING_ALLOW_OFFLINE} is not set or set to {@code false}.
3400      *
3401      * <p>This extra may be supplied as part of the {@link
3402      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} result intent.
3403      *
3404      * <p>Default value is {@link #ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING}.
3405      *
3406      * @hide
3407      */
3408     public static final String EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY =
3409             "android.app.extra.ROLE_HOLDER_UPDATE_FAILURE_STRATEGY";
3410 
3411     /**
3412      * Possible values for {@link #EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY}.
3413      *
3414      * @hide
3415      */
3416     @IntDef(prefix = { "ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_" }, value = {
3417             ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING,
3418             ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FALLBACK_TO_PLATFORM_PROVISIONING
3419     })
3420     @Retention(RetentionPolicy.SOURCE)
3421     public @interface RoleHolderUpdateFailureStrategy {}
3422 
3423     /**
3424      * A value for {@link #EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY} indicating that upon
3425      * failure to update the role holder, provisioning should fail.
3426      *
3427      * @hide
3428      */
3429     public static final int ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING = 1;
3430 
3431     /**
3432      * A value for {@link #EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY} indicating that upon
3433      * failure to update the role holder, provisioning should fallback to be platform-driven.
3434      *
3435      * @hide
3436      */
3437     public static final int ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FALLBACK_TO_PLATFORM_PROVISIONING =
3438             2;
3439 
3440     /**
3441      * An {@code int} extra which contains the result code of the last attempt to update
3442      * the device policy management role holder via {@link
3443      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER}.
3444      *
3445      * <p>This extra is provided to the device policy management role holder via either {@link
3446      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link
3447      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} when started after the role holder
3448      * had previously returned {@link #RESULT_UPDATE_ROLE_HOLDER}.
3449      *
3450      * <p>If the role holder update had failed, the role holder can use the value of this extra to
3451      * make a decision whether to fail the provisioning flow or to carry on with the older version
3452      * of the role holder.
3453      *
3454      * <p>Possible values can be:
3455      * <ul>
3456      *    <li>{@link Activity#RESULT_OK} if the update was successful
3457      *    <li>{@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_RECOVERABLE_ERROR} if it
3458      *    encounters a problem that may be solved by relaunching it again.
3459      *    <li>{@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR} if
3460      *    it encounters a problem that will not be solved by relaunching it again.
3461      *    <li>Any other value returned by {@link
3462      *    #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER}
3463      * </ul>
3464      *
3465      * @hide
3466      */
3467     @SystemApi
3468     public static final String EXTRA_ROLE_HOLDER_UPDATE_RESULT_CODE =
3469             "android.app.extra.ROLE_HOLDER_UPDATE_RESULT_CODE";
3470 
3471     /**
3472      * An {@link Intent} extra which resolves to a custom user consent screen.
3473      *
3474      * <p>If this extra is provided to the device policy management role holder via either {@link
3475      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link
3476      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE}, the device policy management role holder must
3477      * launch this intent which shows the custom user consent screen, replacing its own standard
3478      * consent screen.
3479      *
3480      * <p>If this extra is provided, it is the responsibility of the intent handler to show the
3481      * list of disclaimers which are normally shown by the standard consent screen:
3482      * <ul>
3483      *     <li>Disclaimers set by the IT admin via the {@link #EXTRA_PROVISIONING_DISCLAIMERS}
3484      *     provisioning extra</li>
3485      *     <li>For fully-managed device provisioning, disclaimers defined in system apps via the
3486      *     {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER} and {@link
3487      *     #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} metadata in their manifests</li>
3488      *     <li>General disclaimer relevant to the provisioning mode</li>
3489      * </ul>
3490      *
3491      * <p>When this {@link Intent} is started, the following intent extras will be supplied:
3492      * <ul>
3493      *     <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}</li>
3494      *     <li>{@link #EXTRA_PROVISIONING_MODE}</li>
3495      *     <li>{@link #EXTRA_PROVISIONING_LOCALE}</li>
3496      *     <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME}</li>
3497      *     <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}</li>
3498      *     <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}</li>
3499      * </ul>
3500      *
3501      * <p>If the custom consent screens are granted by the user {@link Activity#RESULT_OK} is
3502      * returned, otherwise {@link Activity#RESULT_CANCELED} is returned. The device policy
3503      * management role holder should ensure that the provisioning flow terminates immediately if
3504      * consent is not granted by the user.
3505      *
3506      * @hide
3507      */
3508     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3509     @SystemApi
3510     public static final String EXTRA_PROVISIONING_ROLE_HOLDER_CUSTOM_USER_CONSENT_INTENT =
3511             "android.app.extra.PROVISIONING_ROLE_HOLDER_CUSTOM_USER_CONSENT_INTENT";
3512 
3513     /**
3514      * Activity action: attempts to establish network connection
3515      *
3516      * <p>This intent can be accompanied by any of the relevant provisioning extras related to
3517      * network connectivity, such as:
3518      * <ul>
3519      *     <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}</li>
3520      *     <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN}</li>
3521      *     <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}</li>
3522      *     <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}</li>
3523      *     <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}</li>
3524      *     <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT}</li>
3525      *     <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}</li>
3526      *     <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}</li>
3527      *     <li>{@code #EXTRA_PROVISIONING_WIFI_EAP_METHOD}</li>
3528      *     <li>{@code #EXTRA_PROVISIONING_WIFI_PHASE2_AUTH}</li>
3529      *     <li>{@code #EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE}</li>
3530      *     <li>{@code #EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE}</li>
3531      *     <li>{@code #EXTRA_PROVISIONING_WIFI_IDENTITY}</li>
3532      *     <li>{@code #EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY}</li>
3533      *     <li>{@code #EXTRA_PROVISIONING_WIFI_DOMAIN}</li>
3534      * </ul>
3535      *
3536      * <p>If there are provisioning extras related to network connectivity, this activity
3537      * attempts to connect to the specified network. Otherwise it prompts the end-user to connect.
3538      *
3539      * <p>This activity is meant to be started by the provisioning initiator prior to starting
3540      * {@link #ACTION_PROVISION_MANAGED_PROFILE} or {@link
3541      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}.
3542      *
3543      * <p>Note that network connectivity is still also handled when provisioning via {@link
3544      * #ACTION_PROVISION_MANAGED_PROFILE} or {@link
3545      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}. {@link
3546      * #ACTION_ESTABLISH_NETWORK_CONNECTION} should only be used in cases when the provisioning
3547      * initiator would like to do some additional logic after the network connectivity step and
3548      * before the start of provisioning.
3549      *
3550      * If network connection is established, {@link Activity#RESULT_OK} will be returned. Otherwise
3551      * the result will be {@link Activity#RESULT_CANCELED}.
3552      *
3553      * @hide
3554      */
3555     @RequiresPermission(android.Manifest.permission.DISPATCH_PROVISIONING_MESSAGE)
3556     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3557     @SystemApi
3558     public static final String ACTION_ESTABLISH_NETWORK_CONNECTION =
3559             "android.app.action.ESTABLISH_NETWORK_CONNECTION";
3560 
3561     /**
3562      * Maximum supported password length. Kind-of arbitrary.
3563      * @hide
3564      */
3565     public static final int MAX_PASSWORD_LENGTH = 16;
3566 
3567     /**
3568      * Service Action: Service implemented by a device owner or profile owner supervision app to
3569      * provide a secondary lockscreen.
3570      * @hide
3571      */
3572     @SystemApi
3573     public static final String ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE =
3574             "android.app.action.BIND_SECONDARY_LOCKSCREEN_SERVICE";
3575 
3576     /**
3577      * Return value for {@link #getPersonalAppsSuspendedReasons} when personal apps are not
3578      * suspended.
3579      */
3580     public static final int PERSONAL_APPS_NOT_SUSPENDED = 0;
3581 
3582     /**
3583      * Flag for {@link #getPersonalAppsSuspendedReasons} return value. Set when personal
3584      * apps are suspended by an admin explicitly via {@link #setPersonalAppsSuspended}.
3585      */
3586     public static final int PERSONAL_APPS_SUSPENDED_EXPLICITLY = 1 << 0;
3587 
3588     /**
3589      * Flag for {@link #getPersonalAppsSuspendedReasons} return value. Set when personal apps are
3590      * suspended by framework because managed profile was off for longer than allowed by policy.
3591      * @see #setManagedProfileMaximumTimeOff
3592      */
3593     public static final int PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT = 1 << 1;
3594 
3595     /**
3596      * @hide
3597      */
3598     @IntDef(flag = true, prefix = { "PERSONAL_APPS_" }, value = {
3599             PERSONAL_APPS_NOT_SUSPENDED,
3600             PERSONAL_APPS_SUSPENDED_EXPLICITLY,
3601             PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT
3602     })
3603     @Retention(RetentionPolicy.SOURCE)
3604     public @interface PersonalAppsSuspensionReason {}
3605 
3606     /**
3607      * The default device owner type for a managed device.
3608      *
3609      * @hide
3610      */
3611     @TestApi
3612     public static final int DEVICE_OWNER_TYPE_DEFAULT = 0;
3613 
3614     /**
3615      * The device owner type for a financed device.
3616      *
3617      * @hide
3618      */
3619     @TestApi
3620     public static final int DEVICE_OWNER_TYPE_FINANCED = 1;
3621 
3622     /**
3623      * Different device owner types for a managed device.
3624      *
3625      * @hide
3626      */
3627     @Retention(RetentionPolicy.SOURCE)
3628     @IntDef(prefix = { "DEVICE_OWNER_TYPE_" }, value = {
3629             DEVICE_OWNER_TYPE_DEFAULT,
3630             DEVICE_OWNER_TYPE_FINANCED
3631     })
3632     public @interface DeviceOwnerType {}
3633 
3634     /** @hide */
3635     @TestApi
3636     public static final int OPERATION_LOCK_NOW = 1;
3637     /** @hide */
3638     @TestApi
3639     public static final int OPERATION_SWITCH_USER = 2;
3640     /** @hide */
3641     @TestApi
3642     public static final int OPERATION_START_USER_IN_BACKGROUND = 3;
3643     /** @hide */
3644     @TestApi
3645     public static final int OPERATION_STOP_USER = 4;
3646     /** @hide */
3647     @TestApi
3648     public static final int OPERATION_CREATE_AND_MANAGE_USER = 5;
3649     /** @hide */
3650     @TestApi
3651     public static final int OPERATION_REMOVE_USER = 6;
3652     /** @hide */
3653     @TestApi
3654     public static final int OPERATION_REBOOT = 7;
3655     /** @hide */
3656     @TestApi
3657     public static final int OPERATION_WIPE_DATA = 8;
3658     /** @hide */
3659     @TestApi
3660     public static final int OPERATION_LOGOUT_USER = 9;
3661     /** @hide */
3662     @TestApi
3663     public static final int OPERATION_SET_USER_RESTRICTION = 10;
3664     /** @hide */
3665     @TestApi
3666     public static final int OPERATION_SET_SYSTEM_SETTING = 11;
3667     /** @hide */
3668     @TestApi
3669     public static final int OPERATION_SET_KEYGUARD_DISABLED = 12;
3670     /** @hide */
3671     @TestApi
3672     public static final int OPERATION_SET_STATUS_BAR_DISABLED = 13;
3673     /** @hide */
3674     @TestApi
3675     public static final int OPERATION_SET_SYSTEM_UPDATE_POLICY = 14;
3676     /** @hide */
3677     @TestApi
3678     public static final int OPERATION_SET_APPLICATION_HIDDEN = 15;
3679     /** @hide */
3680     @TestApi
3681     public static final int OPERATION_SET_APPLICATION_RESTRICTIONS = 16;
3682     /** @hide */
3683     @TestApi
3684     public static final int OPERATION_SET_KEEP_UNINSTALLED_PACKAGES = 17;
3685     /** @hide */
3686     @TestApi
3687     public static final int OPERATION_SET_LOCK_TASK_FEATURES = 18;
3688     /** @hide */
3689     @TestApi
3690     public static final int OPERATION_SET_LOCK_TASK_PACKAGES = 19;
3691     /** @hide */
3692     @TestApi
3693     public static final int OPERATION_SET_PACKAGES_SUSPENDED = 20;
3694     /** @hide */
3695     @TestApi
3696     public static final int OPERATION_SET_TRUST_AGENT_CONFIGURATION = 21;
3697     /** @hide */
3698     @TestApi
3699     public static final int OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES = 22;
3700     /** @hide */
3701     @TestApi
3702     public static final int OPERATION_CLEAR_APPLICATION_USER_DATA = 23;
3703     /** @hide */
3704     @TestApi
3705     public static final int OPERATION_INSTALL_CA_CERT = 24;
3706     /** @hide */
3707     @TestApi
3708     public static final int OPERATION_INSTALL_KEY_PAIR = 25;
3709     /** @hide */
3710     @TestApi
3711     public static final int OPERATION_INSTALL_SYSTEM_UPDATE = 26;
3712     /** @hide */
3713     @TestApi
3714     public static final int OPERATION_REMOVE_ACTIVE_ADMIN = 27;
3715     /** @hide */
3716     @TestApi
3717     public static final int OPERATION_REMOVE_KEY_PAIR = 28;
3718     /** @hide */
3719     @TestApi
3720     public static final int OPERATION_REQUEST_BUGREPORT = 29;
3721     /** @hide */
3722     @TestApi
3723     public static final int OPERATION_SET_ALWAYS_ON_VPN_PACKAGE = 30;
3724     /** @hide */
3725     @TestApi
3726     public static final int OPERATION_SET_CAMERA_DISABLED = 31;
3727     /** @hide */
3728     @TestApi
3729     public static final int OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY = 32;
3730     /** @hide */
3731     @TestApi
3732     public static final int OPERATION_SET_GLOBAL_PRIVATE_DNS = 33;
3733     /** @hide */
3734     @TestApi
3735     public static final int OPERATION_SET_LOGOUT_ENABLED = 34;
3736     /** @hide */
3737     @TestApi
3738     public static final int OPERATION_SET_MASTER_VOLUME_MUTED = 35;
3739     /** @hide */
3740     @TestApi
3741     public static final int OPERATION_SET_OVERRIDE_APNS_ENABLED = 36;
3742     /** @hide */
3743     @TestApi
3744     public static final int OPERATION_SET_PERMISSION_GRANT_STATE = 37;
3745     /** @hide */
3746     @TestApi
3747     public static final int OPERATION_SET_PERMISSION_POLICY = 38;
3748     /** @hide */
3749     @TestApi
3750     public static final int OPERATION_SET_RESTRICTIONS_PROVIDER = 39;
3751     /** @hide */
3752     @TestApi
3753     public static final int OPERATION_UNINSTALL_CA_CERT = 40;
3754 
3755     private static final String PREFIX_OPERATION = "OPERATION_";
3756 
3757     /** @hide */
3758     @IntDef(prefix = PREFIX_OPERATION, value = {
3759             OPERATION_LOCK_NOW,
3760             OPERATION_SWITCH_USER,
3761             OPERATION_START_USER_IN_BACKGROUND,
3762             OPERATION_STOP_USER,
3763             OPERATION_CREATE_AND_MANAGE_USER,
3764             OPERATION_REMOVE_USER,
3765             OPERATION_REBOOT,
3766             OPERATION_WIPE_DATA,
3767             OPERATION_LOGOUT_USER,
3768             OPERATION_SET_USER_RESTRICTION,
3769             OPERATION_SET_SYSTEM_SETTING,
3770             OPERATION_SET_KEYGUARD_DISABLED,
3771             OPERATION_SET_STATUS_BAR_DISABLED,
3772             OPERATION_SET_SYSTEM_UPDATE_POLICY,
3773             OPERATION_SET_APPLICATION_HIDDEN,
3774             OPERATION_SET_APPLICATION_RESTRICTIONS,
3775             OPERATION_SET_KEEP_UNINSTALLED_PACKAGES,
3776             OPERATION_SET_LOCK_TASK_FEATURES,
3777             OPERATION_SET_LOCK_TASK_PACKAGES,
3778             OPERATION_SET_PACKAGES_SUSPENDED,
3779             OPERATION_SET_TRUST_AGENT_CONFIGURATION,
3780             OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES,
3781             OPERATION_CLEAR_APPLICATION_USER_DATA,
3782             OPERATION_INSTALL_CA_CERT,
3783             OPERATION_INSTALL_KEY_PAIR,
3784             OPERATION_INSTALL_SYSTEM_UPDATE,
3785             OPERATION_REMOVE_ACTIVE_ADMIN,
3786             OPERATION_REMOVE_KEY_PAIR,
3787             OPERATION_REQUEST_BUGREPORT,
3788             OPERATION_SET_ALWAYS_ON_VPN_PACKAGE,
3789             OPERATION_SET_CAMERA_DISABLED,
3790             OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY,
3791             OPERATION_SET_GLOBAL_PRIVATE_DNS,
3792             OPERATION_SET_LOGOUT_ENABLED,
3793             OPERATION_SET_MASTER_VOLUME_MUTED,
3794             OPERATION_SET_OVERRIDE_APNS_ENABLED,
3795             OPERATION_SET_PERMISSION_GRANT_STATE,
3796             OPERATION_SET_PERMISSION_POLICY,
3797             OPERATION_SET_RESTRICTIONS_PROVIDER,
3798             OPERATION_UNINSTALL_CA_CERT
3799     })
3800     @Retention(RetentionPolicy.SOURCE)
3801     public static @interface DevicePolicyOperation {
3802     }
3803 
3804     /** @hide */
3805     @TestApi
3806     @NonNull
operationToString(@evicePolicyOperation int operation)3807     public static String operationToString(@DevicePolicyOperation int operation) {
3808         return DebugUtils.constantToString(DevicePolicyManager.class, PREFIX_OPERATION, operation);
3809     }
3810 
3811     private static final String PREFIX_OPERATION_SAFETY_REASON = "OPERATION_SAFETY_REASON_";
3812 
3813     /** @hide */
3814     @IntDef(prefix = PREFIX_OPERATION_SAFETY_REASON, value = {
3815             OPERATION_SAFETY_REASON_NONE,
3816             OPERATION_SAFETY_REASON_DRIVING_DISTRACTION
3817     })
3818     @Retention(RetentionPolicy.SOURCE)
3819     public static @interface OperationSafetyReason {
3820     }
3821 
3822     /** @hide */
3823     @TestApi
3824     public static final int OPERATION_SAFETY_REASON_NONE = -1;
3825 
3826     /**
3827      * Indicates that a {@link UnsafeStateException} was thrown because the operation would distract
3828      * the driver of the vehicle.
3829      */
3830     public static final int OPERATION_SAFETY_REASON_DRIVING_DISTRACTION = 1;
3831 
3832     /**
3833      * Broadcast action: notify system apps (e.g. settings, SysUI, etc) that the device management
3834      * resources with IDs {@link #EXTRA_RESOURCE_IDS} has been updated, the updated resources can be
3835      * retrieved using {@link DevicePolicyResourcesManager#getDrawable} and
3836      * {@link DevicePolicyResourcesManager#getString}.
3837      *
3838      * <p>This broadcast is sent to registered receivers only.
3839      *
3840      * <p> {@link #EXTRA_RESOURCE_TYPE} will be included to identify the type of resource being
3841      * updated.
3842      */
3843     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3844     public static final String ACTION_DEVICE_POLICY_RESOURCE_UPDATED =
3845             "android.app.action.DEVICE_POLICY_RESOURCE_UPDATED";
3846 
3847     /**
3848      * An {@code int} extra for {@link #ACTION_DEVICE_POLICY_RESOURCE_UPDATED} to indicate the type
3849      * of the resource being updated, the type can be {@link #EXTRA_RESOURCE_TYPE_DRAWABLE} or
3850      * {@link #EXTRA_RESOURCE_TYPE_STRING}
3851      */
3852     public static final String EXTRA_RESOURCE_TYPE =
3853             "android.app.extra.RESOURCE_TYPE";
3854 
3855     /**
3856      * A {@code int} value for {@link #EXTRA_RESOURCE_TYPE} to indicate that a resource of type
3857      * {@link Drawable} is being updated.
3858      */
3859     public static final int EXTRA_RESOURCE_TYPE_DRAWABLE = 1;
3860 
3861     /**
3862      * A {@code int} value for {@link #EXTRA_RESOURCE_TYPE} to indicate that a resource of type
3863      * {@link String} is being updated.
3864      */
3865     public static final int EXTRA_RESOURCE_TYPE_STRING = 2;
3866 
3867     /**
3868      * An integer array extra for {@link #ACTION_DEVICE_POLICY_RESOURCE_UPDATED} to indicate which
3869      * resource IDs (see {@link DevicePolicyResources.Drawables} and
3870      * {@link DevicePolicyResources.Strings}) have been updated.
3871      */
3872     public static final String EXTRA_RESOURCE_IDS =
3873             "android.app.extra.RESOURCE_IDS";
3874 
3875     /**
3876      * This object is a single place to tack on invalidation and disable calls.  All
3877      * binder caches in this class derive from this Config, so all can be invalidated or
3878      * disabled through this Config.
3879      */
3880     private static final IpcDataCache.Config sDpmCaches =
3881             new IpcDataCache.Config(8, IpcDataCache.MODULE_SYSTEM, "DevicePolicyManagerCaches");
3882 
3883     /** @hide */
invalidateBinderCaches()3884     public static void invalidateBinderCaches() {
3885         sDpmCaches.invalidateCache();
3886     }
3887 
3888     /** @hide */
disableLocalCaches()3889     public static void disableLocalCaches() {
3890         sDpmCaches.disableAllForCurrentProcess();
3891     }
3892 
3893     /** @hide */
3894     @NonNull
3895     @TestApi
operationSafetyReasonToString(@perationSafetyReason int reason)3896     public static String operationSafetyReasonToString(@OperationSafetyReason int reason) {
3897         return DebugUtils.constantToString(DevicePolicyManager.class,
3898                 PREFIX_OPERATION_SAFETY_REASON, reason);
3899     }
3900 
3901     /** @hide */
isValidOperationSafetyReason(@perationSafetyReason int reason)3902     public static boolean isValidOperationSafetyReason(@OperationSafetyReason int reason) {
3903         return reason == OPERATION_SAFETY_REASON_DRIVING_DISTRACTION;
3904     }
3905 
3906     /**
3907      * Checks if it's safe to run operations that can be affected by the given {@code reason}.
3908      *
3909      * <p><b>Note:</b> notice that the operation safety state might change between the time this
3910      * method returns and the operation's method is called, so calls to the latter could still throw
3911      * a {@link UnsafeStateException} even when this method returns {@code true}.
3912      *
3913      * @param reason currently, only supported reason is
3914      * {@link #OPERATION_SAFETY_REASON_DRIVING_DISTRACTION}.
3915      *
3916      * @return whether it's safe to run operations that can be affected by the given {@code reason}.
3917      */
3918     // TODO(b/173541467): should it throw SecurityException if caller is not admin?
isSafeOperation(@perationSafetyReason int reason)3919     public boolean isSafeOperation(@OperationSafetyReason int reason) {
3920         throwIfParentInstance("isSafeOperation");
3921         if (mService == null) return false;
3922 
3923         try {
3924             return mService.isSafeOperation(reason);
3925         } catch (RemoteException e) {
3926             throw e.rethrowFromSystemServer();
3927         }
3928     }
3929 
3930     /**
3931      * Acknoledges that the new managed user disclaimer was viewed by the (human) user
3932      * so that {@link #ACTION_SHOW_NEW_USER_DISCLAIMER broadcast} is not sent again the next time
3933      * this user is switched to.
3934      *
3935      * @hide
3936      */
3937     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
3938             android.Manifest.permission.INTERACT_ACROSS_USERS})
3939     @UserHandleAware
3940     @TestApi
3941     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
acknowledgeNewUserDisclaimer()3942     public void acknowledgeNewUserDisclaimer() {
3943         if (mService != null) {
3944             try {
3945                 mService.acknowledgeNewUserDisclaimer(mContext.getUserId());
3946             } catch (RemoteException e) {
3947                 throw e.rethrowFromSystemServer();
3948             }
3949         }
3950     }
3951 
3952     /**
3953      * Checks whether the new managed user disclaimer was viewed by the user.
3954      *
3955      * @hide
3956      */
3957     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
3958             android.Manifest.permission.INTERACT_ACROSS_USERS})
3959     @TestApi
3960     @UserHandleAware
isNewUserDisclaimerAcknowledged()3961     public boolean isNewUserDisclaimerAcknowledged() {
3962         if (mService != null) {
3963             try {
3964                 return mService.isNewUserDisclaimerAcknowledged(mContext.getUserId());
3965             } catch (RemoteException e) {
3966                 throw e.rethrowFromSystemServer();
3967             }
3968         }
3969         return false;
3970     }
3971 
3972     /**
3973      * Return true if the given administrator component is currently active (enabled) in the system.
3974      *
3975      * @param admin The administrator component to check for.
3976      * @return {@code true} if {@code admin} is currently enabled in the system, {@code false}
3977      *         otherwise
3978      */
isAdminActive(@onNull ComponentName admin)3979     public boolean isAdminActive(@NonNull ComponentName admin) {
3980         throwIfParentInstance("isAdminActive");
3981         return isAdminActiveAsUser(admin, myUserId());
3982     }
3983 
3984     /**
3985      * @see #isAdminActive(ComponentName)
3986      * @hide
3987      */
isAdminActiveAsUser(@onNull ComponentName admin, int userId)3988     public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
3989         if (mService != null) {
3990             try {
3991                 return mService.isAdminActive(admin, userId);
3992             } catch (RemoteException e) {
3993                 throw e.rethrowFromSystemServer();
3994             }
3995         }
3996         return false;
3997     }
3998 
3999     /**
4000      * Return true if the given administrator component is currently being removed
4001      * for the user.
4002      * @hide
4003      */
4004     @TestApi
isRemovingAdmin(@onNull ComponentName admin, int userId)4005     public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
4006         if (mService != null) {
4007             try {
4008                 return mService.isRemovingAdmin(admin, userId);
4009             } catch (RemoteException e) {
4010                 throw e.rethrowFromSystemServer();
4011             }
4012         }
4013         return false;
4014     }
4015 
4016     /**
4017      * Return a list of all currently active device administrators' component
4018      * names.  If there are no administrators {@code null} may be
4019      * returned.
4020      */
getActiveAdmins()4021     public @Nullable List<ComponentName> getActiveAdmins() {
4022         throwIfParentInstance("getActiveAdmins");
4023         return getActiveAdminsAsUser(myUserId());
4024     }
4025 
4026     /**
4027      * @see #getActiveAdmins()
4028      * @hide
4029      */
4030     @UnsupportedAppUsage
getActiveAdminsAsUser(int userId)4031     public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) {
4032         if (mService != null) {
4033             try {
4034                 return mService.getActiveAdmins(userId);
4035             } catch (RemoteException e) {
4036                 throw e.rethrowFromSystemServer();
4037             }
4038         }
4039         return null;
4040     }
4041 
4042     /**
4043      * Used by package administration code to determine if a package can be stopped
4044      * or uninstalled.
4045      * @hide
4046      */
4047     @SystemApi
4048     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
packageHasActiveAdmins(String packageName)4049     public boolean packageHasActiveAdmins(String packageName) {
4050         return packageHasActiveAdmins(packageName, myUserId());
4051     }
4052 
4053     /**
4054      * Used by package administration code to determine if a package can be stopped
4055      * or uninstalled.
4056      * @hide
4057      */
4058     @UnsupportedAppUsage
packageHasActiveAdmins(String packageName, int userId)4059     public boolean packageHasActiveAdmins(String packageName, int userId) {
4060         if (mService != null) {
4061             try {
4062                 return mService.packageHasActiveAdmins(packageName, userId);
4063             } catch (RemoteException e) {
4064                 throw e.rethrowFromSystemServer();
4065             }
4066         }
4067         return false;
4068     }
4069 
4070     /**
4071      * Remove a current administration component.  This can only be called
4072      * by the application that owns the administration component; if you
4073      * try to remove someone else's component, a security exception will be
4074      * thrown.
4075      *
4076      * <p>Note that the operation is not synchronous and the admin might still be active (as
4077      * indicated by {@link #getActiveAdmins()}) by the time this method returns.
4078      *
4079      * @param admin The administration compononent to remove.
4080      * @throws SecurityException if the caller is not in the owner application of {@code admin}.
4081      */
removeActiveAdmin(@onNull ComponentName admin)4082     public void removeActiveAdmin(@NonNull ComponentName admin) {
4083         throwIfParentInstance("removeActiveAdmin");
4084         if (mService != null) {
4085             try {
4086                 mService.removeActiveAdmin(admin, myUserId());
4087             } catch (RemoteException e) {
4088                 throw e.rethrowFromSystemServer();
4089             }
4090         }
4091     }
4092 
4093     /**
4094      * Returns true if an administrator has been granted a particular device policy. This can be
4095      * used to check whether the administrator was activated under an earlier set of policies, but
4096      * requires additional policies after an upgrade.
4097      *
4098      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be an
4099      *            active administrator, or an exception will be thrown.
4100      * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
4101      * @throws SecurityException if {@code admin} is not an active administrator.
4102      */
hasGrantedPolicy(@onNull ComponentName admin, int usesPolicy)4103     public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) {
4104         throwIfParentInstance("hasGrantedPolicy");
4105         if (mService != null) {
4106             try {
4107                 return mService.hasGrantedPolicy(admin, usesPolicy, myUserId());
4108             } catch (RemoteException e) {
4109                 throw e.rethrowFromSystemServer();
4110             }
4111         }
4112         return false;
4113     }
4114 
4115     /**
4116      * Constant for {@link #setPasswordQuality}: the policy has no requirements
4117      * for the password.  Note that quality constants are ordered so that higher
4118      * values are more restrictive.
4119      */
4120     public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
4121 
4122     /**
4123      * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
4124      * recognition technology.  This implies technologies that can recognize the identity of
4125      * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
4126      * Note that quality constants are ordered so that higher values are more restrictive.
4127      */
4128     public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
4129 
4130     /**
4131      * Constant for {@link #setPasswordQuality}: the policy requires some kind
4132      * of password or pattern, but doesn't care what it is. Note that quality constants
4133      * are ordered so that higher values are more restrictive.
4134      */
4135     public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
4136 
4137     /**
4138      * Constant for {@link #setPasswordQuality}: the user must have entered a
4139      * password containing at least numeric characters.  Note that quality
4140      * constants are ordered so that higher values are more restrictive.
4141      */
4142     public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
4143 
4144     /**
4145      * Constant for {@link #setPasswordQuality}: the user must have entered a
4146      * password containing at least numeric characters with no repeating (4444)
4147      * or ordered (1234, 4321, 2468) sequences.  Note that quality
4148      * constants are ordered so that higher values are more restrictive.
4149      */
4150     public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
4151 
4152     /**
4153      * Constant for {@link #setPasswordQuality}: the user must have entered a
4154      * password containing at least alphabetic (or other symbol) characters.
4155      * Note that quality constants are ordered so that higher values are more
4156      * restrictive.
4157      */
4158     public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
4159 
4160     /**
4161      * Constant for {@link #setPasswordQuality}: the user must have entered a
4162      * password containing at least <em>both></em> numeric <em>and</em>
4163      * alphabetic (or other symbol) characters.  Note that quality constants are
4164      * ordered so that higher values are more restrictive.
4165      */
4166     public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
4167 
4168     /**
4169      * Constant for {@link #setPasswordQuality}: allows the admin to set precisely how many
4170      * characters of various types the password should contain to satisfy the policy. The admin
4171      * should set these requirements via {@link #setPasswordMinimumLetters},
4172      * {@link #setPasswordMinimumNumeric}, {@link #setPasswordMinimumSymbols},
4173      * {@link #setPasswordMinimumUpperCase}, {@link #setPasswordMinimumLowerCase},
4174      * {@link #setPasswordMinimumNonLetter}, and {@link #setPasswordMinimumLength}.
4175      * Note that quality constants are ordered so that higher values are more restrictive.
4176      */
4177     public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
4178 
4179     /**
4180      * Constant for {@link #setPasswordQuality}: the user is not allowed to
4181      * modify password. In case this password quality is set, the password is
4182      * managed by a profile owner. The profile owner can set any password,
4183      * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note
4184      * that quality constants are ordered so that higher values are more
4185      * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is
4186      * the highest.
4187      * @hide
4188      */
4189     public static final int PASSWORD_QUALITY_MANAGED = 0x80000;
4190 
4191     /**
4192      * @hide
4193      *
4194      * adb shell dpm set-{device,profile}-owner will normally not allow installing an owner to
4195      * a user with accounts.  {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED}
4196      * and {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} are the account features
4197      * used by authenticator to exempt their accounts from this:
4198      *
4199      * <ul>
4200      *     <li>Non-test-only DO/PO still can't be installed when there are accounts.
4201      *     <p>In order to make an apk test-only, add android:testOnly="true" to the
4202      *     &lt;application&gt; tag in the manifest.
4203      *
4204      *     <li>Test-only DO/PO can be installed even when there are accounts, as long as all the
4205      *     accounts have the {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} feature.
4206      *     Some authenticators claim to have any features, so to detect it, we also check
4207      *     {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} and disallow installing
4208      *     if any of the accounts have it.
4209      * </ul>
4210      */
4211     @SystemApi
4212     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED =
4213             "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED";
4214 
4215     /** @hide See {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} */
4216     @SystemApi
4217     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED =
4218             "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED";
4219 
4220     /**
4221      * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
4222      * manifest element, which declares that the module should be considered a required app for
4223      * managed users.
4224      * <p>Being declared as a required app prevents removal of this package during the
4225      * provisioning process.
4226      * @hide
4227      */
4228     @SystemApi
4229     public static final String REQUIRED_APP_MANAGED_USER = "android.app.REQUIRED_APP_MANAGED_USER";
4230 
4231     /**
4232      * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
4233      * manifest element, which declares that the module should be considered a required app for
4234      * managed devices.
4235      * <p>Being declared as a required app prevents removal of this package during the
4236      * provisioning process.
4237      * @hide
4238      */
4239     @SystemApi
4240     public static final String REQUIRED_APP_MANAGED_DEVICE =
4241             "android.app.REQUIRED_APP_MANAGED_DEVICE";
4242 
4243     /**
4244      * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
4245      * manifest element, which declares that the module should be considered a required app for
4246      * managed profiles.
4247      * <p>Being declared as a required app prevents removal of this package during the
4248      * provisioning process.
4249      * @hide
4250      */
4251     @SystemApi
4252     public static final String REQUIRED_APP_MANAGED_PROFILE =
4253             "android.app.REQUIRED_APP_MANAGED_PROFILE";
4254 
4255     /**
4256      * Called by an application that is administering the device to set the password restrictions it
4257      * is imposing. After setting this, the user will not be able to enter a new password that is
4258      * not at least as restrictive as what has been set. Note that the current password will remain
4259      * until the user has set a new one, so the change does not take place immediately. To prompt
4260      * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
4261      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after calling this method.
4262      * <p>
4263      * Quality constants are ordered so that higher values are more restrictive; thus the highest
4264      * requested quality constant (between the policy set here, the user's preference, and any other
4265      * considerations) is the one that is in effect.
4266      * <p>
4267      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4268      * password is always treated as empty.
4269      * <p>
4270      * The calling device admin must have requested
4271      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4272      * not, a security exception will be thrown.
4273      * <p>
4274      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4275      * {@link DevicePolicyManager} instance returned by
4276      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4277      * profile. Apps targeting {@link android.os.Build.VERSION_CODES#S} and above, with the
4278      * exception of a profile owner on an organization-owned device (as can be identified by
4279      * {@link #isOrganizationOwnedDeviceWithManagedProfile}), will get a
4280      * {@code IllegalArgumentException} when calling this method on the parent
4281      * {@link DevicePolicyManager} instance.
4282      *
4283      * <p><strong>Note:</strong> Specifying password requirements using this method clears the
4284      * password complexity requirements set using {@link #setRequiredPasswordComplexity(int)}.
4285      * If this method is called on the {@link DevicePolicyManager} instance returned by
4286      * {@link #getParentProfileInstance(ComponentName)}, then password complexity requirements
4287      * set on the primary {@link DevicePolicyManager} must be cleared first by calling
4288      * {@link #setRequiredPasswordComplexity} with {@link #PASSWORD_COMPLEXITY_NONE) first.
4289      *
4290      * <p><string>Note:</strong> this method is ignored on
4291      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4292      *
4293      * @deprecated Prefer using {@link #setRequiredPasswordComplexity(int)}, to require a password
4294      * that satisfies a complexity level defined by the platform, rather than specifying custom
4295      * password requirement.
4296      * Setting custom, overly-complicated password requirements leads to passwords that are hard
4297      * for users to remember and may not provide any security benefits given as Android uses
4298      * hardware-backed throttling to thwart online and offline brute-forcing of the device's
4299      * screen lock. Company-owned devices (fully-managed and organization-owned managed profile
4300      * devices) are able to continue using this method, though it is recommended that
4301      * {@link #setRequiredPasswordComplexity(int)} should be used instead.
4302      *
4303      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4304      * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED},
4305      *            {@link #PASSWORD_QUALITY_BIOMETRIC_WEAK},
4306      *            {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC},
4307      *            {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
4308      *            {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
4309      * @throws SecurityException if {@code admin} is not an active administrator, if {@code admin}
4310      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} or if the
4311      *             calling app is targeting {@link android.os.Build.VERSION_CODES#S} and above,
4312      *             and is calling the method the {@link DevicePolicyManager} instance returned by
4313      *             {@link #getParentProfileInstance(ComponentName)}.
4314      * @throws IllegalStateException if the caller is trying to set password quality on the parent
4315      *             {@link DevicePolicyManager} instance while password complexity was set on the
4316      *             primary {@link DevicePolicyManager} instance.
4317      */
4318     @Deprecated
setPasswordQuality(@onNull ComponentName admin, int quality)4319     public void setPasswordQuality(@NonNull ComponentName admin, int quality) {
4320         if (mService != null) {
4321             try {
4322                 mService.setPasswordQuality(admin, quality, mParentInstance);
4323             } catch (RemoteException e) {
4324                 throw e.rethrowFromSystemServer();
4325             }
4326         }
4327     }
4328 
4329     /**
4330      * Retrieve the current minimum password quality for a particular admin or all admins that set
4331      * restrictions on this user and its participating profiles. Restrictions on profiles that have
4332      * a separate challenge are not taken into account.
4333      *
4334      * <p>This method can be called on the {@link DevicePolicyManager} instance
4335      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4336      * restrictions on the parent profile.
4337      *
4338      * <p>Note: on devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
4339      * the password is always treated as empty.
4340      *
4341      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4342      *
4343      * @param admin The name of the admin component to check, or {@code null} to aggregate
4344      * all admins.
4345      */
4346     @Deprecated
getPasswordQuality(@ullable ComponentName admin)4347     public int getPasswordQuality(@Nullable ComponentName admin) {
4348         return getPasswordQuality(admin, myUserId());
4349     }
4350 
4351     /** @hide per-user version */
4352     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordQuality(@ullable ComponentName admin, int userHandle)4353     public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) {
4354         if (mService != null) {
4355             try {
4356                 return mService.getPasswordQuality(admin, userHandle, mParentInstance);
4357             } catch (RemoteException e) {
4358                 throw e.rethrowFromSystemServer();
4359             }
4360         }
4361         return PASSWORD_QUALITY_UNSPECIFIED;
4362     }
4363 
4364     /**
4365      * Called by an application that is administering the device to set the minimum allowed password
4366      * length. After setting this, the user will not be able to enter a new password that is not at
4367      * least as restrictive as what has been set. Note that the current password will remain until
4368      * the user has set a new one, so the change does not take place immediately. To prompt the user
4369      * for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
4370      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
4371      * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
4372      * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
4373      * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with
4374      * {@link #setPasswordQuality}. If an app targeting SDK level
4375      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
4376      * password quality to one of these values first, this method will throw
4377      * {@link IllegalStateException}.
4378      * <p>
4379      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4380      * password is always treated as empty.
4381      * <p>
4382      * The calling device admin must have requested
4383      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4384      * not, a security exception will be thrown.
4385      * <p>
4386      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4387      * {@link DevicePolicyManager} instance returned by
4388      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4389      * profile.
4390      *
4391      * <p><string>Note:</strong> this method is ignored on
4392      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4393      *
4394      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4395      *
4396      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4397      * @param length The new desired minimum password length. A value of 0 means there is no
4398      *     restriction.
4399      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4400      *     does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4401      * @throws IllegalStateException if the calling app is targeting SDK level
4402      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4403      *     quality requirement prior to calling this method.
4404      */
4405     @Deprecated
setPasswordMinimumLength(@onNull ComponentName admin, int length)4406     public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
4407         if (mService != null) {
4408             try {
4409                 mService.setPasswordMinimumLength(admin, length, mParentInstance);
4410             } catch (RemoteException e) {
4411                 throw e.rethrowFromSystemServer();
4412             }
4413         }
4414     }
4415 
4416     /**
4417      * Retrieve the current minimum password length for a particular admin or all admins that set
4418      * restrictions on this user and its participating profiles. Restrictions on profiles that have
4419      * a separate challenge are not taken into account.
4420      *
4421      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4422      * password is always treated as empty.
4423      *
4424      * <p>This method can be called on the {@link DevicePolicyManager} instance
4425      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4426      * restrictions on the parent profile.
4427      *
4428      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4429      *
4430      * @param admin The name of the admin component to check, or {@code null} to aggregate
4431      * all admins.
4432      */
4433     @Deprecated
getPasswordMinimumLength(@ullable ComponentName admin)4434     public int getPasswordMinimumLength(@Nullable ComponentName admin) {
4435         return getPasswordMinimumLength(admin, myUserId());
4436     }
4437 
4438     /** @hide per-user version */
4439     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLength(@ullable ComponentName admin, int userHandle)4440     public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) {
4441         if (mService != null) {
4442             try {
4443                 return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance);
4444             } catch (RemoteException e) {
4445                 throw e.rethrowFromSystemServer();
4446             }
4447         }
4448         return 0;
4449     }
4450 
4451     /**
4452      * Called by an application that is administering the device to set the minimum number of upper
4453      * case letters required in the password. After setting this, the user will not be able to enter
4454      * a new password that is not at least as restrictive as what has been set. Note that the
4455      * current password will remain until the user has set a new one, so the change does not take
4456      * place immediately. To prompt the user for a new password, use
4457      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
4458      * setting this value. This constraint is only imposed if the administrator has also requested
4459      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
4460      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
4461      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4462      * {@link IllegalStateException}. The default value is 0.
4463      * <p>
4464      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4465      * password is always treated as empty.
4466      * <p>
4467      * The calling device admin must have requested
4468      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4469      * not, a security exception will be thrown.
4470      * <p>
4471      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4472      * {@link DevicePolicyManager} instance returned by
4473      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4474      * profile.
4475      *
4476      * <p><string>Note:</strong> this method is ignored on
4477      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4478      *
4479      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4480      *
4481      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4482      * @param length The new desired minimum number of upper case letters required in the password.
4483      *            A value of 0 means there is no restriction.
4484      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4485      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4486      * @throws IllegalStateException if the calling app is targeting SDK level
4487      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4488      *     quality requirement prior to calling this method.
4489      */
4490     @Deprecated
setPasswordMinimumUpperCase(@onNull ComponentName admin, int length)4491     public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
4492         if (mService != null) {
4493             try {
4494                 mService.setPasswordMinimumUpperCase(admin, length, mParentInstance);
4495             } catch (RemoteException e) {
4496                 throw e.rethrowFromSystemServer();
4497             }
4498         }
4499     }
4500 
4501     /**
4502      * Retrieve the current number of upper case letters required in the password
4503      * for a particular admin or all admins that set restrictions on this user and
4504      * its participating profiles. Restrictions on profiles that have a separate challenge
4505      * are not taken into account.
4506      * This is the same value as set by
4507      * {@link #setPasswordMinimumUpperCase(ComponentName, int)}
4508      * and only applies when the password quality is
4509      * {@link #PASSWORD_QUALITY_COMPLEX}.
4510      *
4511      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4512      * password is always treated as empty.
4513      *
4514      * <p>This method can be called on the {@link DevicePolicyManager} instance
4515      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4516      * restrictions on the parent profile.
4517      *
4518      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4519      *
4520      * @param admin The name of the admin component to check, or {@code null} to
4521      *            aggregate all admins.
4522      * @return The minimum number of upper case letters required in the
4523      *         password.
4524      */
4525     @Deprecated
getPasswordMinimumUpperCase(@ullable ComponentName admin)4526     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) {
4527         return getPasswordMinimumUpperCase(admin, myUserId());
4528     }
4529 
4530     /** @hide per-user version */
4531     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumUpperCase(@ullable ComponentName admin, int userHandle)4532     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) {
4533         if (mService != null) {
4534             try {
4535                 return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance);
4536             } catch (RemoteException e) {
4537                 throw e.rethrowFromSystemServer();
4538             }
4539         }
4540         return 0;
4541     }
4542 
4543     /**
4544      * Called by an application that is administering the device to set the minimum number of lower
4545      * case letters required in the password. After setting this, the user will not be able to enter
4546      * a new password that is not at least as restrictive as what has been set. Note that the
4547      * current password will remain until the user has set a new one, so the change does not take
4548      * place immediately. To prompt the user for a new password, use
4549      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
4550      * setting this value. This constraint is only imposed if the administrator has also requested
4551      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
4552      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
4553      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4554      * {@link IllegalStateException}. The default value is 0.
4555      * <p>
4556      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4557      * password is always treated as empty.
4558      * <p>
4559      * The calling device admin must have requested
4560      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4561      * not, a security exception will be thrown.
4562      * <p>
4563      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4564      * {@link DevicePolicyManager} instance returned by
4565      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4566      * profile.
4567      *
4568      * <p><string>Note:</strong> this method is ignored on
4569      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4570      *
4571      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4572      *
4573      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4574      * @param length The new desired minimum number of lower case letters required in the password.
4575      *            A value of 0 means there is no restriction.
4576      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4577      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4578      * @throws IllegalStateException if the calling app is targeting SDK level
4579      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4580      *     quality requirement prior to calling this method.
4581      */
4582     @Deprecated
setPasswordMinimumLowerCase(@onNull ComponentName admin, int length)4583     public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
4584         if (mService != null) {
4585             try {
4586                 mService.setPasswordMinimumLowerCase(admin, length, mParentInstance);
4587             } catch (RemoteException e) {
4588                 throw e.rethrowFromSystemServer();
4589             }
4590         }
4591     }
4592 
4593     /**
4594      * Retrieve the current number of lower case letters required in the password
4595      * for a particular admin or all admins that set restrictions on this user
4596      * and its participating profiles. Restrictions on profiles that have
4597      * a separate challenge are not taken into account.
4598      * This is the same value as set by
4599      * {@link #setPasswordMinimumLowerCase(ComponentName, int)}
4600      * and only applies when the password quality is
4601      * {@link #PASSWORD_QUALITY_COMPLEX}.
4602      *
4603      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4604      * password is always treated as empty.
4605      *
4606      * <p>This method can be called on the {@link DevicePolicyManager} instance
4607      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4608      * restrictions on the parent profile.
4609      *
4610      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4611      *
4612      * @param admin The name of the admin component to check, or {@code null} to
4613      *            aggregate all admins.
4614      * @return The minimum number of lower case letters required in the
4615      *         password.
4616      */
4617     @Deprecated
getPasswordMinimumLowerCase(@ullable ComponentName admin)4618     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) {
4619         return getPasswordMinimumLowerCase(admin, myUserId());
4620     }
4621 
4622     /** @hide per-user version */
4623     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLowerCase(@ullable ComponentName admin, int userHandle)4624     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) {
4625         if (mService != null) {
4626             try {
4627                 return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance);
4628             } catch (RemoteException e) {
4629                 throw e.rethrowFromSystemServer();
4630             }
4631         }
4632         return 0;
4633     }
4634 
4635     /**
4636      * Called by an application that is administering the device to set the minimum number of
4637      * letters required in the password. After setting this, the user will not be able to enter a
4638      * new password that is not at least as restrictive as what has been set. Note that the current
4639      * password will remain until the user has set a new one, so the change does not take place
4640      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
4641      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
4642      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
4643      * {@link #setPasswordQuality}. If an app targeting SDK level
4644      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
4645      * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4646      * {@link IllegalStateException}. The default value is 1.
4647      * <p>
4648      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4649      * password is always treated as empty.
4650      * <p>
4651      * The calling device admin must have requested
4652      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4653      * not, a security exception will be thrown.
4654      * <p>
4655      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4656      * {@link DevicePolicyManager} instance returned by
4657      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4658      * profile.
4659      *
4660      * <p><string>Note:</strong> this method is ignored on
4661      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4662      *
4663      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4664      *
4665      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4666      * @param length The new desired minimum number of letters required in the password. A value of
4667      *            0 means there is no restriction.
4668      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4669      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4670      * @throws IllegalStateException if the calling app is targeting SDK level
4671      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4672      *     quality requirement prior to calling this method.
4673      */
4674     @Deprecated
setPasswordMinimumLetters(@onNull ComponentName admin, int length)4675     public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
4676         if (mService != null) {
4677             try {
4678                 mService.setPasswordMinimumLetters(admin, length, mParentInstance);
4679             } catch (RemoteException e) {
4680                 throw e.rethrowFromSystemServer();
4681             }
4682         }
4683     }
4684 
4685     /**
4686      * Retrieve the current number of letters required in the password
4687      * for a particular admin or all admins that set restrictions on this user
4688      * and its participating profiles. Restrictions on profiles that have
4689      * a separate challenge are not taken into account.
4690      * This is the same value as set by
4691      * {@link #setPasswordMinimumLetters(ComponentName, int)}
4692      * and only applies when the password quality is
4693      * {@link #PASSWORD_QUALITY_COMPLEX}.
4694      *
4695      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4696      * password is always treated as empty.
4697      *
4698      * <p>This method can be called on the {@link DevicePolicyManager} instance
4699      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4700      * restrictions on the parent profile.
4701      *
4702      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4703      *
4704      * @param admin The name of the admin component to check, or {@code null} to
4705      *            aggregate all admins.
4706      * @return The minimum number of letters required in the password.
4707      */
4708     @Deprecated
getPasswordMinimumLetters(@ullable ComponentName admin)4709     public int getPasswordMinimumLetters(@Nullable ComponentName admin) {
4710         return getPasswordMinimumLetters(admin, myUserId());
4711     }
4712 
4713     /** @hide per-user version */
4714     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLetters(@ullable ComponentName admin, int userHandle)4715     public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) {
4716         if (mService != null) {
4717             try {
4718                 return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance);
4719             } catch (RemoteException e) {
4720                 throw e.rethrowFromSystemServer();
4721             }
4722         }
4723         return 0;
4724     }
4725 
4726     /**
4727      * Called by an application that is administering the device to set the minimum number of
4728      * numerical digits required in the password. After setting this, the user will not be able to
4729      * enter a new password that is not at least as restrictive as what has been set. Note that the
4730      * current password will remain until the user has set a new one, so the change does not take
4731      * place immediately. To prompt the user for a new password, use
4732      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
4733      * setting this value. This constraint is only imposed if the administrator has also requested
4734      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
4735      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
4736      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4737      * {@link IllegalStateException}. The default value is 1.
4738      * <p>
4739      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4740      * password is always treated as empty.
4741      * <p>
4742      * The calling device admin must have requested
4743      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4744      * not, a security exception will be thrown.
4745      * <p>
4746      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4747      * {@link DevicePolicyManager} instance returned by
4748      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4749      * profile.
4750      *
4751      * <p><string>Note:</strong> this method is ignored on
4752      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4753      *
4754      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4755      *
4756      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4757      * @param length The new desired minimum number of numerical digits required in the password. A
4758      *            value of 0 means there is no restriction.
4759      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4760      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4761      * @throws IllegalStateException if the calling app is targeting SDK level
4762      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4763      *     quality requirement prior to calling this method.
4764      */
4765     @Deprecated
setPasswordMinimumNumeric(@onNull ComponentName admin, int length)4766     public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
4767         if (mService != null) {
4768             try {
4769                 mService.setPasswordMinimumNumeric(admin, length, mParentInstance);
4770             } catch (RemoteException e) {
4771                 throw e.rethrowFromSystemServer();
4772             }
4773         }
4774     }
4775 
4776     /**
4777      * Retrieve the current number of numerical digits required in the password
4778      * for a particular admin or all admins that set restrictions on this user
4779      * and its participating profiles. Restrictions on profiles that have
4780      * a separate challenge are not taken into account.
4781      * This is the same value as set by
4782      * {@link #setPasswordMinimumNumeric(ComponentName, int)}
4783      * and only applies when the password quality is
4784      * {@link #PASSWORD_QUALITY_COMPLEX}.
4785      *
4786      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4787      * password is always treated as empty.
4788      *
4789      * <p>This method can be called on the {@link DevicePolicyManager} instance
4790      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4791      * restrictions on the parent profile.
4792      *
4793      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4794      *
4795      * @param admin The name of the admin component to check, or {@code null} to
4796      *            aggregate all admins.
4797      * @return The minimum number of numerical digits required in the password.
4798      */
4799     @Deprecated
getPasswordMinimumNumeric(@ullable ComponentName admin)4800     public int getPasswordMinimumNumeric(@Nullable ComponentName admin) {
4801         return getPasswordMinimumNumeric(admin, myUserId());
4802     }
4803 
4804     /** @hide per-user version */
4805     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumNumeric(@ullable ComponentName admin, int userHandle)4806     public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) {
4807         if (mService != null) {
4808             try {
4809                 return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance);
4810             } catch (RemoteException e) {
4811                 throw e.rethrowFromSystemServer();
4812             }
4813         }
4814         return 0;
4815     }
4816 
4817     /**
4818      * Called by an application that is administering the device to set the minimum number of
4819      * symbols required in the password. After setting this, the user will not be able to enter a
4820      * new password that is not at least as restrictive as what has been set. Note that the current
4821      * password will remain until the user has set a new one, so the change does not take place
4822      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
4823      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
4824      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
4825      * {@link #setPasswordQuality}. If an app targeting SDK level
4826      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
4827      * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4828      * {@link IllegalStateException}. The default value is 1.
4829      * <p>
4830      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4831      * password is always treated as empty.
4832      * <p>
4833      * The calling device admin must have requested
4834      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4835      * not, a security exception will be thrown.
4836      * <p>
4837      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4838      * {@link DevicePolicyManager} instance returned by
4839      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4840      * profile.
4841      *
4842      * <p><string>Note:</strong> this method is ignored on
4843      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4844      *
4845      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4846      *
4847      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4848      * @param length The new desired minimum number of symbols required in the password. A value of
4849      *            0 means there is no restriction.
4850      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4851      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4852      * @throws IllegalStateException if the calling app is targeting SDK level
4853      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4854      *     quality requirement prior to calling this method.
4855      */
4856     @Deprecated
setPasswordMinimumSymbols(@onNull ComponentName admin, int length)4857     public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
4858         if (mService != null) {
4859             try {
4860                 mService.setPasswordMinimumSymbols(admin, length, mParentInstance);
4861             } catch (RemoteException e) {
4862                 throw e.rethrowFromSystemServer();
4863             }
4864         }
4865     }
4866 
4867     /**
4868      * Retrieve the current number of symbols required in the password
4869      * for a particular admin or all admins that set restrictions on this user
4870      * and its participating profiles. Restrictions on profiles that have
4871      * a separate challenge are not taken into account. This is the same value as
4872      * set by {@link #setPasswordMinimumSymbols(ComponentName, int)}
4873      * and only applies when the password quality is
4874      * {@link #PASSWORD_QUALITY_COMPLEX}.
4875      *
4876      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4877      * password is always treated as empty.
4878      *
4879      * <p>This method can be called on the {@link DevicePolicyManager} instance
4880      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4881      * restrictions on the parent profile.
4882      *
4883      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4884      *
4885      * @param admin The name of the admin component to check, or {@code null} to
4886      *            aggregate all admins.
4887      * @return The minimum number of symbols required in the password.
4888      */
4889     @Deprecated
getPasswordMinimumSymbols(@ullable ComponentName admin)4890     public int getPasswordMinimumSymbols(@Nullable ComponentName admin) {
4891         return getPasswordMinimumSymbols(admin, myUserId());
4892     }
4893 
4894     /** @hide per-user version */
4895     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumSymbols(@ullable ComponentName admin, int userHandle)4896     public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) {
4897         if (mService != null) {
4898             try {
4899                 return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance);
4900             } catch (RemoteException e) {
4901                 throw e.rethrowFromSystemServer();
4902             }
4903         }
4904         return 0;
4905     }
4906 
4907     /**
4908      * Called by an application that is administering the device to set the minimum number of
4909      * non-letter characters (numerical digits or symbols) required in the password. After setting
4910      * this, the user will not be able to enter a new password that is not at least as restrictive
4911      * as what has been set. Note that the current password will remain until the user has set a new
4912      * one, so the change does not take place immediately. To prompt the user for a new password,
4913      * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
4914      * setting this value. This constraint is only imposed if the administrator has also requested
4915      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
4916      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
4917      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4918      * {@link IllegalStateException}. The default value is 0.
4919      * <p>
4920      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4921      * password is always treated as empty.
4922      * <p>
4923      * The calling device admin must have requested
4924      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4925      * not, a security exception will be thrown.
4926      * <p>
4927      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4928      * {@link DevicePolicyManager} instance returned by
4929      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4930      * profile.
4931      *
4932      * <p><string>Note:</strong> this method is ignored on
4933      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4934      *
4935      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4936      *
4937      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4938      * @param length The new desired minimum number of letters required in the password. A value of
4939      *            0 means there is no restriction.
4940      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4941      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4942      * @throws IllegalStateException if the calling app is targeting SDK level
4943      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4944      *     quality requirement prior to calling this method.
4945      */
4946     @Deprecated
setPasswordMinimumNonLetter(@onNull ComponentName admin, int length)4947     public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
4948         if (mService != null) {
4949             try {
4950                 mService.setPasswordMinimumNonLetter(admin, length, mParentInstance);
4951             } catch (RemoteException e) {
4952                 throw e.rethrowFromSystemServer();
4953             }
4954         }
4955     }
4956 
4957     /**
4958      * Retrieve the current number of non-letter characters required in the password
4959      * for a particular admin or all admins that set restrictions on this user
4960      * and its participating profiles. Restrictions on profiles that have
4961      * a separate challenge are not taken into account.
4962      * This is the same value as set by
4963      * {@link #setPasswordMinimumNonLetter(ComponentName, int)}
4964      * and only applies when the password quality is
4965      * {@link #PASSWORD_QUALITY_COMPLEX}.
4966      *
4967      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4968      * password is always treated as empty.
4969      *
4970      * <p>This method can be called on the {@link DevicePolicyManager} instance
4971      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4972      * restrictions on the parent profile.
4973      *
4974      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4975      *
4976      * @param admin The name of the admin component to check, or {@code null} to
4977      *            aggregate all admins.
4978      * @return The minimum number of letters required in the password.
4979      */
4980     @Deprecated
getPasswordMinimumNonLetter(@ullable ComponentName admin)4981     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) {
4982         return getPasswordMinimumNonLetter(admin, myUserId());
4983     }
4984 
4985     /** @hide per-user version */
4986     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumNonLetter(@ullable ComponentName admin, int userHandle)4987     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) {
4988         if (mService != null) {
4989             try {
4990                 return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance);
4991             } catch (RemoteException e) {
4992                 throw e.rethrowFromSystemServer();
4993             }
4994         }
4995         return 0;
4996     }
4997 
4998     /**
4999      * Returns minimum PasswordMetrics that satisfies all admin policies.
5000      *
5001      * @hide
5002      */
getPasswordMinimumMetrics(@serIdInt int userHandle)5003     public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle) {
5004         return getPasswordMinimumMetrics(userHandle, false);
5005     }
5006 
5007     /**
5008      * Returns minimum PasswordMetrics that satisfies all admin policies.
5009      * If requested, only consider device-wide admin policies and ignore policies set on the
5010      * managed profile instance (as if the managed profile had separate work challenge).
5011      *
5012      * @hide
5013      */
getPasswordMinimumMetrics(@serIdInt int userHandle, boolean deviceWideOnly)5014     public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle,
5015             boolean deviceWideOnly) {
5016         if (mService != null) {
5017             try {
5018                 return mService.getPasswordMinimumMetrics(userHandle, deviceWideOnly);
5019             } catch (RemoteException e) {
5020                 throw e.rethrowFromSystemServer();
5021             }
5022         }
5023         return null;
5024     }
5025 
5026     /**
5027      * Called by an application that is administering the device to set the length of the password
5028      * history. After setting this, the user will not be able to enter a new password that is the
5029      * same as any password in the history. Note that the current password will remain until the
5030      * user has set a new one, so the change does not take place immediately. To prompt the user for
5031      * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
5032      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value.
5033      * <p>
5034      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5035      * password history length is always 0.
5036      * <p>
5037      * The calling device admin must have requested
5038      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
5039      * not, a security exception will be thrown.
5040      * <p>
5041      * This method can be called on the {@link DevicePolicyManager} instance returned by
5042      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5043      * profile.
5044      *
5045      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5046      * @param length The new desired length of password history. A value of 0 means there is no
5047      *            restriction.
5048      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
5049      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
5050      */
5051     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setPasswordHistoryLength(@onNull ComponentName admin, int length)5052     public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
5053         if (mService != null) {
5054             try {
5055                 mService.setPasswordHistoryLength(admin, length, mParentInstance);
5056             } catch (RemoteException e) {
5057                 throw e.rethrowFromSystemServer();
5058             }
5059         }
5060     }
5061 
5062     /**
5063      * Called by a device admin to set the password expiration timeout. Calling this method will
5064      * restart the countdown for password expiration for the given admin, as will changing the
5065      * device password (for all admins).
5066      * <p>
5067      * The provided timeout is the time delta in ms and will be added to the current time. For
5068      * example, to have the password expire 5 days from now, timeout would be 5 * 86400 * 1000 =
5069      * 432000000 ms for timeout.
5070      * <p>
5071      * To disable password expiration, a value of 0 may be used for timeout.
5072      * <p>
5073      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5074      * password expiration is always disabled.
5075      * <p>
5076      * The calling device admin must have requested
5077      * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this method; if it has
5078      * not, a security exception will be thrown.
5079      * <p>
5080      * Note that setting the password will automatically reset the expiration time for all active
5081      * admins. Active admins do not need to explicitly call this method in that case.
5082      * <p>
5083      * This method can be called on the {@link DevicePolicyManager} instance returned by
5084      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5085      * profile.
5086      *
5087      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5088      * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 means
5089      *            there is no restriction (unlimited).
5090      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
5091      *             does not use {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD}
5092      */
5093     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setPasswordExpirationTimeout(@onNull ComponentName admin, long timeout)5094     public void setPasswordExpirationTimeout(@NonNull ComponentName admin, long timeout) {
5095         if (mService != null) {
5096             try {
5097                 mService.setPasswordExpirationTimeout(admin, timeout, mParentInstance);
5098             } catch (RemoteException e) {
5099                 throw e.rethrowFromSystemServer();
5100             }
5101         }
5102     }
5103 
5104     /**
5105      * Get the password expiration timeout for the given admin. The expiration timeout is the
5106      * recurring expiration timeout provided in the call to
5107      * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
5108      * aggregate of all participating policy administrators if {@code admin} is null. Admins that
5109      * have set restrictions on profiles that have a separate challenge are not taken into account.
5110      *
5111      * <p>This method can be called on the {@link DevicePolicyManager} instance
5112      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5113      * restrictions on the parent profile.
5114      *
5115      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5116      * password expiration is always disabled and this method always returns 0.
5117      *
5118      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
5119      * @return The timeout for the given admin or the minimum of all timeouts
5120      */
5121     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordExpirationTimeout(@ullable ComponentName admin)5122     public long getPasswordExpirationTimeout(@Nullable ComponentName admin) {
5123         if (mService != null) {
5124             try {
5125                 return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance);
5126             } catch (RemoteException e) {
5127                 throw e.rethrowFromSystemServer();
5128             }
5129         }
5130         return 0;
5131     }
5132 
5133     /**
5134      * Get the current password expiration time for a particular admin or all admins that set
5135      * restrictions on this user and its participating profiles. Restrictions on profiles that have
5136      * a separate challenge are not taken into account. If admin is {@code null}, then a composite
5137      * of all expiration times is returned - which will be the minimum of all of them.
5138      *
5139      * <p>This method can be called on the {@link DevicePolicyManager} instance
5140      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5141      * the password expiration for the parent profile.
5142      *
5143      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5144      * password expiration is always disabled and this method always returns 0.
5145      *
5146      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
5147      * @return The password expiration time, in milliseconds since epoch.
5148      */
5149     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordExpiration(@ullable ComponentName admin)5150     public long getPasswordExpiration(@Nullable ComponentName admin) {
5151         if (mService != null) {
5152             try {
5153                 return mService.getPasswordExpiration(admin, myUserId(), mParentInstance);
5154             } catch (RemoteException e) {
5155                 throw e.rethrowFromSystemServer();
5156             }
5157         }
5158         return 0;
5159     }
5160 
5161     /**
5162      * Retrieve the current password history length for a particular admin or all admins that
5163      * set restrictions on this user and its participating profiles. Restrictions on profiles that
5164      * have a separate challenge are not taken into account.
5165      *
5166      * <p>This method can be called on the {@link DevicePolicyManager} instance
5167      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5168      * restrictions on the parent profile.
5169      *
5170      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5171      * password history length is always 0.
5172      *
5173      * @param admin The name of the admin component to check, or {@code null} to aggregate
5174      * all admins.
5175      * @return The length of the password history
5176      */
5177     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordHistoryLength(@ullable ComponentName admin)5178     public int getPasswordHistoryLength(@Nullable ComponentName admin) {
5179         return getPasswordHistoryLength(admin, myUserId());
5180     }
5181 
5182     /** @hide per-user version */
5183     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
5184     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordHistoryLength(@ullable ComponentName admin, int userHandle)5185     public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) {
5186         if (mService != null) {
5187             try {
5188                 return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance);
5189             } catch (RemoteException e) {
5190                 throw e.rethrowFromSystemServer();
5191             }
5192         }
5193         return 0;
5194     }
5195 
5196     /**
5197      * Return the maximum password length that the device supports for a
5198      * particular password quality.
5199      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5200      * password is always empty and this method always returns 0.
5201      * @param quality The quality being interrogated.
5202      * @return Returns the maximum length that the user can enter.
5203      */
getPasswordMaximumLength(int quality)5204     public int getPasswordMaximumLength(int quality) {
5205         PackageManager pm = mContext.getPackageManager();
5206         if (!pm.hasSystemFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)) {
5207             return 0;
5208         }
5209         return MAX_PASSWORD_LENGTH;
5210     }
5211 
5212     /**
5213      * Determines whether the calling user's current password meets policy requirements
5214      * (e.g. quality, minimum length). The user must be unlocked to perform this check.
5215      *
5216      * <p>Policy requirements which affect this check can be set by admins of the user, but also
5217      * by the admin of a managed profile associated with the calling user (when the managed profile
5218      * doesn't have a separate work challenge). When a managed profile has a separate work
5219      * challenge, its policy requirements only affect the managed profile.
5220      *
5221      * <p>Depending on the user, this method checks the policy requirement against one of the
5222      * following passwords:
5223      * <ul>
5224      * <li>For the primary user or secondary users: the personal keyguard password.
5225      * <li>For managed profiles: a work challenge if set, otherwise the parent user's personal
5226      *     keyguard password.
5227      * <ul/>
5228      * In other words, it's always checking the requirement against the password that is protecting
5229      * the calling user.
5230      *
5231      * <p>Note that this method considers all policy requirements targeting the password in
5232      * question. For example a profile owner might set a requirement on the parent profile i.e.
5233      * personal keyguard but not on the profile itself. When the device has a weak personal keyguard
5234      * password and no separate work challenge, calling this method will return {@code false}
5235      * despite the profile owner not setting a policy on the profile itself. This is because the
5236      * profile's current password is the personal keyguard password, and it does not meet all policy
5237      * requirements.
5238      *
5239      * <p>Device admins must request {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} before
5240      * calling this method. Note, this policy type is deprecated for device admins in Android 9.0
5241      * (API level 28) or higher.
5242      *
5243      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
5244      * {@link #getParentProfileInstance(ComponentName)} in order to determine if the password set on
5245      * the parent profile is sufficient.
5246      *
5247      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5248      * password is always treated as empty - i.e. this method will always return false on such
5249      * devices, provided any password requirements were set.
5250      *
5251      * @return {@code true} if the password meets the policy requirements, {@code false} otherwise
5252      * @throws SecurityException if the calling application isn't an active admin that uses
5253      *     {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
5254      * @throws IllegalStateException if the user isn't unlocked
5255      */
isActivePasswordSufficient()5256     public boolean isActivePasswordSufficient() {
5257         if (mService != null) {
5258             try {
5259                 return mService.isActivePasswordSufficient(myUserId(), mParentInstance);
5260             } catch (RemoteException e) {
5261                 throw e.rethrowFromSystemServer();
5262             }
5263         }
5264         return false;
5265     }
5266 
5267     /**
5268      * Called by profile owner of a managed profile to determine whether the current device password
5269      * meets policy requirements set explicitly device-wide.
5270      * <p> This API is similar to {@link #isActivePasswordSufficient()}, with two notable
5271      * differences:
5272      * <ul>
5273      * <li>this API always targets the device password. As a result it should always be called on
5274      *   the {@link #getParentProfileInstance(ComponentName)} instance.</li>
5275      * <li>password policy requirement set on the managed profile is not taken into consideration
5276      *   by this API, even if the device currently does not have a separate work challenge set.</li>
5277      * </ul>
5278      *
5279      * <p>This API is designed to facilite progressive password enrollment flows when the DPC
5280      * imposes both device and profile password policies. DPC applies profile password policy by
5281      * calling {@link #setPasswordQuality(ComponentName, int)} or
5282      * {@link #setRequiredPasswordComplexity} on the regular {@link DevicePolicyManager} instance,
5283      * while it applies device-wide policy by calling {@link #setRequiredPasswordComplexity} on the
5284      * {@link #getParentProfileInstance(ComponentName)} instance. The DPC can utilize this check to
5285      * guide the user to set a device password first taking into consideration the device-wide
5286      * policy only, and then prompt the user to either upgrade it to be fully compliant, or enroll a
5287      * separate work challenge to satisfy the profile password policy only.
5288      *
5289      * <p>The device user must be unlocked (@link {@link UserManager#isUserUnlocked(UserHandle)})
5290      * to perform this check.
5291      *
5292      * @return {@code true} if the device password meets explicit requirement set on it,
5293      *   {@code false} otherwise.
5294      * @throws SecurityException if the calling application is not a profile owner of a managed
5295      *   profile, or if this API is not called on the parent DevicePolicyManager instance.
5296      * @throws IllegalStateException if the user isn't unlocked
5297      * @see #EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY
5298      */
isActivePasswordSufficientForDeviceRequirement()5299     public boolean isActivePasswordSufficientForDeviceRequirement() {
5300         if (!mParentInstance) {
5301             throw new SecurityException("only callable on the parent instance");
5302         }
5303         if (mService != null) {
5304             try {
5305                 return mService.isActivePasswordSufficientForDeviceRequirement();
5306             } catch (RemoteException e) {
5307                 throw e.rethrowFromSystemServer();
5308             }
5309         }
5310         return false;
5311     }
5312 
5313     /**
5314      * Returns how complex the current user's screen lock is.
5315      *
5316      * <p>Note that when called from a profile which uses an unified challenge with its parent, the
5317      * screen lock complexity of the parent will be returned.
5318      *
5319      * <p>Apps need the {@link permission#REQUEST_PASSWORD_COMPLEXITY} permission to call this
5320      * method. On Android {@link android.os.Build.VERSION_CODES#S} and above, the calling
5321      * application does not need this permission if it is a device owner or a profile owner.
5322      *
5323      * <p>This method can be called on the {@link DevicePolicyManager} instance
5324      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5325      * restrictions on the parent profile.
5326      *
5327      * @throws IllegalStateException if the user is not unlocked.
5328      * @throws SecurityException     if the calling application does not have the permission
5329      *                               {@link permission#REQUEST_PASSWORD_COMPLEXITY}, and is not a
5330      *                               device owner or a profile owner.
5331      */
5332     @PasswordComplexity
5333     @RequiresPermission(android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY)
getPasswordComplexity()5334     public int getPasswordComplexity() {
5335         if (mService == null) {
5336             return PASSWORD_COMPLEXITY_NONE;
5337         }
5338 
5339         try {
5340             return mService.getPasswordComplexity(mParentInstance);
5341         } catch (RemoteException e) {
5342             throw e.rethrowFromSystemServer();
5343         }
5344     }
5345 
5346     /**
5347      * Sets a minimum password complexity requirement for the user's screen lock.
5348      * The complexity level is one of the pre-defined levels, and the user is unable to set a
5349      * password with a lower complexity level.
5350      *
5351      * <p>Note that when called on a profile which uses an unified challenge with its parent, the
5352      * complexity would apply to the unified challenge.
5353      *
5354      * <p>This method can be called on the {@link DevicePolicyManager} instance
5355      * returned by {@link #getParentProfileInstance(ComponentName)} in order to set
5356      * restrictions on the parent profile.
5357      *
5358      * <p><strong>Note:</strong> Specifying password requirements using this method clears any
5359      * password requirements set using the obsolete {@link #setPasswordQuality(ComponentName, int)}
5360      * and any of its associated methods.
5361      * Additionally, if there are password requirements set using the obsolete
5362      * {@link #setPasswordQuality(ComponentName, int)} on the parent {@code DevicePolicyManager}
5363      * instance, they must be cleared by calling {@link #setPasswordQuality(ComponentName, int)}
5364      * with {@link #PASSWORD_QUALITY_UNSPECIFIED} on that instance prior to setting complexity
5365      * requirement for the managed profile.
5366      *
5367      * @throws SecurityException if the calling application is not a device owner or a profile
5368      * owner.
5369      * @throws IllegalArgumentException if the complexity level is not one of the four above.
5370      * @throws IllegalStateException if the caller is trying to set password complexity while there
5371      * are password requirements specified using {@link #setPasswordQuality(ComponentName, int)}
5372      * on the parent {@code DevicePolicyManager} instance.
5373      */
setRequiredPasswordComplexity(@asswordComplexity int passwordComplexity)5374     public void setRequiredPasswordComplexity(@PasswordComplexity int passwordComplexity) {
5375         if (mService == null) {
5376             return;
5377         }
5378 
5379         try {
5380             mService.setRequiredPasswordComplexity(passwordComplexity, mParentInstance);
5381         } catch (RemoteException e) {
5382             throw e.rethrowFromSystemServer();
5383         }
5384     }
5385 
5386 
5387     /**
5388      * Gets the password complexity requirement set by {@link #setRequiredPasswordComplexity(int)},
5389      * for the current user.
5390      *
5391      * <p>The difference between this method and {@link #getPasswordComplexity()} is that this
5392      * method simply returns the value set by {@link #setRequiredPasswordComplexity(int)} while
5393      * {@link #getPasswordComplexity()} returns the complexity of the actual password.
5394      *
5395      * <p>This method can be called on the {@link DevicePolicyManager} instance
5396      * returned by {@link #getParentProfileInstance(ComponentName)} in order to get
5397      * restrictions on the parent profile.
5398      *
5399      * @throws SecurityException if the calling application is not a device owner or a profile
5400      * owner.
5401      */
5402     @PasswordComplexity
getRequiredPasswordComplexity()5403     public int getRequiredPasswordComplexity() {
5404         if (mService == null) {
5405             return PASSWORD_COMPLEXITY_NONE;
5406         }
5407 
5408         try {
5409             return mService.getRequiredPasswordComplexity(mParentInstance);
5410         } catch (RemoteException e) {
5411             throw e.rethrowFromSystemServer();
5412         }
5413     }
5414 
5415     /**
5416      * Returns the password complexity that applies to this user, aggregated from other users if
5417      * necessary (for example, if the DPC has set password complexity requirements on the parent
5418      * profile DPM instance of a managed profile user, they would apply to the primary user on the
5419      * device).
5420      * @hide
5421      */
5422     @PasswordComplexity
getAggregatedPasswordComplexityForUser(int userId)5423     public int getAggregatedPasswordComplexityForUser(int userId) {
5424         return getAggregatedPasswordComplexityForUser(userId, false);
5425     }
5426 
5427     /**
5428      * Returns the password complexity that applies to this user, aggregated from other users if
5429      * necessary (for example, if the DPC has set password complexity requirements on the parent
5430      * profile DPM instance of a managed profile user, they would apply to the primary user on the
5431      * device). If {@code deviceWideOnly} is {@code true}, ignore policies set on the
5432      * managed profile DPM instance (as if the managed profile had separate work challenge).
5433      * @hide
5434      */
5435     @PasswordComplexity
getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly)5436     public int getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly) {
5437         if (mService == null) {
5438             return PASSWORD_COMPLEXITY_NONE;
5439         }
5440 
5441         try {
5442             return mService.getAggregatedPasswordComplexityForUser(userId, deviceWideOnly);
5443         } catch (RemoteException e) {
5444             throw e.rethrowFromSystemServer();
5445         }
5446     }
5447 
5448 
5449     /**
5450      * When called by a profile owner of a managed profile returns true if the profile uses unified
5451      * challenge with its parent user.
5452      *
5453      * <strong>Note</strong>: This method is not concerned with password quality and will return
5454      * false if the profile has empty password as a separate challenge.
5455      *
5456      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5457      * @throws SecurityException if {@code admin} is not a profile owner of a managed profile.
5458      * @see UserManager#DISALLOW_UNIFIED_PASSWORD
5459      */
isUsingUnifiedPassword(@onNull ComponentName admin)5460     public boolean isUsingUnifiedPassword(@NonNull ComponentName admin) {
5461         throwIfParentInstance("isUsingUnifiedPassword");
5462         if (mService != null) {
5463             try {
5464                 return mService.isUsingUnifiedPassword(admin);
5465             } catch (RemoteException e) {
5466                 throw e.rethrowFromSystemServer();
5467             }
5468         }
5469         return true;
5470     }
5471 
5472     /**
5473      * Returns whether the given user's credential will be sufficient for all password policy
5474      * requirement, once the user's profile has switched to unified challenge.
5475      *
5476      * <p>This is different from {@link #isActivePasswordSufficient()} since once the profile
5477      * switches to unified challenge, policies set explicitly on the profile will start to affect
5478      * the parent user.
5479      * @param userHandle the user whose password requirement will be checked
5480      * @param profileUser the profile user whose lockscreen challenge will be unified.
5481      * @hide
5482      */
isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser)5483     public boolean isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser) {
5484         if (mService != null) {
5485             try {
5486                 return mService.isPasswordSufficientAfterProfileUnification(userHandle,
5487                         profileUser);
5488             } catch (RemoteException e) {
5489                 throw e.rethrowFromSystemServer();
5490             }
5491         }
5492         return false;
5493     }
5494     /**
5495      * Retrieve the number of times the user has failed at entering a password since that last
5496      * successful password entry.
5497      * <p>
5498      * This method can be called on the {@link DevicePolicyManager} instance returned by
5499      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the number of failed
5500      * password attemts for the parent user.
5501      * <p>
5502      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
5503      * to be able to call this method; if it has not, a security exception will be thrown.
5504      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5505      * password is always empty and this method always returns 0.
5506      *
5507      * @return The number of times user has entered an incorrect password since the last correct
5508      *         password entry.
5509      * @throws SecurityException if the calling application does not own an active administrator
5510      *             that uses {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
5511      */
5512     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getCurrentFailedPasswordAttempts()5513     public int getCurrentFailedPasswordAttempts() {
5514         return getCurrentFailedPasswordAttempts(myUserId());
5515     }
5516 
5517     /**
5518      * Retrieve the number of times the given user has failed at entering a
5519      * password since that last successful password entry.
5520      *
5521      * <p>The calling device admin must have requested
5522      * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call this method; if it has
5523      * not and it is not the system uid, a security exception will be thrown.
5524      *
5525      * @hide
5526      */
5527     @UnsupportedAppUsage
getCurrentFailedPasswordAttempts(int userHandle)5528     public int getCurrentFailedPasswordAttempts(int userHandle) {
5529         if (mService != null) {
5530             try {
5531                 return mService.getCurrentFailedPasswordAttempts(userHandle, mParentInstance);
5532             } catch (RemoteException e) {
5533                 throw e.rethrowFromSystemServer();
5534             }
5535         }
5536         return -1;
5537     }
5538 
5539     /**
5540      * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set.
5541      *
5542      * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set.
5543      * @hide
5544      */
getDoNotAskCredentialsOnBoot()5545     public boolean getDoNotAskCredentialsOnBoot() {
5546         if (mService != null) {
5547             try {
5548                 return mService.getDoNotAskCredentialsOnBoot();
5549             } catch (RemoteException e) {
5550                 throw e.rethrowFromSystemServer();
5551             }
5552         }
5553         return false;
5554     }
5555 
5556     /**
5557      * Setting this to a value greater than zero enables a built-in policy that will perform a
5558      * device or profile wipe after too many incorrect device-unlock passwords have been entered.
5559      * This built-in policy combines watching for failed passwords and wiping the device, and
5560      * requires that you request both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
5561      * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
5562      * <p>
5563      * When this policy is set by a device owner, profile owner of an organization-owned device or
5564      * an admin on the primary user, the device will be factory reset after too many incorrect
5565      * password attempts. When set by a profile owner or an admin on a secondary user or a managed
5566      * profile, only the corresponding user or profile will be wiped.
5567      * <p>
5568      * To implement any other policy (e.g. wiping data for a particular application only, erasing or
5569      * revoking credentials, or reporting the failure to a server), you should implement
5570      * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)} instead. Do not
5571      * use this API, because if the maximum count is reached, the device or profile will be wiped
5572      * immediately, and your callback will not be invoked.
5573      * <p>
5574      * This method can be called on the {@link DevicePolicyManager} instance returned by
5575      * {@link #getParentProfileInstance(ComponentName)} in order to set a value on the parent
5576      * profile.
5577      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5578      * password is always empty and this method has no effect - i.e. the policy is not set.
5579      *
5580      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5581      * @param num The number of failed password attempts at which point the device or profile will
5582      *            be wiped.
5583      * @throws SecurityException if {@code admin} is not an active administrator or does not use
5584      *             both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
5585      *             {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}.
5586      */
5587     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setMaximumFailedPasswordsForWipe(@onNull ComponentName admin, int num)5588     public void setMaximumFailedPasswordsForWipe(@NonNull ComponentName admin, int num) {
5589         if (mService != null) {
5590             try {
5591                 mService.setMaximumFailedPasswordsForWipe(admin, num, mParentInstance);
5592             } catch (RemoteException e) {
5593                 throw e.rethrowFromSystemServer();
5594             }
5595         }
5596     }
5597 
5598     /**
5599      * Retrieve the current maximum number of login attempts that are allowed before the device
5600      * or profile is wiped, for a particular admin or all admins that set restrictions on this user
5601      * and its participating profiles. Restrictions on profiles that have a separate challenge are
5602      * not taken into account.
5603      *
5604      * <p>This method can be called on the {@link DevicePolicyManager} instance
5605      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5606      * the value for the parent profile.
5607      *
5608      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5609      * password is always empty and this method returns a default value (0) indicating that the
5610      * policy is not set.
5611      *
5612      * @param admin The name of the admin component to check, or {@code null} to aggregate
5613      * all admins.
5614      */
5615     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin)5616     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) {
5617         return getMaximumFailedPasswordsForWipe(admin, myUserId());
5618     }
5619 
5620     /** @hide per-user version */
5621     @UnsupportedAppUsage
5622     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin, int userHandle)5623     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) {
5624         if (mService != null) {
5625             try {
5626                 return mService.getMaximumFailedPasswordsForWipe(
5627                         admin, userHandle, mParentInstance);
5628             } catch (RemoteException e) {
5629                 throw e.rethrowFromSystemServer();
5630             }
5631         }
5632         return 0;
5633     }
5634 
5635     /**
5636      * Returns the user that will be wiped first when too many failed attempts are made to unlock
5637      * user {@code userHandle}. That user is either the same as {@code userHandle} or belongs to the
5638      * same profile group. When there is no such policy, returns {@code UserHandle.USER_NULL}.
5639      * E.g. managed profile user may be wiped as a result of failed primary profile password
5640      * attempts when using unified challenge. Primary user may be wiped as a result of failed
5641      * password attempts on the managed profile on an organization-owned device.
5642      * @hide Used only by Keyguard
5643      */
5644     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getProfileWithMinimumFailedPasswordsForWipe(int userHandle)5645     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
5646         if (mService != null) {
5647             try {
5648                 return mService.getProfileWithMinimumFailedPasswordsForWipe(
5649                         userHandle, mParentInstance);
5650             } catch (RemoteException e) {
5651                 throw e.rethrowFromSystemServer();
5652             }
5653         }
5654         return UserHandle.USER_NULL;
5655     }
5656 
5657     /**
5658      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't allow other admins
5659      * to change the password again until the user has entered it.
5660      */
5661     public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
5662 
5663     /**
5664      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't ask for user
5665      * credentials on device boot.
5666      * If the flag is set, the device can be booted without asking for user password.
5667      * The absence of this flag does not change the current boot requirements. This flag
5668      * can be set by the device owner only. If the app is not the device owner, the flag
5669      * is ignored. Once the flag is set, it cannot be reverted back without resetting the
5670      * device to factory defaults.
5671      */
5672     public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
5673 
5674     /**
5675      * Force a new password for device unlock (the password needed to access the entire device) or
5676      * the work profile challenge on the current user. This takes effect immediately.
5677      *
5678      * <p> Before {@link android.os.Build.VERSION_CODES#N}, this API is available to device admin,
5679      * profile owner and device owner. Starting from {@link android.os.Build.VERSION_CODES#N},
5680      * legacy device admin (who is not also profile owner or device owner) can only call this
5681      * API to set a new password if there is currently no password set. Profile owner and device
5682      * owner can continue to force change an existing password as long as the target user is
5683      * unlocked, although device owner will not be able to call this API at all if there is also a
5684      * managed profile on the device.
5685      *
5686      * <p> Between {@link android.os.Build.VERSION_CODES#O},
5687      * {@link android.os.Build.VERSION_CODES#P} and {@link android.os.Build.VERSION_CODES#Q},
5688      * profile owner and devices owner targeting SDK level {@link android.os.Build.VERSION_CODES#O}
5689      * or above who attempt to call this API will receive {@link SecurityException}; they are
5690      * encouraged to migrate to the new {@link #resetPasswordWithToken} API instead.
5691      * Profile owner and device owner targeting older SDK levels are not affected: they continue
5692      * to experience the existing behaviour described in the previous paragraph.
5693      *
5694      * <p><em>Starting from {@link android.os.Build.VERSION_CODES#R}, this API is no longer
5695      * supported in most cases.</em> Device owner and profile owner calling
5696      * this API will receive {@link SecurityException} if they target SDK level
5697      * {@link android.os.Build.VERSION_CODES#O} or above, or they will receive a silent failure
5698      * (API returning {@code false}) if they target lower SDK level.
5699      * For legacy device admins, this API throws {@link SecurityException} if they target SDK level
5700      * {@link android.os.Build.VERSION_CODES#N} or above, and returns {@code false} otherwise. Only
5701      * privileged apps holding RESET_PASSWORD permission which are part of
5702      * the system factory image can still call this API to set a new password if there is currently
5703      * no password set. In this case, if the device already has a password, this API will throw
5704      * {@link SecurityException}.
5705      *
5706      * <p>
5707      * The given password must be sufficient for the current password quality and length constraints
5708      * as returned by {@link #getPasswordQuality(ComponentName)} and
5709      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
5710      * it will be rejected and false returned. Note that the password may be a stronger quality
5711      * (containing alphanumeric characters when the requested quality is only numeric), in which
5712      * case the currently active quality will be increased to match.
5713      *
5714      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
5715      * methods does nothing.
5716      * <p>
5717      * The calling device admin must have requested
5718      * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call this method; if it has
5719      * not, a security exception will be thrown.
5720      *
5721      * @param password The new password for the user. Null or empty clears the password.
5722      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
5723      *            {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
5724      * @return Returns true if the password was applied, or false if it is not acceptable for the
5725      *         current constraints.
5726      * @throws SecurityException if the calling application does not own an active administrator
5727      *             that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
5728      * @throws IllegalStateException if the calling user is locked or has a managed profile.
5729      * @deprecated Please use {@link #resetPasswordWithToken} instead.
5730      */
5731     @Deprecated
5732     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
resetPassword(String password, int flags)5733     public boolean resetPassword(String password, int flags) {
5734         throwIfParentInstance("resetPassword");
5735         if (mService != null) {
5736             try {
5737                 return mService.resetPassword(password, flags);
5738             } catch (RemoteException e) {
5739                 throw e.rethrowFromSystemServer();
5740             }
5741         }
5742         return false;
5743     }
5744 
5745     /**
5746      * Called by a profile or device owner to provision a token which can later be used to reset the
5747      * device lockscreen password (if called by device owner), or managed profile challenge (if
5748      * called by profile owner), via {@link #resetPasswordWithToken}.
5749      * <p>
5750      * If the user currently has a lockscreen password, the provisioned token will not be
5751      * immediately usable; it only becomes active after the user performs a confirm credential
5752      * operation, which can be triggered by {@link KeyguardManager#createConfirmDeviceCredentialIntent}.
5753      * If the user has no lockscreen password, the token is activated immediately. In all cases,
5754      * the active state of the current token can be checked by {@link #isResetPasswordTokenActive}.
5755      * For security reasons, un-activated tokens are only stored in memory and will be lost once
5756      * the device reboots. In this case a new token needs to be provisioned again.
5757      * <p>
5758      * Once provisioned and activated, the token will remain effective even if the user changes
5759      * or clears the lockscreen password.
5760      * <p>
5761      * <em>This token is highly sensitive and should be treated at the same level as user
5762      * credentials. In particular, NEVER store this token on device in plaintext. Do not store
5763      * the plaintext token in device-encrypted storage if it will be needed to reset password on
5764      * file-based encryption devices before user unlocks. Consider carefully how any password token
5765      * will be stored on your server and who will need access to them. Tokens may be the subject of
5766      * legal access requests.
5767      * </em>
5768      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5769      * reset token is not set and this method returns false.
5770      *
5771      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5772      * @param token a secure token a least 32-byte long, which must be generated by a
5773      *        cryptographically strong random number generator.
5774      * @return true if the operation is successful, false otherwise.
5775      * @throws SecurityException if admin is not a device or profile owner.
5776      * @throws IllegalArgumentException if the supplied token is invalid.
5777      */
5778     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setResetPasswordToken(ComponentName admin, byte[] token)5779     public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
5780         throwIfParentInstance("setResetPasswordToken");
5781         if (mService != null) {
5782             try {
5783                 return mService.setResetPasswordToken(admin, token);
5784             } catch (RemoteException e) {
5785                 throw e.rethrowFromSystemServer();
5786             }
5787         }
5788         return false;
5789     }
5790 
5791     /**
5792      * Called by a profile or device owner to revoke the current password reset token.
5793      *
5794      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
5795      * method has no effect - the reset token should not have been set in the first place - and
5796      * false is returned.
5797      *
5798      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5799      * @return true if the operation is successful, false otherwise.
5800      * @throws SecurityException if admin is not a device or profile owner.
5801      */
5802     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
clearResetPasswordToken(ComponentName admin)5803     public boolean clearResetPasswordToken(ComponentName admin) {
5804         throwIfParentInstance("clearResetPasswordToken");
5805         if (mService != null) {
5806             try {
5807                 return mService.clearResetPasswordToken(admin);
5808             } catch (RemoteException e) {
5809                 throw e.rethrowFromSystemServer();
5810             }
5811         }
5812         return false;
5813     }
5814 
5815     /**
5816      * Called by a profile or device owner to check if the current reset password token is active.
5817      *
5818      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
5819      * false is always returned.
5820      *
5821      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5822      * @return true if the token is active, false otherwise.
5823      * @throws SecurityException if admin is not a device or profile owner.
5824      * @throws IllegalStateException if no token has been set.
5825      */
5826     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
isResetPasswordTokenActive(ComponentName admin)5827     public boolean isResetPasswordTokenActive(ComponentName admin) {
5828         throwIfParentInstance("isResetPasswordTokenActive");
5829         if (mService != null) {
5830             try {
5831                 return mService.isResetPasswordTokenActive(admin);
5832             } catch (RemoteException e) {
5833                 throw e.rethrowFromSystemServer();
5834             }
5835         }
5836         return false;
5837     }
5838 
5839     /**
5840      * Called by device or profile owner to force set a new device unlock password or a managed
5841      * profile challenge on current user. This takes effect immediately.
5842      * <p>
5843      * Unlike {@link #resetPassword}, this API can change the password even before the user or
5844      * device is unlocked or decrypted. The supplied token must have been previously provisioned via
5845      * {@link #setResetPasswordToken}, and in active state {@link #isResetPasswordTokenActive}.
5846      * <p>
5847      * The given password must be sufficient for the current password quality and length constraints
5848      * as returned by {@link #getPasswordQuality(ComponentName)} and
5849      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
5850      * it will be rejected and false returned. Note that the password may be a stronger quality, for
5851      * example, a password containing alphanumeric characters when the requested quality is only
5852      * numeric.
5853      * <p>
5854      * Calling with a {@code null} or empty password will clear any existing PIN, pattern or
5855      * password if the current password constraints allow it.
5856      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
5857      * calling this methods has no effect - the password is always empty - and false is returned.
5858      *
5859      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5860      * @param password The new password for the user. {@code null} or empty clears the password.
5861      * @param token the password reset token previously provisioned by
5862      *        {@link #setResetPasswordToken}.
5863      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
5864      *        {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
5865      * @return Returns true if the password was applied, or false if it is not acceptable for the
5866      *         current constraints.
5867      * @throws SecurityException if admin is not a device or profile owner.
5868      * @throws IllegalStateException if the provided token is not valid.
5869      */
5870     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
resetPasswordWithToken(@onNull ComponentName admin, String password, byte[] token, int flags)5871     public boolean resetPasswordWithToken(@NonNull ComponentName admin, String password,
5872             byte[] token, int flags) {
5873         throwIfParentInstance("resetPassword");
5874         if (mService != null) {
5875             try {
5876                 return mService.resetPasswordWithToken(admin, password, token, flags);
5877             } catch (RemoteException e) {
5878                 throw e.rethrowFromSystemServer();
5879             }
5880         }
5881         return false;
5882     }
5883 
5884     /**
5885      * Called by an application that is administering the device to set the maximum time for user
5886      * activity until the device will lock. This limits the length that the user can set. It takes
5887      * effect immediately.
5888      * <p>
5889      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
5890      * to be able to call this method; if it has not, a security exception will be thrown.
5891      * <p>
5892      * This method can be called on the {@link DevicePolicyManager} instance returned by
5893      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5894      * profile.
5895      *
5896      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5897      * @param timeMs The new desired maximum time to lock in milliseconds. A value of 0 means there
5898      *            is no restriction.
5899      * @throws SecurityException if {@code admin} is not an active administrator or it does not use
5900      *             {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
5901      */
setMaximumTimeToLock(@onNull ComponentName admin, long timeMs)5902     public void setMaximumTimeToLock(@NonNull ComponentName admin, long timeMs) {
5903         if (mService != null) {
5904             try {
5905                 mService.setMaximumTimeToLock(admin, timeMs, mParentInstance);
5906             } catch (RemoteException e) {
5907                 throw e.rethrowFromSystemServer();
5908             }
5909         }
5910     }
5911 
5912     /**
5913      * Retrieve the current maximum time to unlock for a particular admin or all admins that set
5914      * restrictions on this user and its participating profiles. Restrictions on profiles that have
5915      * a separate challenge are not taken into account.
5916      *
5917      * <p>This method can be called on the {@link DevicePolicyManager} instance
5918      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5919      * restrictions on the parent profile.
5920      *
5921      * @param admin The name of the admin component to check, or {@code null} to aggregate
5922      * all admins.
5923      * @return time in milliseconds for the given admin or the minimum value (strictest) of
5924      * all admins if admin is null. Returns 0 if there are no restrictions.
5925      */
getMaximumTimeToLock(@ullable ComponentName admin)5926     public long getMaximumTimeToLock(@Nullable ComponentName admin) {
5927         return getMaximumTimeToLock(admin, myUserId());
5928     }
5929 
5930     /** @hide per-user version */
5931     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getMaximumTimeToLock(@ullable ComponentName admin, int userHandle)5932     public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) {
5933         if (mService != null) {
5934             try {
5935                 return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance);
5936             } catch (RemoteException e) {
5937                 throw e.rethrowFromSystemServer();
5938             }
5939         }
5940         return 0;
5941     }
5942 
5943     /**
5944      * Called by a device/profile owner to set the timeout after which unlocking with secondary, non
5945      * strong auth (e.g. fingerprint, face, trust agents) times out, i.e. the user has to use a
5946      * strong authentication method like password, pin or pattern.
5947      *
5948      * <p>This timeout is used internally to reset the timer to require strong auth again after
5949      * specified timeout each time it has been successfully used.
5950      *
5951      * <p>Fingerprint can also be disabled altogether using {@link #KEYGUARD_DISABLE_FINGERPRINT}.
5952      *
5953      * <p>Trust agents can also be disabled altogether using {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
5954      *
5955      * <p>The calling device admin must be a device or profile owner. If it is not,
5956      * a {@link SecurityException} will be thrown.
5957      *
5958      * <p>The calling device admin can verify the value it has set by calling
5959      * {@link #getRequiredStrongAuthTimeout(ComponentName)} and passing in its instance.
5960      *
5961      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
5962      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5963      * profile.
5964      *
5965      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
5966      * calling this methods has no effect - i.e. the timeout is not set.
5967      *
5968      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5969      * @param timeoutMs The new timeout in milliseconds, after which the user will have to unlock
5970      *         with strong authentication method. A value of 0 means the admin is not participating
5971      *         in controlling the timeout.
5972      *         The minimum and maximum timeouts are platform-defined and are typically 1 hour and
5973      *         72 hours, respectively. Though discouraged, the admin may choose to require strong
5974      *         auth at all times using {@link #KEYGUARD_DISABLE_FINGERPRINT} and/or
5975      *         {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
5976      *
5977      * @throws SecurityException if {@code admin} is not a device or profile owner.
5978      */
5979     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setRequiredStrongAuthTimeout(@onNull ComponentName admin, long timeoutMs)5980     public void setRequiredStrongAuthTimeout(@NonNull ComponentName admin,
5981             long timeoutMs) {
5982         if (mService != null) {
5983             try {
5984                 mService.setRequiredStrongAuthTimeout(admin, timeoutMs, mParentInstance);
5985             } catch (RemoteException e) {
5986                 throw e.rethrowFromSystemServer();
5987             }
5988         }
5989     }
5990 
5991     /**
5992      * Determine for how long the user will be able to use secondary, non strong auth for
5993      * authentication, since last strong method authentication (password, pin or pattern) was used.
5994      * After the returned timeout the user is required to use strong authentication method.
5995      *
5996      * <p>This method can be called on the {@link DevicePolicyManager} instance
5997      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5998      * restrictions on the parent profile.
5999      *
6000      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
6001      * 0 is returned to indicate that no timeout is configured.
6002      *
6003      * @param admin The name of the admin component to check, or {@code null} to aggregate
6004      *         across all participating admins.
6005      * @return The timeout in milliseconds or 0 if not configured for the provided admin.
6006      */
6007     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getRequiredStrongAuthTimeout(@ullable ComponentName admin)6008     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin) {
6009         return getRequiredStrongAuthTimeout(admin, myUserId());
6010     }
6011 
6012     /** @hide per-user version */
6013     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
6014     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getRequiredStrongAuthTimeout(@ullable ComponentName admin, @UserIdInt int userId)6015     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin, @UserIdInt int userId) {
6016         if (mService != null) {
6017             try {
6018                 return mService.getRequiredStrongAuthTimeout(admin, userId, mParentInstance);
6019             } catch (RemoteException e) {
6020                 throw e.rethrowFromSystemServer();
6021             }
6022         }
6023         return DEFAULT_STRONG_AUTH_TIMEOUT_MS;
6024     }
6025 
6026     /**
6027      * Flag for {@link #lockNow(int)}: also evict the user's credential encryption key from the
6028      * keyring. The user's credential will need to be entered again in order to derive the
6029      * credential encryption key that will be stored back in the keyring for future use.
6030      * <p>
6031      * This flag can only be used by a profile owner when locking a managed profile when
6032      * {@link #getStorageEncryptionStatus} returns {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
6033      * <p>
6034      * In order to secure user data, the user will be stopped and restarted so apps should wait
6035      * until they are next run to perform further actions.
6036      */
6037     public static final int FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY = 1;
6038 
6039     /** @hide */
6040     @Retention(RetentionPolicy.SOURCE)
6041     @IntDef(flag = true, prefix = { "FLAG_EVICT_" }, value = {
6042             FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY
6043     })
6044     public @interface LockNowFlag {}
6045 
6046     /**
6047      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
6048      * this call.
6049      * <p>
6050      * This method secures the device in response to an urgent situation, such as a lost or stolen
6051      * device. After this method is called, the device must be unlocked using strong authentication
6052      * (PIN, pattern, or password). This API is intended for use only by device admins.
6053      * <p>
6054      * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have
6055      * the LOCK_DEVICE permission or the device must have the device admin feature; if neither is
6056      * true, then the method will return without completing any action. Before version
6057      * {@link android.os.Build.VERSION_CODES#R}, the device needed the device admin feature,
6058      * regardless of the caller's permissions.
6059      * <p>
6060      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
6061      * to be able to call this method; if it has not, a security exception will be thrown.
6062      * <p>
6063      * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
6064      * the device. Device admins who find the device in this state can lock an otherwise-insecure
6065      * device by first calling {@link #resetPassword} to set the password and then lock the device.
6066      * <p>
6067      * This method can be called on the {@link DevicePolicyManager} instance returned by
6068      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
6069      * <p>
6070      * NOTE: on {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, this
6071      * method doesn't turn off the screen as it would be a driving safety distraction.
6072      * <p>
6073      * Equivalent to calling {@link #lockNow(int)} with no flags.
6074      *
6075      * @throws SecurityException if the calling application does not own an active administrator
6076      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
6077      */
lockNow()6078     public void lockNow() {
6079         lockNow(0);
6080     }
6081 
6082     /**
6083      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
6084      * this call.
6085      * <p>
6086      * This method secures the device in response to an urgent situation, such as a lost or stolen
6087      * device. After this method is called, the device must be unlocked using strong authentication
6088      * (PIN, pattern, or password). This API is intended for use only by device admins.
6089      * <p>
6090      * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have
6091      * the LOCK_DEVICE permission or the device must have the device admin feature; if neither is
6092      * true, then the method will return without completing any action. Before version
6093      * {@link android.os.Build.VERSION_CODES#R}, the device needed the device admin feature,
6094      * regardless of the caller's permissions.
6095      * <p>
6096      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
6097      * to be able to call this method; if it has not, a security exception will be thrown.
6098      * <p>
6099      * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
6100      * the device. Device admins who find the device in this state can lock an otherwise-insecure
6101      * device by first calling {@link #resetPassword} to set the password and then lock the device.
6102      * <p>
6103      * This method can be called on the {@link DevicePolicyManager} instance returned by
6104      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile as
6105      * well as the managed profile.
6106      * <p>
6107      * NOTE: In order to lock the parent profile and evict the encryption key of the managed
6108      * profile, {@link #lockNow()} must be called twice: First, {@link #lockNow()} should be called
6109      * on the {@link DevicePolicyManager} instance returned by
6110      * {@link #getParentProfileInstance(ComponentName)}, then {@link #lockNow(int)} should be
6111      * called on the {@link DevicePolicyManager} instance associated with the managed profile,
6112      * with the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag.
6113      * Calling the method twice in this order ensures that all users are locked and does not
6114      * stop the device admin on the managed profile from issuing a second call to lock its own
6115      * profile.
6116      * <p>
6117      * NOTE: on {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, this
6118      * method doesn't turn off the screen as it would be a driving safety distraction.
6119      *
6120      * @param flags May be 0 or {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}.
6121      * @throws SecurityException if the calling application does not own an active administrator
6122      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} or the
6123      *             {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is passed by an application
6124      *             that is not a profile
6125      *             owner of a managed profile.
6126      * @throws IllegalArgumentException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is
6127      *             passed when locking the parent profile.
6128      * @throws UnsupportedOperationException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}
6129      *             flag is passed when {@link #getStorageEncryptionStatus} does not return
6130      *             {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
6131      */
lockNow(@ockNowFlag int flags)6132     public void lockNow(@LockNowFlag int flags) {
6133         if (mService != null) {
6134             try {
6135                 mService.lockNow(flags, mParentInstance);
6136             } catch (RemoteException e) {
6137                 throw e.rethrowFromSystemServer();
6138             }
6139         }
6140     }
6141 
6142     /**
6143      * Flag for {@link #wipeData(int)}: also erase the device's external
6144      * storage (such as SD cards).
6145      */
6146     public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
6147 
6148     /**
6149      * Flag for {@link #wipeData(int)}: also erase the factory reset protection
6150      * data.
6151      *
6152      * <p>This flag may only be set by device owner admins; if it is set by
6153      * other admins a {@link SecurityException} will be thrown.
6154      */
6155     public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
6156 
6157     /**
6158      * Flag for {@link #wipeData(int)}: also erase the device's eUICC data.
6159      */
6160     public static final int WIPE_EUICC = 0x0004;
6161 
6162     /**
6163      * Flag for {@link #wipeData(int)}: won't show reason for wiping to the user.
6164      */
6165     public static final int WIPE_SILENTLY = 0x0008;
6166 
6167     /**
6168      * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
6169      * other users will remain unaffected. Calling from the primary user will cause the device to
6170      * reboot, erasing all device data - including all the secondary users and their data - while
6171      * booting up.
6172      * <p>
6173      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
6174      * be able to call this method; if it has not, a security exception will be thrown.
6175      *
6176      * If the caller is a profile owner of an organization-owned managed profile, it may
6177      * additionally call this method on the parent instance.
6178      * Calling this method on the parent {@link DevicePolicyManager} instance would wipe the
6179      * entire device, while calling it on the current profile instance would relinquish the device
6180      * for personal use, removing the managed profile and all policies set by the profile owner.
6181      *
6182      * @param flags Bit mask of additional options: currently supported flags are
6183      *            {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA},
6184      *            {@link #WIPE_EUICC} and {@link #WIPE_SILENTLY}.
6185      * @throws SecurityException if the calling application does not own an active administrator
6186      *            that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} or is not granted the
6187      *            {@link android.Manifest.permission#MASTER_CLEAR} permission.
6188      */
wipeData(int flags)6189     public void wipeData(int flags) {
6190         wipeDataInternal(flags, "");
6191     }
6192 
6193     /**
6194      * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
6195      * other users will remain unaffected, the provided reason for wiping data can be shown to
6196      * user. Calling from the primary user will cause the device to reboot, erasing all device data
6197      * - including all the secondary users and their data - while booting up. In this case, we don't
6198      * show the reason to the user since the device would be factory reset.
6199      * <p>
6200      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
6201      * be able to call this method; if it has not, a security exception will be thrown.
6202      *
6203      * If the caller is a profile owner of an organization-owned managed profile, it may
6204      * additionally call this method on the parent instance.
6205      * Calling this method on the parent {@link DevicePolicyManager} instance would wipe the
6206      * entire device, while calling it on the current profile instance would relinquish the device
6207      * for personal use, removing the managed profile and all policies set by the profile owner.
6208      *
6209      * @param flags Bit mask of additional options: currently supported flags are
6210      *            {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA} and
6211      *            {@link #WIPE_EUICC}.
6212      * @param reason a string that contains the reason for wiping data, which can be
6213      *            presented to the user.
6214      * @throws SecurityException if the calling application does not own an active administrator
6215      *            that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} or is not granted the
6216      *            {@link android.Manifest.permission#MASTER_CLEAR} permission.
6217      * @throws IllegalArgumentException if the input reason string is null or empty, or if
6218      *            {@link #WIPE_SILENTLY} is set.
6219      */
wipeData(int flags, @NonNull CharSequence reason)6220     public void wipeData(int flags, @NonNull CharSequence reason) {
6221         Objects.requireNonNull(reason, "reason string is null");
6222         Preconditions.checkStringNotEmpty(reason, "reason string is empty");
6223         Preconditions.checkArgument((flags & WIPE_SILENTLY) == 0, "WIPE_SILENTLY cannot be set");
6224         wipeDataInternal(flags, reason.toString());
6225     }
6226 
6227     /**
6228      * Internal function for both {@link #wipeData(int)} and
6229      * {@link #wipeData(int, CharSequence)} to call.
6230      *
6231      * @see #wipeData(int)
6232      * @see #wipeData(int, CharSequence)
6233      * @hide
6234      */
wipeDataInternal(int flags, @NonNull String wipeReasonForUser)6235     private void wipeDataInternal(int flags, @NonNull String wipeReasonForUser) {
6236         if (mService != null) {
6237             try {
6238                 mService.wipeDataWithReason(flags, wipeReasonForUser, mParentInstance);
6239             } catch (RemoteException e) {
6240                 throw e.rethrowFromSystemServer();
6241             }
6242         }
6243     }
6244 
6245     /**
6246      * Callable by device owner or profile owner of an organization-owned device, to set a
6247      * factory reset protection (FRP) policy. When a new policy is set, the system
6248      * notifies the FRP management agent of a policy change by broadcasting
6249      * {@code ACTION_RESET_PROTECTION_POLICY_CHANGED}.
6250      *
6251      * @param admin  Which {@link DeviceAdminReceiver} this request is associated with.
6252      * @param policy the new FRP policy, or {@code null} to clear the current policy.
6253      * @throws SecurityException if {@code admin} is not a device owner or a profile owner of
6254      *                           an organization-owned device.
6255      * @throws UnsupportedOperationException if factory reset protection is not
6256      *                           supported on the device.
6257      */
setFactoryResetProtectionPolicy(@onNull ComponentName admin, @Nullable FactoryResetProtectionPolicy policy)6258     public void setFactoryResetProtectionPolicy(@NonNull ComponentName admin,
6259             @Nullable FactoryResetProtectionPolicy policy) {
6260         throwIfParentInstance("setFactoryResetProtectionPolicy");
6261         if (mService != null) {
6262             try {
6263                 mService.setFactoryResetProtectionPolicy(admin, policy);
6264             } catch (RemoteException e) {
6265                 throw e.rethrowFromSystemServer();
6266             }
6267         }
6268     }
6269 
6270     /**
6271      * Callable by device owner or profile owner of an organization-owned device, to retrieve
6272      * the current factory reset protection (FRP) policy set previously by
6273      * {@link #setFactoryResetProtectionPolicy}.
6274      * <p>
6275      * This method can also be called by the FRP management agent on device or with the permission
6276      * {@link android.Manifest.permission#MASTER_CLEAR}, in which case, it can pass {@code null}
6277      * as the ComponentName.
6278      *
6279      * @param admin Which {@link DeviceAdminReceiver} this request is associated with or
6280      *              {@code null} if called by the FRP management agent on device or with the
6281      *              permission {@link android.Manifest.permission#MASTER_CLEAR}.
6282      * @return The current FRP policy object or {@code null} if no policy is set.
6283      * @throws SecurityException if {@code admin} is not a device owner, a profile owner of
6284      *                           an organization-owned device or the FRP management agent.
6285      * @throws UnsupportedOperationException if factory reset protection is not
6286      *                           supported on the device.
6287      */
getFactoryResetProtectionPolicy( @ullable ComponentName admin)6288     public @Nullable FactoryResetProtectionPolicy getFactoryResetProtectionPolicy(
6289             @Nullable ComponentName admin) {
6290         throwIfParentInstance("getFactoryResetProtectionPolicy");
6291         if (mService != null) {
6292             try {
6293                 return mService.getFactoryResetProtectionPolicy(admin);
6294             } catch (RemoteException e) {
6295                 throw e.rethrowFromSystemServer();
6296             }
6297         }
6298         return null;
6299     }
6300 
6301     /**
6302      * Send a lost mode location update to the admin. This API is limited to organization-owned
6303      * devices, which includes devices with a device owner or devices with a profile owner on an
6304      * organization-owned managed profile.
6305      *
6306      * <p>The caller must hold the
6307      * {@link android.Manifest.permission#TRIGGER_LOST_MODE} permission.
6308      *
6309      * <p> Not for use by third-party applications.
6310      *
6311      * @param executor The executor through which the callback should be invoked.
6312      * @param callback A callback object that will inform the caller whether a lost mode location
6313      *                 update was successfully sent
6314      * @hide
6315      */
6316     @SystemApi
6317     @RequiresPermission(android.Manifest.permission.TRIGGER_LOST_MODE)
sendLostModeLocationUpdate(@onNull @allbackExecutor Executor executor, @NonNull Consumer<Boolean> callback)6318     public void sendLostModeLocationUpdate(@NonNull @CallbackExecutor Executor executor,
6319             @NonNull Consumer<Boolean> callback) {
6320         throwIfParentInstance("sendLostModeLocationUpdate");
6321         if (mService == null) {
6322             executeCallback(AndroidFuture.completedFuture(false), executor, callback);
6323             return;
6324         }
6325         try {
6326             final AndroidFuture<Boolean> future = new AndroidFuture<>();
6327             mService.sendLostModeLocationUpdate(future);
6328             executeCallback(future, executor, callback);
6329         } catch (RemoteException e) {
6330             throw e.rethrowFromSystemServer();
6331         }
6332     }
6333 
executeCallback(AndroidFuture<Boolean> future, @CallbackExecutor @NonNull Executor executor, Consumer<Boolean> callback)6334     private void executeCallback(AndroidFuture<Boolean> future,
6335             @CallbackExecutor @NonNull Executor executor,
6336             Consumer<Boolean> callback) {
6337         future.whenComplete((result, error) -> executor.execute(() -> {
6338             final long token = Binder.clearCallingIdentity();
6339             try {
6340                 if (error != null) {
6341                     callback.accept(false);
6342                 } else {
6343                     callback.accept(result);
6344                 }
6345             } finally {
6346                 Binder.restoreCallingIdentity(token);
6347             }
6348         }));
6349     }
6350 
6351     /**
6352      * Called by an application that is administering the device to set the
6353      * global proxy and exclusion list.
6354      * <p>
6355      * The calling device admin must have requested
6356      * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
6357      * this method; if it has not, a security exception will be thrown.
6358      * Only the first device admin can set the proxy. If a second admin attempts
6359      * to set the proxy, the {@link ComponentName} of the admin originally setting the
6360      * proxy will be returned. If successful in setting the proxy, {@code null} will
6361      * be returned.
6362      * The method can be called repeatedly by the device admin alrady setting the
6363      * proxy to update the proxy and exclusion list.
6364      *
6365      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6366      * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
6367      *            Pass Proxy.NO_PROXY to reset the proxy.
6368      * @param exclusionList a list of domains to be excluded from the global proxy.
6369      * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
6370      *            of the device admin that sets the proxy.
6371      * @hide
6372      */
6373     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setGlobalProxy(@onNull ComponentName admin, Proxy proxySpec, List<String> exclusionList )6374     public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
6375             List<String> exclusionList ) {
6376         throwIfParentInstance("setGlobalProxy");
6377         if (proxySpec == null) {
6378             throw new NullPointerException();
6379         }
6380         if (mService != null) {
6381             try {
6382                 String hostSpec;
6383                 String exclSpec;
6384                 if (proxySpec.equals(Proxy.NO_PROXY)) {
6385                     hostSpec = null;
6386                     exclSpec = null;
6387                 } else {
6388                     if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
6389                         throw new IllegalArgumentException();
6390                     }
6391                     final Pair<String, String> proxyParams =
6392                             getProxyParameters(proxySpec, exclusionList);
6393                     hostSpec = proxyParams.first;
6394                     exclSpec = proxyParams.second;
6395                 }
6396                 return mService.setGlobalProxy(admin, hostSpec, exclSpec);
6397             } catch (RemoteException e) {
6398                 throw e.rethrowFromSystemServer();
6399             }
6400         }
6401         return null;
6402     }
6403 
6404     /**
6405      * Build HTTP proxy parameters for {@link IDevicePolicyManager#setGlobalProxy}.
6406      * @throws IllegalArgumentException Invalid proxySpec
6407      * @hide
6408      */
6409     @VisibleForTesting
getProxyParameters(Proxy proxySpec, List<String> exclusionList)6410     public Pair<String, String> getProxyParameters(Proxy proxySpec, List<String> exclusionList) {
6411         InetSocketAddress sa = (InetSocketAddress) proxySpec.address();
6412         String hostName = sa.getHostName();
6413         int port = sa.getPort();
6414         final List<String> trimmedExclList;
6415         if (exclusionList == null) {
6416             trimmedExclList = Collections.emptyList();
6417         } else {
6418             trimmedExclList = new ArrayList<>(exclusionList.size());
6419             for (String exclDomain : exclusionList) {
6420                 trimmedExclList.add(exclDomain.trim());
6421             }
6422         }
6423         final ProxyInfo info = ProxyInfo.buildDirectProxy(hostName, port, trimmedExclList);
6424         // The hostSpec is built assuming that there is a specified port and hostname,
6425         // but ProxyInfo.isValid() accepts 0 / empty as unspecified: also reject them.
6426         if (port == 0 || TextUtils.isEmpty(hostName) || !info.isValid()) {
6427             throw new IllegalArgumentException();
6428         }
6429 
6430         return new Pair<>(hostName + ":" + port, TextUtils.join(",", trimmedExclList));
6431     }
6432 
6433     /**
6434      * Set a network-independent global HTTP proxy. This is not normally what you want for typical
6435      * HTTP proxies - they are generally network dependent. However if you're doing something
6436      * unusual like general internal filtering this may be useful. On a private network where the
6437      * proxy is not accessible, you may break HTTP using this.
6438      * <p>
6439      * This method requires the caller to be the device owner.
6440      * <p>
6441      * This proxy is only a recommendation and it is possible that some apps will ignore it.
6442      * <p>
6443      * Note: The device owner won't be able to set a global HTTP proxy if there are unaffiliated
6444      * secondary users or profiles on the device. It's recommended that affiliation ids are set for
6445      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
6446      *
6447      * @see ProxyInfo
6448      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6449      * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A
6450      *            {@code null} value will clear the global HTTP proxy.
6451      * @throws SecurityException if {@code admin} is not the device owner.
6452      */
setRecommendedGlobalProxy(@onNull ComponentName admin, @Nullable ProxyInfo proxyInfo)6453     public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
6454             proxyInfo) {
6455         throwIfParentInstance("setRecommendedGlobalProxy");
6456         if (mService != null) {
6457             try {
6458                 mService.setRecommendedGlobalProxy(admin, proxyInfo);
6459             } catch (RemoteException e) {
6460                 throw e.rethrowFromSystemServer();
6461             }
6462         }
6463     }
6464 
6465     /**
6466      * Returns the component name setting the global proxy.
6467      * @return ComponentName object of the device admin that set the global proxy, or {@code null}
6468      *         if no admin has set the proxy.
6469      * @hide
6470      */
getGlobalProxyAdmin()6471     public @Nullable ComponentName getGlobalProxyAdmin() {
6472         if (mService != null) {
6473             try {
6474                 return mService.getGlobalProxyAdmin(myUserId());
6475             } catch (RemoteException e) {
6476                 throw e.rethrowFromSystemServer();
6477             }
6478         }
6479         return null;
6480     }
6481 
6482     /**
6483      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
6484      * indicating that encryption is not supported.
6485      */
6486     public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
6487 
6488     /**
6489      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
6490      * indicating that encryption is supported, but is not currently active.
6491      */
6492     public static final int ENCRYPTION_STATUS_INACTIVE = 1;
6493 
6494     /**
6495      * Result code for {@link #getStorageEncryptionStatus}:
6496      * indicating that encryption is not currently active, but is currently
6497      * being activated.  This is only reported by devices that support
6498      * encryption of data and only when the storage is currently
6499      * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
6500      * to become encrypted will never return this value.
6501      */
6502     public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
6503 
6504     /**
6505      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
6506      * indicating that encryption is active.
6507      * <p>
6508      * Also see {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
6509      */
6510     public static final int ENCRYPTION_STATUS_ACTIVE = 3;
6511 
6512     /**
6513      * Result code for {@link #getStorageEncryptionStatus}:
6514      * indicating that encryption is active, but an encryption key has not
6515      * been set by the user.
6516      */
6517     public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
6518 
6519     /**
6520      * Result code for {@link #getStorageEncryptionStatus}:
6521      * indicating that encryption is active and the encryption key is tied to the user or profile.
6522      * <p>
6523      * This value is only returned to apps targeting API level 24 and above. For apps targeting
6524      * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the
6525      * encryption key is specific to the user or profile.
6526      */
6527     public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5;
6528 
6529     /**
6530      * Activity action: begin the process of encrypting data on the device.  This activity should
6531      * be launched after using {@link #setStorageEncryption} to request encryption be activated.
6532      * After resuming from this activity, use {@link #getStorageEncryption}
6533      * to check encryption status.  However, on some devices this activity may never return, as
6534      * it may trigger a reboot and in some cases a complete data wipe of the device.
6535      */
6536     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
6537     public static final String ACTION_START_ENCRYPTION
6538             = "android.app.action.START_ENCRYPTION";
6539 
6540     /**
6541      * Activity action: launch the DPC to check policy compliance. This intent is launched when
6542      * the user taps on the notification about personal apps suspension. When handling this intent
6543      * the DPC must check if personal apps should still be suspended and either unsuspend them or
6544      * instruct the user on how to resolve the noncompliance causing the suspension.
6545      *
6546      * @see #setPersonalAppsSuspended
6547      */
6548     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
6549     public static final String ACTION_CHECK_POLICY_COMPLIANCE =
6550             "android.app.action.CHECK_POLICY_COMPLIANCE";
6551 
6552     /**
6553      * Broadcast action: notify managed provisioning that PO/DO provisioning has completed.
6554      *
6555      * @hide
6556      */
6557     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
6558     public static final String ACTION_PROVISIONING_COMPLETED =
6559             "android.app.action.PROVISIONING_COMPLETED";
6560 
6561     /**
6562      * Extra for {@link #ACTION_PROVISIONING_COMPLETED} to indicate the provisioning action that has
6563      * been completed, this can either be {@link #ACTION_PROVISION_MANAGED_PROFILE},
6564      * {@link #ACTION_PROVISION_MANAGED_DEVICE}, or {@link #ACTION_PROVISION_MANAGED_USER}.
6565      *
6566      * @hide
6567      */
6568     public static final String EXTRA_PROVISIONING_ACTION =
6569             "android.app.extra.PROVISIONING_ACTION";
6570 
6571     /**
6572      * Broadcast action: notify system that a new (Android) user was added when the device is
6573      * managed by a device owner, so receivers can show the proper disclaimer to the (human) user.
6574      *
6575      * @hide
6576      */
6577     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
6578     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
6579     public static final String ACTION_SHOW_NEW_USER_DISCLAIMER =
6580             "android.app.action.SHOW_NEW_USER_DISCLAIMER";
6581 
6582     /**
6583      * Widgets are enabled in keyguard
6584      */
6585     public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
6586 
6587     /**
6588      * Disable all keyguard widgets. Has no effect starting from
6589      * {@link android.os.Build.VERSION_CODES#LOLLIPOP} since keyguard widget is only supported
6590      * on Android versions lower than 5.0.
6591      */
6592     public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
6593 
6594     /**
6595      * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
6596      */
6597     public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
6598 
6599     /**
6600      * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
6601      */
6602     public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
6603 
6604     /**
6605      * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
6606      */
6607     public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
6608 
6609     /**
6610      * Disable trust agents on secure keyguard screens (e.g. PIN/Pattern/Password).
6611      * By setting this flag alone, all trust agents are disabled. If the admin then wants to
6612      * allowlist specific features of some trust agent, {@link #setTrustAgentConfiguration} can be
6613      * used in conjuction to set trust-agent-specific configurations.
6614      */
6615     public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
6616 
6617     /**
6618      * Disable fingerprint authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
6619      */
6620     public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
6621 
6622     /**
6623      * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
6624      * @deprecated This flag was added in version {@link android.os.Build.VERSION_CODES#N}, but it
6625      * never had any effect.
6626      */
6627     @Deprecated
6628     public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
6629 
6630     /**
6631      * Disable face authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
6632      */
6633     public static final int KEYGUARD_DISABLE_FACE = 1 << 7;
6634 
6635     /**
6636      * Disable iris authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
6637      */
6638     public static final int KEYGUARD_DISABLE_IRIS = 1 << 8;
6639 
6640     /**
6641      * Disable all keyguard shortcuts.
6642      *
6643      * @hide
6644      */
6645     public static final int KEYGUARD_DISABLE_SHORTCUTS_ALL = 1 << 9;
6646 
6647     /**
6648      * NOTE: Please remember to update the DevicePolicyManagerTest's testKeyguardDisabledFeatures
6649      * CTS test when adding to the list above.
6650      */
6651 
6652     /**
6653      * Disable all biometric authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
6654      */
6655     public static final int KEYGUARD_DISABLE_BIOMETRICS =
6656             DevicePolicyManager.KEYGUARD_DISABLE_FACE
6657             | DevicePolicyManager.KEYGUARD_DISABLE_IRIS
6658             | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
6659 
6660     /**
6661      * Disable all current and future keyguard customizations.
6662      */
6663     public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
6664 
6665     /**
6666      * Keyguard features that when set on a non-organization-owned managed profile that doesn't
6667      * have its own challenge will affect the profile's parent user. These can also be set on the
6668      * managed profile's parent {@link DevicePolicyManager} instance to explicitly control the
6669      * parent user.
6670      *
6671      * <p>
6672      * Organization-owned managed profile supports disabling additional keyguard features on the
6673      * parent user as defined in {@link #ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY}.
6674      *
6675      * @hide
6676      */
6677     public static final int NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
6678             DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
6679             | DevicePolicyManager.KEYGUARD_DISABLE_BIOMETRICS;
6680 
6681     /**
6682      * Keyguard features that when set by the profile owner of an organization-owned managed
6683      * profile will affect the profile's parent user if set on the managed profile's parent
6684      * {@link DevicePolicyManager} instance.
6685      *
6686      * @hide
6687      */
6688     public static final int ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY =
6689             DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA
6690                     | DevicePolicyManager.KEYGUARD_DISABLE_SECURE_NOTIFICATIONS
6691                     | DevicePolicyManager.KEYGUARD_DISABLE_SHORTCUTS_ALL;
6692 
6693     /**
6694      * Keyguard features that when set on a normal or organization-owned managed profile, have
6695      * the potential to affect the profile's parent user.
6696      *
6697      * @hide
6698      */
6699     public static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
6700             DevicePolicyManager.NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER
6701                     | DevicePolicyManager.ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY;
6702 
6703     /**
6704      * @deprecated This method does not actually modify the storage encryption of the device.
6705      * It has never affected the encryption status of a device.
6706      *
6707      * Called by an application that is administering the device to request that the storage system
6708      * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
6709      * <p>
6710      * When multiple device administrators attempt to control device encryption, the most secure,
6711      * supported setting will always be used. If any device administrator requests device
6712      * encryption, it will be enabled; Conversely, if a device administrator attempts to disable
6713      * device encryption while another device administrator has enabled it, the call to disable will
6714      * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
6715      * <p>
6716      * This policy controls encryption of the secure (application data) storage area. Data written
6717      * to other storage areas may or may not be encrypted, and this policy does not require or
6718      * control the encryption of any other storage areas. There is one exception: If
6719      * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the
6720      * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be
6721      * written to disk within the encrypted storage area.
6722      * <p>
6723      * Important Note: On some devices, it is possible to encrypt storage without requiring the user
6724      * to create a device PIN or Password. In this case, the storage is encrypted, but the
6725      * encryption key may not be fully secured. For maximum security, the administrator should also
6726      * require (and check for) a pattern, PIN, or password.
6727      *
6728      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6729      * @param encrypt true to request encryption, false to release any previous request
6730      * @return the new total request status (for all active admins), or {@link
6731      *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user.
6732      *         Will be one of {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link
6733      *         #ENCRYPTION_STATUS_INACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value
6734      *         of the requests; use {@link #getStorageEncryptionStatus()} to query the actual device
6735      *         state.
6736      *
6737      * @throws SecurityException if {@code admin} is not an active administrator or does not use
6738      *             {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE}
6739      */
6740     @Deprecated
setStorageEncryption(@onNull ComponentName admin, boolean encrypt)6741     public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
6742         throwIfParentInstance("setStorageEncryption");
6743         if (mService != null) {
6744             try {
6745                 return mService.setStorageEncryption(admin, encrypt);
6746             } catch (RemoteException e) {
6747                 throw e.rethrowFromSystemServer();
6748             }
6749         }
6750         return ENCRYPTION_STATUS_UNSUPPORTED;
6751     }
6752 
6753     /**
6754      * @deprecated This method only returns the value set by {@link #setStorageEncryption}.
6755      * It does not actually reflect the storage encryption status.
6756      * Use {@link #getStorageEncryptionStatus} for that.
6757      *
6758      * Called by an application that is administering the device to
6759      * determine the requested setting for secure storage.
6760      *
6761      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
6762      * this will return the requested encryption setting as an aggregate of all active
6763      * administrators.
6764      * @return true if the admin(s) are requesting encryption, false if not.
6765      */
6766     @Deprecated
getStorageEncryption(@ullable ComponentName admin)6767     public boolean getStorageEncryption(@Nullable ComponentName admin) {
6768         throwIfParentInstance("getStorageEncryption");
6769         if (mService != null) {
6770             try {
6771                 return mService.getStorageEncryption(admin, myUserId());
6772             } catch (RemoteException e) {
6773                 throw e.rethrowFromSystemServer();
6774             }
6775         }
6776         return false;
6777     }
6778 
6779     /**
6780      * Called by an application that is administering the device to
6781      * determine the current encryption status of the device.
6782      * <p>
6783      * Depending on the returned status code, the caller may proceed in different
6784      * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
6785      * storage system does not support encryption.  If the
6786      * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
6787      * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
6788      * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
6789      * storage system has enabled encryption but no password is set so further action
6790      * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING},
6791      * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER},
6792      * no further action is required.
6793      *
6794      * @return current status of encryption. The value will be one of
6795      * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
6796      * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
6797      * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
6798      *
6799      * @throws SecurityException if called on a parent instance.
6800      */
getStorageEncryptionStatus()6801     public int getStorageEncryptionStatus() {
6802         throwIfParentInstance("getStorageEncryptionStatus");
6803         return getStorageEncryptionStatus(myUserId());
6804     }
6805 
6806     /** @hide per-user version */
6807     @UnsupportedAppUsage
getStorageEncryptionStatus(int userHandle)6808     public int getStorageEncryptionStatus(int userHandle) {
6809         if (mService != null) {
6810             try {
6811                 return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle);
6812             } catch (RemoteException e) {
6813                 throw e.rethrowFromSystemServer();
6814             }
6815         }
6816         return ENCRYPTION_STATUS_UNSUPPORTED;
6817     }
6818 
6819     /**
6820      * Mark a CA certificate as approved by the device user. This means that they have been notified
6821      * of the installation, were made aware of the risks, viewed the certificate and still wanted to
6822      * keep the certificate on the device.
6823      *
6824      * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to
6825      * this certificate.
6826      *
6827      * @hide
6828      */
approveCaCert(String alias, int userHandle, boolean approval)6829     public boolean approveCaCert(String alias, int userHandle, boolean approval) {
6830         if (mService != null) {
6831             try {
6832                 return mService.approveCaCert(alias, userHandle, approval);
6833             } catch (RemoteException e) {
6834                 throw e.rethrowFromSystemServer();
6835             }
6836         }
6837         return false;
6838     }
6839 
6840     /**
6841      * Check whether a CA certificate has been approved by the device user.
6842      *
6843      * @hide
6844      */
isCaCertApproved(String alias, int userHandle)6845     public boolean isCaCertApproved(String alias, int userHandle) {
6846         if (mService != null) {
6847             try {
6848                 return mService.isCaCertApproved(alias, userHandle);
6849             } catch (RemoteException e) {
6850                 throw e.rethrowFromSystemServer();
6851             }
6852         }
6853         return false;
6854     }
6855 
6856     /**
6857      * Installs the given certificate as a user CA.
6858      * <p>
6859      * Inserted user CAs aren't automatically trusted by apps in Android 7.0 (API level 24) and
6860      * higher. App developers can change the default behavior for an app by adding a
6861      * <a href="{@docRoot}training/articles/security-config.html">Security Configuration
6862      * File</a> to the app manifest file.
6863      *
6864      * The caller must be a profile or device owner on that user, or a delegate package given the
6865      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
6866      * security exception will be thrown.
6867      *
6868      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6869      *              {@code null} if calling from a delegated certificate installer.
6870      * @param certBuffer encoded form of the certificate to install.
6871      *
6872      * @return false if the certBuffer cannot be parsed or installation is
6873      *         interrupted, true otherwise.
6874      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6875      *         owner.
6876      * @see #setDelegatedScopes
6877      * @see #DELEGATION_CERT_INSTALL
6878      */
installCaCert(@ullable ComponentName admin, byte[] certBuffer)6879     public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
6880         throwIfParentInstance("installCaCert");
6881         if (mService != null) {
6882             try {
6883                 return mService.installCaCert(admin, mContext.getPackageName(), certBuffer);
6884             } catch (RemoteException e) {
6885                 throw e.rethrowFromSystemServer();
6886             }
6887         }
6888         return false;
6889     }
6890 
6891     /**
6892      * Uninstalls the given certificate from trusted user CAs, if present.
6893      *
6894      * The caller must be a profile or device owner on that user, or a delegate package given the
6895      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
6896      * security exception will be thrown.
6897      *
6898      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6899      *              {@code null} if calling from a delegated certificate installer.
6900      * @param certBuffer encoded form of the certificate to remove.
6901      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6902      *         owner.
6903      * @see #setDelegatedScopes
6904      * @see #DELEGATION_CERT_INSTALL
6905      */
uninstallCaCert(@ullable ComponentName admin, byte[] certBuffer)6906     public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
6907         throwIfParentInstance("uninstallCaCert");
6908         if (mService != null) {
6909             try {
6910                 final String alias = getCaCertAlias(certBuffer);
6911                 mService.uninstallCaCerts(admin, mContext.getPackageName(), new String[] {alias});
6912             } catch (CertificateException e) {
6913                 Log.w(TAG, "Unable to parse certificate", e);
6914             } catch (RemoteException e) {
6915                 throw e.rethrowFromSystemServer();
6916             }
6917         }
6918     }
6919 
6920     /**
6921      * Returns all CA certificates that are currently trusted, excluding system CA certificates.
6922      * If a user has installed any certificates by other means than device policy these will be
6923      * included too.
6924      *
6925      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6926      *              {@code null} if calling from a delegated certificate installer.
6927      * @return a List of byte[] arrays, each encoding one user CA certificate.
6928      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6929      *         owner.
6930      */
getInstalledCaCerts(@ullable ComponentName admin)6931     public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
6932         final List<byte[]> certs = new ArrayList<byte[]>();
6933         throwIfParentInstance("getInstalledCaCerts");
6934         if (mService != null) {
6935             try {
6936                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
6937                 final TrustedCertificateStore certStore = new TrustedCertificateStore();
6938                 for (String alias : certStore.userAliases()) {
6939                     try {
6940                         certs.add(certStore.getCertificate(alias).getEncoded());
6941                     } catch (CertificateException ce) {
6942                         Log.w(TAG, "Could not encode certificate: " + alias, ce);
6943                     }
6944                 }
6945             } catch (RemoteException re) {
6946                 throw re.rethrowFromSystemServer();
6947             }
6948         }
6949         return certs;
6950     }
6951 
6952     /**
6953      * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
6954      * means other than device policy will also be removed, except for system CA certificates.
6955      *
6956      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6957      *              {@code null} if calling from a delegated certificate installer.
6958      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6959      *         owner.
6960      */
uninstallAllUserCaCerts(@ullable ComponentName admin)6961     public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
6962         throwIfParentInstance("uninstallAllUserCaCerts");
6963         if (mService != null) {
6964             try {
6965                 mService.uninstallCaCerts(admin, mContext.getPackageName(),
6966                         new TrustedCertificateStore().userAliases() .toArray(new String[0]));
6967             } catch (RemoteException re) {
6968                 throw re.rethrowFromSystemServer();
6969             }
6970         }
6971     }
6972 
6973     /**
6974      * Returns whether this certificate is installed as a trusted CA.
6975      *
6976      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6977      *              {@code null} if calling from a delegated certificate installer.
6978      * @param certBuffer encoded form of the certificate to look up.
6979      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
6980      *         owner.
6981      */
hasCaCertInstalled(@ullable ComponentName admin, byte[] certBuffer)6982     public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
6983         throwIfParentInstance("hasCaCertInstalled");
6984         if (mService != null) {
6985             try {
6986                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
6987                 return getCaCertAlias(certBuffer) != null;
6988             } catch (RemoteException re) {
6989                 throw re.rethrowFromSystemServer();
6990             } catch (CertificateException ce) {
6991                 Log.w(TAG, "Could not parse certificate", ce);
6992             }
6993         }
6994         return false;
6995     }
6996 
6997     /**
6998      * This API can be called by the following to install a certificate and corresponding
6999      * private key:
7000      * <ul>
7001      *    <li>Device owner</li>
7002      *    <li>Profile owner</li>
7003      *    <li>Delegated certificate installer</li>
7004      *    <li>Credential management app</li>
7005      * </ul>
7006      * All apps within the profile will be able to access the certificate and use the private key,
7007      * given direct user approval.
7008      *
7009      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7010      * can call this API. However, this API sets the key pair as user selectable by default,
7011      * which is not permitted when called by the credential management app. Instead,
7012      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)} should be
7013      * called with {@link #INSTALLKEY_SET_USER_SELECTABLE} not set as a flag.
7014      *
7015      * <p>Access to the installed credentials will not be granted to the caller of this API without
7016      * direct user approval. This is for security - should a certificate installer become
7017      * compromised, certificates it had already installed will be protected.
7018      *
7019      * <p>If the installer must have access to the credentials, call
7020      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead.
7021      *
7022      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
7023      * have been given to access the key and certificates associated with this alias will be
7024      * revoked.
7025      *
7026      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7027      *            {@code null} if calling from a delegated certificate installer.
7028      * @param privKey The private key to install.
7029      * @param cert The certificate to install.
7030      * @param alias The private key alias under which to install the certificate. If a certificate
7031      * with that alias already exists, it will be overwritten.
7032      * @return {@code true} if the keys were installed, {@code false} otherwise.
7033      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7034      *         owner.
7035      * @see #setDelegatedScopes
7036      * @see #DELEGATION_CERT_INSTALL
7037      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate cert, @NonNull String alias)7038     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
7039             @NonNull Certificate cert, @NonNull String alias) {
7040         return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false);
7041     }
7042 
7043     /**
7044      * This API can be called by the following to install a certificate chain and corresponding
7045      * private key for the leaf certificate:
7046      * <ul>
7047      *    <li>Device owner</li>
7048      *    <li>Profile owner</li>
7049      *    <li>Delegated certificate installer</li>
7050      *    <li>Credential management app</li>
7051      * </ul>
7052      * All apps within the profile will be able to access the certificate chain and use the private
7053      * key, given direct user approval.
7054      *
7055      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7056      * can call this API. However, this API sets the key pair as user selectable by default,
7057      * which is not permitted when called by the credential management app. Instead,
7058      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)} should be
7059      * called with {@link #INSTALLKEY_SET_USER_SELECTABLE} not set as a flag.
7060      * Note, there can only be a credential management app on an unmanaged device.
7061      *
7062      * <p>The caller of this API may grant itself access to the certificate and private key
7063      * immediately, without user approval. It is a best practice not to request this unless strictly
7064      * necessary since it opens up additional security vulnerabilities.
7065      *
7066      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
7067      * have been given to access the key and certificates associated with this alias will be
7068      * revoked.
7069      *
7070      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7071      *        {@code null} if calling from a delegated certificate installer.
7072      * @param privKey The private key to install.
7073      * @param certs The certificate chain to install. The chain should start with the leaf
7074      *        certificate and include the chain of trust in order. This will be returned by
7075      *        {@link android.security.KeyChain#getCertificateChain}.
7076      * @param alias The private key alias under which to install the certificate. If a certificate
7077      *        with that alias already exists, it will be overwritten.
7078      * @param requestAccess {@code true} to request that the calling app be granted access to the
7079      *        credentials immediately. Otherwise, access to the credentials will be gated by user
7080      *        approval.
7081      * @return {@code true} if the keys were installed, {@code false} otherwise.
7082      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7083      *         owner.
7084      * @see android.security.KeyChain#getCertificateChain
7085      * @see #setDelegatedScopes
7086      * @see #DELEGATION_CERT_INSTALL
7087      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess)7088     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
7089             @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) {
7090         int flags = INSTALLKEY_SET_USER_SELECTABLE;
7091         if (requestAccess) {
7092             flags |= INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
7093         }
7094         return installKeyPair(admin, privKey, certs, alias, flags);
7095     }
7096 
7097     /**
7098      * This API can be called by the following to install a certificate chain and corresponding
7099      * private key for the leaf certificate:
7100      * <ul>
7101      *    <li>Device owner</li>
7102      *    <li>Profile owner</li>
7103      *    <li>Delegated certificate installer</li>
7104      *    <li>Credential management app</li>
7105      * </ul>
7106      * All apps within the profile will be able to access the certificate chain and use the
7107      * private key, given direct user approval (if the user is allowed to select the private key).
7108      *
7109      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7110      * can call this API. If called by the credential management app:
7111      * <ul>
7112      *    <li>The componentName must be {@code null}r</li>
7113      *    <li>The alias must exist in the credential management app's
7114      *    {@link android.security.AppUriAuthenticationPolicy}</li>
7115      *    <li>The key pair must not be user selectable</li>
7116      * </ul>
7117      * Note, there can only be a credential management app on an unmanaged device.
7118      *
7119      * <p>The caller of this API may grant itself access to the certificate and private key
7120      * immediately, without user approval. It is a best practice not to request this unless strictly
7121      * necessary since it opens up additional security vulnerabilities.
7122      *
7123      * <p>Include {@link #INSTALLKEY_SET_USER_SELECTABLE} in the {@code flags} argument to allow
7124      * the user to select the key from a dialog.
7125      *
7126      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
7127      * have been given to access the key and certificates associated with this alias will be
7128      * revoked.
7129      *
7130      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7131      *        {@code null} if calling from a delegated certificate installer.
7132      * @param privKey The private key to install.
7133      * @param certs The certificate chain to install. The chain should start with the leaf
7134      *        certificate and include the chain of trust in order. This will be returned by
7135      *        {@link android.security.KeyChain#getCertificateChain}.
7136      * @param alias The private key alias under which to install the certificate. If a certificate
7137      *        with that alias already exists, it will be overwritten.
7138      * @param flags Flags to request that the calling app be granted access to the credentials
7139      *        and set the key to be user-selectable. See {@link #INSTALLKEY_SET_USER_SELECTABLE} and
7140      *        {@link #INSTALLKEY_REQUEST_CREDENTIALS_ACCESS}.
7141      * @return {@code true} if the keys were installed, {@code false} otherwise.
7142      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7143      *         owner, or {@code admin} is null but the calling application is not a delegated
7144      *         certificate installer or credential management app.
7145      * @see android.security.KeyChain#getCertificateChain
7146      * @see #setDelegatedScopes
7147      * @see #DELEGATION_CERT_INSTALL
7148      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, int flags)7149     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
7150             @NonNull Certificate[] certs, @NonNull String alias, int flags) {
7151         throwIfParentInstance("installKeyPair");
7152         boolean requestAccess = (flags & INSTALLKEY_REQUEST_CREDENTIALS_ACCESS)
7153                 == INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
7154         boolean isUserSelectable = (flags & INSTALLKEY_SET_USER_SELECTABLE)
7155                 == INSTALLKEY_SET_USER_SELECTABLE;
7156         try {
7157             final byte[] pemCert = Credentials.convertToPem(certs[0]);
7158             byte[] pemChain = null;
7159             if (certs.length > 1) {
7160                 pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length));
7161             }
7162             final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
7163                     .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
7164             return mService.installKeyPair(admin, mContext.getPackageName(), pkcs8Key, pemCert,
7165                     pemChain, alias, requestAccess, isUserSelectable);
7166         } catch (RemoteException e) {
7167             throw e.rethrowFromSystemServer();
7168         } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
7169             Log.w(TAG, "Failed to obtain private key material", e);
7170         } catch (CertificateException | IOException e) {
7171             Log.w(TAG, "Could not pem-encode certificate", e);
7172         }
7173         return false;
7174     }
7175 
7176     /**
7177      * This API can be called by the following to remove a certificate and private key pair
7178      * installed under a given alias:
7179      * <ul>
7180      *    <li>Device owner</li>
7181      *    <li>Profile owner</li>
7182      *    <li>Delegated certificate installer</li>
7183      *    <li>Credential management app</li>
7184      * </ul>
7185      *
7186      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7187      * can call this API. If called by the credential management app, the componentName must be
7188      * {@code null}. Note, there can only be a credential management app on an unmanaged device.
7189      *
7190      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7191      *        {@code null} if calling from a delegated certificate installer.
7192      * @param alias The private key alias under which the certificate is installed.
7193      * @return {@code true} if the private key alias no longer exists, {@code false} otherwise.
7194      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7195      *         owner, or {@code admin} is null but the calling application is not a delegated
7196      *         certificate installer or credential management app.
7197      * @see #setDelegatedScopes
7198      * @see #DELEGATION_CERT_INSTALL
7199      */
removeKeyPair(@ullable ComponentName admin, @NonNull String alias)7200     public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
7201         throwIfParentInstance("removeKeyPair");
7202         try {
7203             return mService.removeKeyPair(admin, mContext.getPackageName(), alias);
7204         } catch (RemoteException e) {
7205             throw e.rethrowFromSystemServer();
7206         }
7207     }
7208 
7209     // STOPSHIP(b/174298501): clarify the expected return value following generateKeyPair call.
7210     /**
7211      * This API can be called by the following to query whether a certificate and private key are
7212      * installed under a given alias:
7213      * <ul>
7214      *    <li>Device owner</li>
7215      *    <li>Profile owner</li>
7216      *    <li>Delegated certificate installer</li>
7217      *    <li>Credential management app</li>
7218      * </ul>
7219      *
7220      * If called by the credential management app, the alias must exist in the credential
7221      * management app's {@link android.security.AppUriAuthenticationPolicy}.
7222      *
7223      * @param alias The alias under which the key pair is installed.
7224      * @return {@code true} if a key pair with this alias exists, {@code false} otherwise.
7225      * @throws SecurityException if the caller is not a device or profile owner, a delegated
7226      *         certificate installer or the credential management app.
7227      * @see #setDelegatedScopes
7228      * @see #DELEGATION_CERT_INSTALL
7229      */
hasKeyPair(@onNull String alias)7230     public boolean hasKeyPair(@NonNull String alias) {
7231         throwIfParentInstance("hasKeyPair");
7232         try {
7233             return mService.hasKeyPair(mContext.getPackageName(), alias);
7234         } catch (RemoteException e) {
7235             throw e.rethrowFromSystemServer();
7236         }
7237     }
7238 
7239     /**
7240      * This API can be called by the following to generate a new private/public key pair:
7241      * <ul>
7242      *    <li>Device owner</li>
7243      *    <li>Profile owner</li>
7244      *    <li>Delegated certificate installer</li>
7245      *    <li>Credential management app</li>
7246      * </ul>
7247      * If the device supports key generation via secure hardware, this method is useful for
7248      * creating a key in KeyChain that never left the secure hardware. Access to the key is
7249      * controlled the same way as in {@link #installKeyPair}.
7250      *
7251      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7252      * can call this API. If called by the credential management app, the componentName must be
7253      * {@code null}. Note, there can only be a credential management app on an unmanaged device.
7254      *
7255      * <p>Because this method might take several seconds to complete, it should only be called from
7256      * a worker thread. This method returns {@code null} when called from the main thread.
7257      *
7258      * <p>This method is not thread-safe, calling it from multiple threads at the same time will
7259      * result in undefined behavior. If the calling thread is interrupted while the invocation is
7260      * in-flight, it will eventually terminate and return {@code null}.
7261      *
7262      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
7263      * have been given to access the key and certificates associated with this alias will be
7264      * revoked.
7265      *
7266      * <p>Attestation: to enable attestation, set an attestation challenge in {@code keySpec} via
7267      * {@link KeyGenParameterSpec.Builder#setAttestationChallenge}. By specifying flags to the
7268      * {@code idAttestationFlags} parameter, it is possible to request the device's unique
7269      * identity to be included in the attestation record.
7270      *
7271      * <p>Specific identifiers can be included in the attestation record, and an individual
7272      * attestation certificate can be used to sign the attestation record. To find out if the device
7273      * supports these features, refer to {@link #isDeviceIdAttestationSupported()} and
7274      * {@link #isUniqueDeviceAttestationSupported()}.
7275      *
7276      * <p>Device owner, profile owner, their delegated certificate installer and the credential
7277      * management app can use {@link #ID_TYPE_BASE_INFO} to request inclusion of the general device
7278      * information including manufacturer, model, brand, device and product in the attestation
7279      * record.
7280      * Only device owner, profile owner on an organization-owned device or affiliated user, and
7281      * their delegated certificate installers can use {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI}
7282      * and {@link #ID_TYPE_MEID} to request unique device identifiers to be attested (the serial
7283      * number, IMEI and MEID correspondingly), if supported by the device
7284      * (see {@link #isDeviceIdAttestationSupported()}).
7285      * Additionally, device owner, profile owner on an organization-owned device and their delegated
7286      * certificate installers can also request the attestation record to be signed using an
7287      * individual attestation certificate by specifying the {@link #ID_TYPE_INDIVIDUAL_ATTESTATION}
7288      * flag (if supported by the device, see {@link #isUniqueDeviceAttestationSupported()}).
7289      * <p>
7290      * If any of {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID}
7291      * is set, it is implicitly assumed that {@link #ID_TYPE_BASE_INFO} is also set.
7292      * <p>
7293      * Attestation using {@link #ID_TYPE_INDIVIDUAL_ATTESTATION} can only be requested if
7294      * key generation is done in StrongBox.
7295      *
7296      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7297      *            {@code null} if calling from a delegated certificate installer.
7298      * @param algorithm The key generation algorithm, see {@link java.security.KeyPairGenerator}.
7299      * @param keySpec Specification of the key to generate, see
7300      * {@link java.security.KeyPairGenerator}.
7301      * @param idAttestationFlags A bitmask of the identifiers that should be included in the
7302      *        attestation record ({@code ID_TYPE_BASE_INFO}, {@code ID_TYPE_SERIAL},
7303      *        {@code ID_TYPE_IMEI} and {@code ID_TYPE_MEID}), and
7304      *        {@code ID_TYPE_INDIVIDUAL_ATTESTATION} if the attestation record should be signed
7305      *        using an individual attestation certificate.
7306      *        <p>
7307      *        {@code 0} should be passed in if no device identification is required in the
7308      *        attestation record and the batch attestation certificate should be used.
7309      *        <p>
7310      *        If any flag is specified, then an attestation challenge must be included in the
7311      *        {@code keySpec}.
7312      * @return A non-null {@code AttestedKeyPair} if the key generation succeeded, null otherwise.
7313      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7314      *         owner, or {@code admin} is null but the calling application is not a delegated
7315      *         certificate installer or credential management app. If Device ID attestation is
7316      *         requested (using {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} or
7317      *         {@link #ID_TYPE_MEID}), the caller must be the Device Owner or the Certificate
7318      *         Installer delegate.
7319      * @throws IllegalArgumentException in the following cases:
7320      *         <p>
7321      *         <ul>
7322      *         <li>The alias in {@code keySpec} is empty.</li>
7323      *         <li>The algorithm specification in {@code keySpec} is not
7324      *         {@code RSAKeyGenParameterSpec} or {@code ECGenParameterSpec}.</li>
7325      *         <li>Device ID attestation was requested but the {@code keySpec} does not contain an
7326      *         attestation challenge.</li>
7327      *         </ul>
7328      * @throws UnsupportedOperationException if Device ID attestation or individual attestation
7329      *         was requested but the underlying hardware does not support it.
7330      * @throws StrongBoxUnavailableException if the use of StrongBox for key generation was
7331      *         specified in {@code keySpec} but the device does not have one.
7332      * @see KeyGenParameterSpec.Builder#setAttestationChallenge(byte[])
7333      */
generateKeyPair(@ullable ComponentName admin, @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec, @AttestationIdType int idAttestationFlags)7334     public AttestedKeyPair generateKeyPair(@Nullable ComponentName admin,
7335             @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec,
7336             @AttestationIdType int idAttestationFlags) {
7337         throwIfParentInstance("generateKeyPair");
7338         try {
7339             final ParcelableKeyGenParameterSpec parcelableSpec =
7340                     new ParcelableKeyGenParameterSpec(keySpec);
7341             KeymasterCertificateChain attestationChain = new KeymasterCertificateChain();
7342 
7343             // Translate ID attestation flags to values used by AttestationUtils
7344             final boolean success = mService.generateKeyPair(
7345                     admin, mContext.getPackageName(), algorithm, parcelableSpec,
7346                     idAttestationFlags, attestationChain);
7347             if (!success) {
7348                 Log.e(TAG, "Error generating key via DevicePolicyManagerService.");
7349                 return null;
7350             }
7351 
7352             final String alias = keySpec.getKeystoreAlias();
7353             final KeyPair keyPair = KeyChain.getKeyPair(mContext, alias);
7354             Certificate[] outputChain = null;
7355             try {
7356                 if (AttestationUtils.isChainValid(attestationChain)) {
7357                     outputChain = AttestationUtils.parseCertificateChain(attestationChain);
7358                 }
7359             } catch (KeyAttestationException e) {
7360                 Log.e(TAG, "Error parsing attestation chain for alias " + alias, e);
7361                 mService.removeKeyPair(admin, mContext.getPackageName(), alias);
7362                 return null;
7363             }
7364             return new AttestedKeyPair(keyPair, outputChain);
7365         } catch (RemoteException e) {
7366             throw e.rethrowFromSystemServer();
7367         } catch (KeyChainException e) {
7368             Log.w(TAG, "Failed to generate key", e);
7369         } catch (InterruptedException e) {
7370             Log.w(TAG, "Interrupted while generating key", e);
7371             Thread.currentThread().interrupt();
7372         } catch (ServiceSpecificException e) {
7373             Log.w(TAG, String.format("Key Generation failure: %d", e.errorCode));
7374             switch (e.errorCode) {
7375                 case KEY_GEN_STRONGBOX_UNAVAILABLE:
7376                     throw new StrongBoxUnavailableException("No StrongBox for key generation.");
7377                 default:
7378                     throw new RuntimeException(
7379                             String.format("Unknown error while generating key: %d", e.errorCode));
7380             }
7381         }
7382         return null;
7383     }
7384 
7385     /**
7386      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7387      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to grant an application access
7388      * to an already-installed (or generated) KeyChain key.
7389      * This is useful (in combination with {@link #installKeyPair} or {@link #generateKeyPair}) to
7390      * let an application call {@link android.security.KeyChain#getPrivateKey} without having to
7391      * call {@link android.security.KeyChain#choosePrivateKeyAlias} first.
7392      *
7393      * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED}
7394      * broadcast when access to a key is granted.
7395      *
7396      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7397      *        {@code null} if calling from a delegated certificate chooser.
7398      * @param alias The alias of the key to grant access to.
7399      * @param packageName The name of the (already installed) package to grant access to.
7400      * @return {@code true} if the grant was set successfully, {@code false} otherwise.
7401      *
7402      * @throws SecurityException if the caller is not a device owner, a profile owner or
7403      *         delegated certificate chooser.
7404      * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if
7405      *         {@code packageName} is not a name of an installed package.
7406      * @see #revokeKeyPairFromApp
7407      */
grantKeyPairToApp(@ullable ComponentName admin, @NonNull String alias, @NonNull String packageName)7408     public boolean grantKeyPairToApp(@Nullable ComponentName admin, @NonNull String alias,
7409             @NonNull String packageName) {
7410         throwIfParentInstance("grantKeyPairToApp");
7411         try {
7412             return mService.setKeyGrantForApp(
7413                     admin, mContext.getPackageName(), alias, packageName, true);
7414         } catch (RemoteException e) {
7415             e.rethrowFromSystemServer();
7416         }
7417         return false;
7418     }
7419 
7420     /**
7421      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7422      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to query which apps have access
7423      * to a given KeyChain key.
7424      *
7425      * Key are granted on a per-UID basis, so if several apps share the same UID, granting access to
7426      * one of them automatically grants it to others. This method returns a map containing one entry
7427      * per grantee UID. Entries have UIDs as keys and sets of corresponding package names as values.
7428      * In particular, grantee packages that don't share UID with other packages are represented by
7429      * entries having singleton sets as values.
7430      *
7431      * @param alias The alias of the key to grant access to.
7432      * @return apps that have access to a given key, arranged in a map from UID to sets of
7433      *       package names.
7434      *
7435      * @throws SecurityException if the caller is not a device owner, a profile owner or
7436      *         delegated certificate chooser.
7437      * @throws IllegalArgumentException if {@code alias} doesn't correspond to an existing key.
7438      *
7439      * @see #grantKeyPairToApp(ComponentName, String, String)
7440      */
getKeyPairGrants(@onNull String alias)7441     public @NonNull Map<Integer, Set<String>> getKeyPairGrants(@NonNull String alias) {
7442         throwIfParentInstance("getKeyPairGrants");
7443         try {
7444             // The result is wrapped into intermediate parcelable representation.
7445             return mService.getKeyPairGrants(mContext.getPackageName(), alias).getPackagesByUid();
7446         } catch (RemoteException e) {
7447             e.rethrowFromSystemServer();
7448         }
7449         return null;
7450     }
7451 
7452     /**
7453      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7454      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to revoke an application's
7455      * grant to a KeyChain key pair.
7456      * Calls by the application to {@link android.security.KeyChain#getPrivateKey}
7457      * will fail after the grant is revoked.
7458      *
7459      * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED}
7460      * broadcast when access to a key is revoked.
7461      *
7462      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7463      *        {@code null} if calling from a delegated certificate chooser.
7464      * @param alias The alias of the key to revoke access from.
7465      * @param packageName The name of the (already installed) package to revoke access from.
7466      * @return {@code true} if the grant was revoked successfully, {@code false} otherwise.
7467      *
7468      * @throws SecurityException if the caller is not a device owner, a profile owner or
7469      *         delegated certificate chooser.
7470      * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if
7471      *         {@code packageName} is not a name of an installed package.
7472      * @see #grantKeyPairToApp
7473      */
revokeKeyPairFromApp(@ullable ComponentName admin, @NonNull String alias, @NonNull String packageName)7474     public boolean revokeKeyPairFromApp(@Nullable ComponentName admin, @NonNull String alias,
7475             @NonNull String packageName) {
7476         throwIfParentInstance("revokeKeyPairFromApp");
7477         try {
7478             return mService.setKeyGrantForApp(
7479                     admin, mContext.getPackageName(), alias, packageName, false);
7480         } catch (RemoteException e) {
7481             e.rethrowFromSystemServer();
7482         }
7483         return false;
7484     }
7485 
7486     /**
7487      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7488      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to allow using a KeyChain key
7489      * pair for authentication to Wifi networks. The key can then be used in configurations passed
7490      * to {@link android.net.wifi.WifiManager#addNetwork}.
7491      *
7492      * @param alias The alias of the key pair.
7493      * @return {@code true} if the operation was set successfully, {@code false} otherwise.
7494      *
7495      * @throws SecurityException if the caller is not a device owner, a profile owner or
7496      *         delegated certificate chooser.
7497      * @see #revokeKeyPairFromWifiAuth
7498      */
grantKeyPairToWifiAuth(@onNull String alias)7499     public boolean grantKeyPairToWifiAuth(@NonNull String alias) {
7500         throwIfParentInstance("grantKeyPairToWifiAuth");
7501         try {
7502             return mService.setKeyGrantToWifiAuth(mContext.getPackageName(), alias, true);
7503         } catch (RemoteException e) {
7504             e.rethrowFromSystemServer();
7505         }
7506         return false;
7507     }
7508 
7509     /**
7510      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7511      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to deny using a KeyChain key
7512      * pair for authentication to Wifi networks. Configured networks using this key won't be able to
7513      * authenticate.
7514      *
7515      * @param alias The alias of the key pair.
7516      * @return {@code true} if the operation was set successfully, {@code false} otherwise.
7517      *
7518      * @throws SecurityException if the caller is not a device owner, a profile owner or
7519      *         delegated certificate chooser.
7520      * @see #grantKeyPairToWifiAuth
7521      */
revokeKeyPairFromWifiAuth(@onNull String alias)7522     public boolean revokeKeyPairFromWifiAuth(@NonNull String alias) {
7523         throwIfParentInstance("revokeKeyPairFromWifiAuth");
7524         try {
7525             return mService.setKeyGrantToWifiAuth(mContext.getPackageName(), alias, false);
7526         } catch (RemoteException e) {
7527             e.rethrowFromSystemServer();
7528         }
7529         return false;
7530     }
7531 
7532     /**
7533      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7534      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to query whether a KeyChain key
7535      * pair can be used for authentication to Wifi networks.
7536      *
7537      * @param alias The alias of the key pair.
7538      * @return {@code true} if the key pair can be used, {@code false} otherwise.
7539      *
7540      * @throws SecurityException if the caller is not a device owner, a profile owner or
7541      *         delegated certificate chooser.
7542      * @see #grantKeyPairToWifiAuth
7543      */
isKeyPairGrantedToWifiAuth(@onNull String alias)7544     public boolean isKeyPairGrantedToWifiAuth(@NonNull String alias) {
7545         throwIfParentInstance("isKeyPairGrantedToWifiAuth");
7546         try {
7547             return mService.isKeyPairGrantedToWifiAuth(mContext.getPackageName(), alias);
7548         } catch (RemoteException e) {
7549             e.rethrowFromSystemServer();
7550         }
7551         return false;
7552     }
7553 
7554     /**
7555      * Returns {@code true} if the device supports attestation of device identifiers in addition
7556      * to key attestation. See
7557      * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}
7558      * @return {@code true} if Device ID attestation is supported.
7559      */
isDeviceIdAttestationSupported()7560     public boolean isDeviceIdAttestationSupported() {
7561         PackageManager pm = mContext.getPackageManager();
7562         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ID_ATTESTATION);
7563     }
7564 
7565     /**
7566      * Returns {@code true} if the StrongBox Keymaster implementation on the device was provisioned
7567      * with an individual attestation certificate and can sign attestation records using it (as
7568      * attestation using an individual attestation certificate is a feature only Keymaster
7569      * implementations with StrongBox security level can implement).
7570      * For use prior to calling
7571      * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}.
7572      * @return {@code true} if individual attestation is supported.
7573      */
isUniqueDeviceAttestationSupported()7574     public boolean isUniqueDeviceAttestationSupported() {
7575         PackageManager pm = mContext.getPackageManager();
7576         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_UNIQUE_ATTESTATION);
7577     }
7578 
7579     /**
7580      * This API can be called by the following to associate certificates with a key pair that was
7581      * generated using {@link #generateKeyPair}, and set whether the key is available for the user
7582      * to choose in the certificate selection prompt:
7583      * <ul>
7584      *    <li>Device owner</li>
7585      *    <li>Profile owner</li>
7586      *    <li>Delegated certificate installer</li>
7587      *    <li>Credential management app</li>
7588      * </ul>
7589      *
7590      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7591      * can call this API. If called by the credential management app, the componentName must be
7592      * {@code null}. Note, there can only be a credential management app on an unmanaged device.
7593      *
7594      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7595      *            {@code null} if calling from a delegated certificate installer.
7596      * @param alias The private key alias under which to install the certificate. The {@code alias}
7597      *        should denote an existing private key. If a certificate with that alias already
7598      *        exists, it will be overwritten.
7599      * @param certs The certificate chain to install. The chain should start with the leaf
7600      *        certificate and include the chain of trust in order. This will be returned by
7601      *        {@link android.security.KeyChain#getCertificateChain}.
7602      * @param isUserSelectable {@code true} to indicate that a user can select this key via the
7603      *        certificate selection prompt, {@code false} to indicate that this key can only be
7604      *        granted access by implementing
7605      *        {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
7606      * @return {@code true} if the provided {@code alias} exists and the certificates has been
7607      *        successfully associated with it, {@code false} otherwise.
7608      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7609      *         owner, or {@code admin} is null but the calling application is not a delegated
7610      *         certificate installer or credential management app.
7611      */
setKeyPairCertificate(@ullable ComponentName admin, @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable)7612     public boolean setKeyPairCertificate(@Nullable ComponentName admin,
7613             @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable) {
7614         throwIfParentInstance("setKeyPairCertificate");
7615         try {
7616             final byte[] pemCert = Credentials.convertToPem(certs.get(0));
7617             byte[] pemChain = null;
7618             if (certs.size() > 1) {
7619                 pemChain = Credentials.convertToPem(
7620                         certs.subList(1, certs.size()).toArray(new Certificate[0]));
7621             }
7622             return mService.setKeyPairCertificate(admin, mContext.getPackageName(), alias, pemCert,
7623                     pemChain, isUserSelectable);
7624         } catch (RemoteException e) {
7625             throw e.rethrowFromSystemServer();
7626         } catch (CertificateException | IOException e) {
7627             Log.w(TAG, "Could not pem-encode certificate", e);
7628         }
7629         return false;
7630     }
7631 
7632 
7633     /**
7634      * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
7635      * doesn't exist.
7636      */
getCaCertAlias(byte[] certBuffer)7637     private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
7638         final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
7639         final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
7640                               new ByteArrayInputStream(certBuffer));
7641         return new TrustedCertificateStore().getCertificateAlias(cert);
7642     }
7643 
7644     /**
7645      * Called by a profile owner or device owner to grant access to privileged certificate
7646      * manipulation APIs to a third-party certificate installer app. Granted APIs include
7647      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
7648      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
7649      * <p>
7650      * Delegated certificate installer is a per-user state. The delegated access is persistent until
7651      * it is later cleared by calling this method with a null value or uninstallling the certificate
7652      * installer.
7653      * <p>
7654      * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
7655      * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
7656      * supplied certificate installer package must be installed when calling this API, otherwise an
7657      * {@link IllegalArgumentException} will be thrown.
7658      *
7659      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7660      * @param installerPackage The package name of the certificate installer which will be given
7661      *            access. If {@code null} is given the current package will be cleared.
7662      * @throws SecurityException if {@code admin} is not a device or a profile owner.
7663      *
7664      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
7665      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
7666      */
7667     @Deprecated
setCertInstallerPackage(@onNull ComponentName admin, @Nullable String installerPackage)7668     public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
7669             installerPackage) throws SecurityException {
7670         throwIfParentInstance("setCertInstallerPackage");
7671         if (mService != null) {
7672             try {
7673                 mService.setCertInstallerPackage(admin, installerPackage);
7674             } catch (RemoteException e) {
7675                 throw e.rethrowFromSystemServer();
7676             }
7677         }
7678     }
7679 
7680     /**
7681      * Called by a profile owner or device owner to retrieve the certificate installer for the user,
7682      * or {@code null} if none is set. If there are multiple delegates this function will return one
7683      * of them.
7684      *
7685      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7686      * @return The package name of the current delegated certificate installer, or {@code null} if
7687      *         none is set.
7688      * @throws SecurityException if {@code admin} is not a device or a profile owner.
7689      *
7690      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
7691      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
7692      */
7693     @Deprecated
getCertInstallerPackage(@onNull ComponentName admin)7694     public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
7695             throws SecurityException {
7696         throwIfParentInstance("getCertInstallerPackage");
7697         if (mService != null) {
7698             try {
7699                 return mService.getCertInstallerPackage(admin);
7700             } catch (RemoteException e) {
7701                 throw e.rethrowFromSystemServer();
7702             }
7703         }
7704         return null;
7705     }
7706 
7707     /**
7708      * Called by a profile owner or device owner to grant access to privileged APIs to another app.
7709      * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*}
7710      * constants.
7711      * <p>
7712      * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be
7713      * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra
7714      * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the
7715      * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag.
7716      * <p>
7717      * Delegated scopes are a per-user state. The delegated access is persistent until it is later
7718      * cleared by calling this method with an empty {@code scopes} list or uninstalling the
7719      * {@code delegatePackage}.
7720      *
7721      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7722      * @param delegatePackage The package name of the app which will be given access.
7723      * @param scopes The groups of privileged APIs whose access should be granted to
7724      *            {@code delegatedPackage}.
7725      * @throws SecurityException if {@code admin} is not a device or a profile owner.
7726      */
setDelegatedScopes(@onNull ComponentName admin, @NonNull String delegatePackage, @NonNull List<String> scopes)7727      public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage,
7728             @NonNull List<String> scopes) {
7729         throwIfParentInstance("setDelegatedScopes");
7730         if (mService != null) {
7731             try {
7732                 mService.setDelegatedScopes(admin, delegatePackage, scopes);
7733             } catch (RemoteException e) {
7734                 throw e.rethrowFromSystemServer();
7735             }
7736         }
7737     }
7738 
7739     /**
7740      * Called by a profile owner or device owner to retrieve a list of the scopes given to a
7741      * delegate package. Other apps can use this method to retrieve their own delegated scopes by
7742      * passing {@code null} for {@code admin} and their own package name as
7743      * {@code delegatedPackage}.
7744      *
7745      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7746      *            {@code null} if the caller is {@code delegatedPackage}.
7747      * @param delegatedPackage The package name of the app whose scopes should be retrieved.
7748      * @return A list containing the scopes given to {@code delegatedPackage}.
7749      * @throws SecurityException if {@code admin} is not a device or a profile owner.
7750      */
7751      @NonNull
getDelegatedScopes(@ullable ComponentName admin, @NonNull String delegatedPackage)7752      public List<String> getDelegatedScopes(@Nullable ComponentName admin,
7753              @NonNull String delegatedPackage) {
7754          throwIfParentInstance("getDelegatedScopes");
7755          if (mService != null) {
7756              try {
7757                  return mService.getDelegatedScopes(admin, delegatedPackage);
7758              } catch (RemoteException e) {
7759                  throw e.rethrowFromSystemServer();
7760              }
7761          }
7762          return null;
7763     }
7764 
7765     /**
7766      * Called by a profile owner or device owner to retrieve a list of delegate packages that were
7767      * granted a delegation scope.
7768      *
7769      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7770      * @param delegationScope The scope whose delegates should be retrieved.
7771      * @return A list of package names of the current delegated packages for
7772                {@code delegationScope}.
7773      * @throws SecurityException if {@code admin} is not a device or a profile owner.
7774      */
7775      @Nullable
getDelegatePackages(@onNull ComponentName admin, @NonNull String delegationScope)7776      public List<String> getDelegatePackages(@NonNull ComponentName admin,
7777              @NonNull String delegationScope) {
7778         throwIfParentInstance("getDelegatePackages");
7779         if (mService != null) {
7780             try {
7781                 return mService.getDelegatePackages(admin, delegationScope);
7782             } catch (RemoteException e) {
7783                 throw e.rethrowFromSystemServer();
7784             }
7785         }
7786         return null;
7787     }
7788 
7789     /**
7790      * Service-specific error code used in implementation of {@code setAlwaysOnVpnPackage} methods.
7791      * @hide
7792      */
7793     public static final int ERROR_VPN_PACKAGE_NOT_FOUND = 1;
7794 
7795     /**
7796      * Called by a device or profile owner to configure an always-on VPN connection through a
7797      * specific application for the current user. This connection is automatically granted and
7798      * persisted after a reboot.
7799      * <p> To support the always-on feature, an app must
7800      * <ul>
7801      *     <li>declare a {@link android.net.VpnService} in its manifest, guarded by
7802      *         {@link android.Manifest.permission#BIND_VPN_SERVICE};</li>
7803      *     <li>target {@link android.os.Build.VERSION_CODES#N API 24} or above; and</li>
7804      *     <li><i>not</i> explicitly opt out of the feature through
7805      *         {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}.</li>
7806      * </ul>
7807      * The call will fail if called with the package name of an unsupported VPN app.
7808      * <p> Enabling lockdown via {@code lockdownEnabled} argument carries the risk that any failure
7809      * of the VPN provider could break networking for all apps. This method clears any lockdown
7810      * allowlist set by {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)}.
7811      * <p> Starting from {@link android.os.Build.VERSION_CODES#S API 31} calling this method with
7812      * {@code vpnPackage} set to {@code null} only removes the existing configuration if it was
7813      * previously created by this admin. To remove VPN configuration created by the user use
7814      * {@link UserManager#DISALLOW_CONFIG_VPN}.
7815      *
7816      * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
7817      *        remove an existing always-on VPN configuration.
7818      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
7819      *        {@code false} otherwise. This has no effect when clearing.
7820      * @throws SecurityException if {@code admin} is not a device or a profile owner.
7821      * @throws NameNotFoundException if {@code vpnPackage} is not installed.
7822      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
7823      *         set as always-on, or if always-on VPN is not available.
7824      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
7825      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled)7826     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
7827             boolean lockdownEnabled) throws NameNotFoundException {
7828         setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled, Collections.emptySet());
7829     }
7830 
7831     /**
7832      * A version of {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} that allows the
7833      * admin to specify a set of apps that should be able to access the network directly when VPN
7834      * is not connected. When VPN connects these apps switch over to VPN if allowed to use that VPN.
7835      * System apps can always bypass VPN.
7836      * <p> Note that the system doesn't update the allowlist when packages are installed or
7837      * uninstalled, the admin app must call this method to keep the list up to date.
7838      * <p> When {@code lockdownEnabled} is false {@code lockdownAllowlist} is ignored . When
7839      * {@code lockdownEnabled} is {@code true} and {@code lockdownAllowlist} is {@code null} or
7840      * empty, only system apps can bypass VPN.
7841      * <p> Setting always-on VPN package to {@code null} or using
7842      * {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} clears lockdown allowlist.
7843      *
7844      * @param vpnPackage package name for an installed VPN app on the device, or {@code null}
7845      *         to remove an existing always-on VPN configuration
7846      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
7847      *         {@code false} otherwise. This has no effect when clearing.
7848      * @param lockdownAllowlist Packages that will be able to access the network directly when VPN
7849      *         is in lockdown mode but not connected. Has no effect when clearing.
7850      * @throws SecurityException if {@code admin} is not a device or a profile
7851      *         owner.
7852      * @throws NameNotFoundException if {@code vpnPackage} or one of
7853      *         {@code lockdownAllowlist} is not installed.
7854      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does
7855      *         not support being set as always-on, or if always-on VPN is not
7856      *         available.
7857      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled, @Nullable Set<String> lockdownAllowlist)7858     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
7859             boolean lockdownEnabled, @Nullable Set<String> lockdownAllowlist)
7860             throws NameNotFoundException {
7861         throwIfParentInstance("setAlwaysOnVpnPackage");
7862         if (mService != null) {
7863             try {
7864                 mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled,
7865                         lockdownAllowlist == null ? null : new ArrayList<>(lockdownAllowlist));
7866             } catch (ServiceSpecificException e) {
7867                 switch (e.errorCode) {
7868                     case ERROR_VPN_PACKAGE_NOT_FOUND:
7869                         throw new NameNotFoundException(e.getMessage());
7870                     default:
7871                         throw new RuntimeException(
7872                                 "Unknown error setting always-on VPN: " + e.errorCode, e);
7873                 }
7874             } catch (RemoteException e) {
7875                 throw e.rethrowFromSystemServer();
7876             }
7877         }
7878     }
7879 
7880     /**
7881      * Called by device or profile owner to query whether current always-on VPN is configured in
7882      * lockdown mode. Returns {@code false} when no always-on configuration is set.
7883      *
7884      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7885      *
7886      * @throws SecurityException if {@code admin} is not a device or a profile owner.
7887      *
7888      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean)
7889      */
isAlwaysOnVpnLockdownEnabled(@onNull ComponentName admin)7890     public boolean isAlwaysOnVpnLockdownEnabled(@NonNull ComponentName admin) {
7891         throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
7892         if (mService != null) {
7893             try {
7894                 // Starting from Android R, the caller can pass the permission check in
7895                 // DevicePolicyManagerService if it holds android.permission.MAINLINE_NETWORK_STACK.
7896                 // Note that the android.permission.MAINLINE_NETWORK_STACK is a signature permission
7897                 // which is used by the NetworkStack mainline module.
7898                 return mService.isAlwaysOnVpnLockdownEnabled(admin);
7899             } catch (RemoteException e) {
7900                 throw e.rethrowFromSystemServer();
7901             }
7902         }
7903         return false;
7904     }
7905 
7906     /**
7907      * Returns whether the admin has enabled always-on VPN lockdown for the current user.
7908      *
7909      * Only callable by the system.
7910     * @hide
7911     */
7912     @UserHandleAware
isAlwaysOnVpnLockdownEnabled()7913     public boolean isAlwaysOnVpnLockdownEnabled() {
7914         throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
7915         if (mService != null) {
7916             try {
7917                 return mService.isAlwaysOnVpnLockdownEnabledForUser(myUserId());
7918             } catch (RemoteException e) {
7919                 throw e.rethrowFromSystemServer();
7920             }
7921         }
7922         return false;
7923     }
7924 
7925     /**
7926      * Called by device or profile owner to query the set of packages that are allowed to access
7927      * the network directly when always-on VPN is in lockdown mode but not connected. Returns
7928      * {@code null} when always-on VPN is not active or not in lockdown mode.
7929      *
7930      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7931      *
7932      * @throws SecurityException if {@code admin} is not a device or a profile owner.
7933      *
7934      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
7935      */
getAlwaysOnVpnLockdownWhitelist(@onNull ComponentName admin)7936     public @Nullable Set<String> getAlwaysOnVpnLockdownWhitelist(@NonNull ComponentName admin) {
7937         throwIfParentInstance("getAlwaysOnVpnLockdownWhitelist");
7938         if (mService != null) {
7939             try {
7940                 final List<String> allowlist =
7941                         mService.getAlwaysOnVpnLockdownAllowlist(admin);
7942                 return allowlist == null ? null : new HashSet<>(allowlist);
7943             } catch (RemoteException e) {
7944                 throw e.rethrowFromSystemServer();
7945             }
7946         }
7947         return null;
7948     }
7949 
7950     /**
7951      * Called by a device or profile owner to read the name of the package administering an
7952      * always-on VPN connection for the current user. If there is no such package, or the always-on
7953      * VPN is provided by the system instead of by an application, {@code null} will be returned.
7954      *
7955      * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
7956      *         is set.
7957      * @throws SecurityException if {@code admin} is not a device or a profile owner.
7958      */
getAlwaysOnVpnPackage(@onNull ComponentName admin)7959     public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
7960         throwIfParentInstance("getAlwaysOnVpnPackage");
7961         if (mService != null) {
7962             try {
7963                 return mService.getAlwaysOnVpnPackage(admin);
7964             } catch (RemoteException e) {
7965                 throw e.rethrowFromSystemServer();
7966             }
7967         }
7968         return null;
7969     }
7970 
7971     /**
7972      * Returns the VPN package name if the admin has enabled always-on VPN on the current user,
7973      * or {@code null} if none is set.
7974      *
7975      * Only callable by the system.
7976      * @hide
7977      */
7978     @UserHandleAware
getAlwaysOnVpnPackage()7979     public @Nullable String getAlwaysOnVpnPackage() {
7980         throwIfParentInstance("getAlwaysOnVpnPackage");
7981         if (mService != null) {
7982             try {
7983                 return mService.getAlwaysOnVpnPackageForUser(myUserId());
7984             } catch (RemoteException e) {
7985                 throw e.rethrowFromSystemServer();
7986             }
7987         }
7988         return null;
7989     }
7990 
7991     /**
7992      * Called by an application that is administering the device to disable all cameras on the
7993      * device, for this user. After setting this, no applications running as this user will be able
7994      * to access any cameras on the device.
7995      * <p>
7996      * This method can be called on the {@link DevicePolicyManager} instance,
7997      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
7998      * the profile owner of an organization-owned managed profile.
7999      * <p>
8000      * If the caller is device owner, then the restriction will be applied to all users. If
8001      * called on the parent instance, then the restriction will be applied on the personal profile.
8002      * <p>
8003      * The calling device admin must have requested
8004      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
8005      * not, a security exception will be thrown.
8006      * <p>
8007      * <b>Note</b>, this policy type is deprecated for legacy device admins since
8008      * {@link android.os.Build.VERSION_CODES#Q}. On Android
8009      * {@link android.os.Build.VERSION_CODES#Q} devices, legacy device admins targeting SDK
8010      * version {@link android.os.Build.VERSION_CODES#P} or below can still call this API to
8011      * disable camera, while legacy device admins targeting SDK version
8012      * {@link android.os.Build.VERSION_CODES#Q} will receive a SecurityException. Starting
8013      * from Android {@link android.os.Build.VERSION_CODES#R}, requests to disable camera from
8014      * legacy device admins targeting SDK version {@link android.os.Build.VERSION_CODES#P} or
8015      * below will be silently ignored.
8016      *
8017      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8018      * @param disabled Whether or not the camera should be disabled.
8019      * @throws SecurityException if {@code admin} is not an active administrator or does not use
8020      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
8021      */
setCameraDisabled(@onNull ComponentName admin, boolean disabled)8022     public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
8023         if (mService != null) {
8024             try {
8025                 mService.setCameraDisabled(admin, disabled, mParentInstance);
8026             } catch (RemoteException e) {
8027                 throw e.rethrowFromSystemServer();
8028             }
8029         }
8030     }
8031 
8032     /**
8033      * Determine whether or not the device's cameras have been disabled for this user,
8034      * either by the calling admin, if specified, or all admins.
8035      * <p>
8036      * This method can be called on the {@link DevicePolicyManager} instance,
8037      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
8038      * the profile owner of an organization-owned managed profile.
8039      *
8040      * @param admin The name of the admin component to check, or {@code null} to check whether any admins
8041      * have disabled the camera
8042      */
getCameraDisabled(@ullable ComponentName admin)8043     public boolean getCameraDisabled(@Nullable ComponentName admin) {
8044         return getCameraDisabled(admin, myUserId());
8045     }
8046 
8047     /** @hide per-user version */
8048     @UnsupportedAppUsage
getCameraDisabled(@ullable ComponentName admin, int userHandle)8049     public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
8050         if (mService != null) {
8051             try {
8052                 return mService.getCameraDisabled(admin, userHandle, mParentInstance);
8053             } catch (RemoteException e) {
8054                 throw e.rethrowFromSystemServer();
8055             }
8056         }
8057         return false;
8058     }
8059 
8060     /**
8061      * Called by a device owner to request a bugreport.
8062      * <p>
8063      * If the device contains secondary users or profiles, they must be affiliated with the device.
8064      * Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
8065      *
8066      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8067      * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
8068      *         wasn't triggered because a previous bugreport operation is still active (either the
8069      *         bugreport is still running or waiting for the user to share or decline)
8070      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
8071      *         profile or secondary user that is not affiliated with the device.
8072      * @see #isAffiliatedUser
8073      */
requestBugreport(@onNull ComponentName admin)8074     public boolean requestBugreport(@NonNull ComponentName admin) {
8075         throwIfParentInstance("requestBugreport");
8076         if (mService != null) {
8077             try {
8078                 return mService.requestBugreport(admin);
8079             } catch (RemoteException e) {
8080                 throw e.rethrowFromSystemServer();
8081             }
8082         }
8083         return false;
8084     }
8085 
8086     /**
8087      * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
8088      * screen capture also prevents the content from being shown on display devices that do not have
8089      * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
8090      * secure surfaces and secure displays.
8091      * <p>
8092      * This method can be called on the {@link DevicePolicyManager} instance, returned by
8093      * {@link #getParentProfileInstance(ComponentName)}, where the calling device admin must be
8094      * the profile owner of an organization-owned managed profile. If it is not, a security
8095      * exception will be thrown.
8096      * <p>
8097      * If the caller is device owner or called on the parent instance by a profile owner of an
8098      * organization-owned managed profile, then the restriction will be applied to all users.
8099      * <p>
8100      * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
8101      * assist requests for all activities of the relevant user.
8102      *
8103      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8104      * @param disabled Whether screen capture is disabled or not.
8105      * @throws SecurityException if {@code admin} is not a device or profile owner or if
8106      *                           called on the parent profile and the {@code admin} is not a
8107      *                           profile owner of an organization-owned managed profile.
8108      */
setScreenCaptureDisabled(@onNull ComponentName admin, boolean disabled)8109     public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
8110         if (mService != null) {
8111             try {
8112                 mService.setScreenCaptureDisabled(admin, disabled, mParentInstance);
8113             } catch (RemoteException e) {
8114                 throw e.rethrowFromSystemServer();
8115             }
8116         }
8117     }
8118 
8119     /**
8120      * Determine whether or not screen capture has been disabled by the calling
8121      * admin, if specified, or all admins.
8122      * <p>
8123      * This method can be called on the {@link DevicePolicyManager} instance,
8124      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
8125      * the profile owner of an organization-owned managed profile (the calling admin must be
8126      * specified).
8127      *
8128      * @param admin The name of the admin component to check, or {@code null} to check whether any
8129      *              admins have disabled screen capture.
8130      */
getScreenCaptureDisabled(@ullable ComponentName admin)8131     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
8132         return getScreenCaptureDisabled(admin, myUserId());
8133     }
8134 
8135     /** @hide per-user version */
getScreenCaptureDisabled(@ullable ComponentName admin, int userHandle)8136     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
8137         if (mService != null) {
8138             try {
8139                 return mService.getScreenCaptureDisabled(admin, userHandle, mParentInstance);
8140             } catch (RemoteException e) {
8141                 throw e.rethrowFromSystemServer();
8142             }
8143         }
8144         return false;
8145     }
8146 
8147     /**
8148      * Called by a device/profile owner to set nearby notification streaming policy. Notification
8149      * streaming is sending notification data from pre-installed apps to nearby devices.
8150      *
8151      * @param policy One of the {@code NearbyStreamingPolicy} constants.
8152      * @throws SecurityException if caller is not a device or profile owner
8153      */
setNearbyNotificationStreamingPolicy(@earbyStreamingPolicy int policy)8154     public void setNearbyNotificationStreamingPolicy(@NearbyStreamingPolicy int policy) {
8155         throwIfParentInstance("setNearbyNotificationStreamingPolicy");
8156         if (mService == null) {
8157             return;
8158         }
8159         try {
8160             mService.setNearbyNotificationStreamingPolicy(policy);
8161         } catch (RemoteException e) {
8162             throw e.rethrowFromSystemServer();
8163         }
8164     }
8165 
8166     /**
8167      * Returns the current runtime nearby notification streaming policy set by the device or profile
8168      * owner.
8169      * <p>
8170      * The caller must be the target user's device owner/profile owner or hold the
8171      * {@link android.Manifest.permission#READ_NEARBY_STREAMING_POLICY READ_NEARBY_STREAMING_POLICY}
8172      * permission.
8173      */
8174     @RequiresPermission(
8175             value = android.Manifest.permission.READ_NEARBY_STREAMING_POLICY,
8176             conditional = true)
getNearbyNotificationStreamingPolicy()8177     public @NearbyStreamingPolicy int getNearbyNotificationStreamingPolicy() {
8178         return getNearbyNotificationStreamingPolicy(myUserId());
8179     }
8180 
8181     /** @hide per-user version */
getNearbyNotificationStreamingPolicy(int userId)8182     public @NearbyStreamingPolicy int getNearbyNotificationStreamingPolicy(int userId) {
8183         throwIfParentInstance("getNearbyNotificationStreamingPolicy");
8184         if (mService == null) {
8185             return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
8186         }
8187         try {
8188             return mService.getNearbyNotificationStreamingPolicy(userId);
8189         } catch (RemoteException re) {
8190             throw re.rethrowFromSystemServer();
8191         }
8192     }
8193 
8194     /**
8195      * Called by a device/profile owner to set nearby app streaming policy. App streaming is when
8196      * the device starts an app on a virtual display and sends a video stream of the app to nearby
8197      * devices.
8198      *
8199      * @param policy One of the {@code NearbyStreamingPolicy} constants.
8200      * @throws SecurityException if caller is not a device or profile owner.
8201      */
setNearbyAppStreamingPolicy(@earbyStreamingPolicy int policy)8202     public void setNearbyAppStreamingPolicy(@NearbyStreamingPolicy int policy) {
8203         throwIfParentInstance("setNearbyAppStreamingPolicy");
8204         if (mService == null) {
8205             return;
8206         }
8207         try {
8208             mService.setNearbyAppStreamingPolicy(policy);
8209         } catch (RemoteException e) {
8210             throw e.rethrowFromSystemServer();
8211         }
8212     }
8213 
8214     /**
8215      * Returns the current runtime nearby app streaming policy set by the device or profile owner.
8216      * <p>
8217      * The caller must be the target user's device owner/profile owner or hold the
8218      * {@link android.Manifest.permission#READ_NEARBY_STREAMING_POLICY READ_NEARBY_STREAMING_POLICY}
8219      * permission.
8220      */
8221     @RequiresPermission(
8222             value = android.Manifest.permission.READ_NEARBY_STREAMING_POLICY,
8223             conditional = true)
getNearbyAppStreamingPolicy()8224     public @NearbyStreamingPolicy int getNearbyAppStreamingPolicy() {
8225         return getNearbyAppStreamingPolicy(myUserId());
8226     }
8227 
8228     /** @hide per-user version */
getNearbyAppStreamingPolicy(int userId)8229     public @NearbyStreamingPolicy int getNearbyAppStreamingPolicy(int userId) {
8230         throwIfParentInstance("getNearbyAppStreamingPolicy");
8231         if (mService == null) {
8232             return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
8233         }
8234         try {
8235             return mService.getNearbyAppStreamingPolicy(userId);
8236         } catch (RemoteException re) {
8237             throw re.rethrowFromSystemServer();
8238         }
8239     }
8240 
8241     /**
8242      * Called by a device owner, or alternatively a profile owner from Android 8.0 (API level 26) or
8243      * higher, to set whether auto time is required. If auto time is required, no user will be able
8244      * set the date and time and network date and time will be used.
8245      * <p>
8246      * Note: if auto time is required the user can still manually set the time zone.
8247      * <p>
8248      * The calling device admin must be a device owner, or alternatively a profile owner from
8249      * Android 8.0 (API level 26) or higher. If it is not, a security exception will be thrown.
8250      * <p>
8251      * Staring from Android 11, this API switches to use
8252      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} to enforce the auto time settings. Calling
8253      * this API to enforce auto time will result in
8254      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being set, while calling this API to lift
8255      * the requirement will result in {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being cleared.
8256      * From Android 11, this API can also no longer be called on a managed profile.
8257      *
8258      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8259      * @param required Whether auto time is set required or not.
8260      * @throws SecurityException if {@code admin} is not a device owner, not a profile owner or
8261      * if this API is called on a managed profile.
8262      * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #setAutoTimeEnabled}
8263      * to turn auto time on or off and use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
8264      * to prevent the user from changing this setting.
8265      */
8266     @Deprecated
setAutoTimeRequired(@onNull ComponentName admin, boolean required)8267     public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
8268         throwIfParentInstance("setAutoTimeRequired");
8269         if (mService != null) {
8270             try {
8271                 mService.setAutoTimeRequired(admin, required);
8272             } catch (RemoteException e) {
8273                 throw e.rethrowFromSystemServer();
8274             }
8275         }
8276     }
8277 
8278     /**
8279      * @return true if auto time is required.
8280      * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #getAutoTimeEnabled}
8281      */
8282     @Deprecated
getAutoTimeRequired()8283     public boolean getAutoTimeRequired() {
8284         throwIfParentInstance("getAutoTimeRequired");
8285         if (mService != null) {
8286             try {
8287                 return mService.getAutoTimeRequired();
8288             } catch (RemoteException e) {
8289                 throw e.rethrowFromSystemServer();
8290             }
8291         }
8292         return false;
8293     }
8294 
8295     /**
8296      * Called by a device owner, a profile owner for the primary user or a profile
8297      * owner of an organization-owned managed profile to turn auto time on and off.
8298      * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
8299      * to prevent the user from changing this setting.
8300      * <p>
8301      * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
8302      * no user will be able set the date and time. Instead, the network date
8303      * and time will be used.
8304      *
8305      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8306      * @param enabled Whether time should be obtained automatically from the network or not.
8307      * @throws SecurityException if caller is not a device owner, a profile owner for the
8308      * primary user, or a profile owner of an organization-owned managed profile.
8309      */
setAutoTimeEnabled(@onNull ComponentName admin, boolean enabled)8310     public void setAutoTimeEnabled(@NonNull ComponentName admin, boolean enabled) {
8311         if (mService != null) {
8312             try {
8313                 mService.setAutoTimeEnabled(admin, enabled);
8314             } catch (RemoteException e) {
8315                 throw e.rethrowFromSystemServer();
8316             }
8317         }
8318     }
8319 
8320     /**
8321      * @return true if auto time is enabled on the device.
8322      * @throws SecurityException if caller is not a device owner, a profile owner for the
8323      * primary user, or a profile owner of an organization-owned managed profile.
8324      */
getAutoTimeEnabled(@onNull ComponentName admin)8325     public boolean getAutoTimeEnabled(@NonNull ComponentName admin) {
8326         if (mService != null) {
8327             try {
8328                 return mService.getAutoTimeEnabled(admin);
8329             } catch (RemoteException e) {
8330                 throw e.rethrowFromSystemServer();
8331             }
8332         }
8333         return false;
8334     }
8335 
8336     /**
8337      * Called by a device owner, a profile owner for the primary user or a profile
8338      * owner of an organization-owned managed profile to turn auto time zone on and off.
8339      * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
8340      * to prevent the user from changing this setting.
8341      * <p>
8342      * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
8343      * no user will be able set the date and time zone. Instead, the network date
8344      * and time zone will be used.
8345      *
8346      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8347      * @param enabled Whether time zone should be obtained automatically from the network or not.
8348      * @throws SecurityException if caller is not a device owner, a profile owner for the
8349      * primary user, or a profile owner of an organization-owned managed profile.
8350      */
setAutoTimeZoneEnabled(@onNull ComponentName admin, boolean enabled)8351     public void setAutoTimeZoneEnabled(@NonNull ComponentName admin, boolean enabled) {
8352         throwIfParentInstance("setAutoTimeZone");
8353         if (mService != null) {
8354             try {
8355                 mService.setAutoTimeZoneEnabled(admin, enabled);
8356             } catch (RemoteException e) {
8357                 throw e.rethrowFromSystemServer();
8358             }
8359         }
8360     }
8361 
8362     /**
8363      * @return true if auto time zone is enabled on the device.
8364      * @throws SecurityException if caller is not a device owner, a profile owner for the
8365      * primary user, or a profile owner of an organization-owned managed profile.
8366      */
getAutoTimeZoneEnabled(@onNull ComponentName admin)8367     public boolean getAutoTimeZoneEnabled(@NonNull ComponentName admin) {
8368         throwIfParentInstance("getAutoTimeZone");
8369         if (mService != null) {
8370             try {
8371                 return mService.getAutoTimeZoneEnabled(admin);
8372             } catch (RemoteException e) {
8373                 throw e.rethrowFromSystemServer();
8374             }
8375         }
8376         return false;
8377     }
8378 
8379     /**
8380      * TODO (b/137101239): remove this method in follow-up CL
8381      * since it's only used for split system user.
8382      * Called by a device owner to set whether all users created on the device should be ephemeral.
8383      * @hide
8384      */
setForceEphemeralUsers( @onNull ComponentName admin, boolean forceEphemeralUsers)8385     public void setForceEphemeralUsers(
8386             @NonNull ComponentName admin, boolean forceEphemeralUsers) {
8387         throwIfParentInstance("setForceEphemeralUsers");
8388         if (mService != null) {
8389             try {
8390                 mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
8391             } catch (RemoteException e) {
8392                 throw e.rethrowFromSystemServer();
8393             }
8394         }
8395     }
8396 
8397     /**
8398      * TODO (b/137101239): remove this method in follow-up CL
8399      * since it's only used for split system user.
8400      * @return true if all users are created ephemeral.
8401      * @throws SecurityException if {@code admin} is not a device owner.
8402      * @hide
8403      */
getForceEphemeralUsers(@onNull ComponentName admin)8404     public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
8405         throwIfParentInstance("getForceEphemeralUsers");
8406         if (mService != null) {
8407             try {
8408                 return mService.getForceEphemeralUsers(admin);
8409             } catch (RemoteException e) {
8410                 throw e.rethrowFromSystemServer();
8411             }
8412         }
8413         return false;
8414     }
8415 
8416     /**
8417      * Called by an application that is administering the device to disable keyguard customizations,
8418      * such as widgets. After setting this, keyguard features will be disabled according to the
8419      * provided feature list.
8420      * <p>
8421      * The calling device admin must have requested
8422      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
8423      * if it has not, a security exception will be thrown.
8424      * <p>
8425      * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
8426      * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
8427      * profile owner of a managed profile can set:
8428      * <ul>
8429      * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
8430      * is no separate challenge set on the managed profile.
8431      * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FACE} or
8432      * {@link #KEYGUARD_DISABLE_IRIS} which affects the managed profile challenge if
8433      * there is one, or the parent user otherwise.
8434      * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
8435      * by applications in the managed profile.
8436      * </ul>
8437      * <p>
8438      * From version {@link android.os.Build.VERSION_CODES#R} the profile owner of an
8439      * organization-owned managed profile can set:
8440      * <ul>
8441      * <li>{@link #KEYGUARD_DISABLE_SECURE_CAMERA} which affects the parent user when called on the
8442      * parent profile.
8443      * <li>{@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS} which affects the parent user when called
8444      * on the parent profile.
8445      * </ul>
8446      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, {@link #KEYGUARD_DISABLE_FINGERPRINT},
8447      * {@link #KEYGUARD_DISABLE_FACE}, {@link #KEYGUARD_DISABLE_IRIS},
8448      * {@link #KEYGUARD_DISABLE_SECURE_CAMERA} and {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS}
8449      * can also be set on the {@link DevicePolicyManager} instance returned by
8450      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
8451      * profile. {@link #KEYGUARD_DISABLE_SECURE_CAMERA} can only be set on the parent profile
8452      * instance if the calling device admin is the profile owner of an organization-owned
8453      * managed profile.
8454      * <p>
8455      * Requests to disable other features on a managed profile will be ignored.
8456      * <p>
8457      * The admin can check which features have been disabled by calling
8458      * {@link #getKeyguardDisabledFeatures(ComponentName)}
8459      *
8460      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8461      * @param which The disabled features flag which can be either
8462      *            {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
8463      *            {@link #KEYGUARD_DISABLE_FEATURES_ALL}, or a combination of
8464      *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
8465      *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
8466      *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
8467      *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
8468      *            {@link #KEYGUARD_DISABLE_FINGERPRINT},
8469      *            {@link #KEYGUARD_DISABLE_FACE},
8470      *            {@link #KEYGUARD_DISABLE_IRIS}.
8471      * @throws SecurityException if {@code admin} is not an active administrator or does not user
8472      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
8473      */
setKeyguardDisabledFeatures(@onNull ComponentName admin, int which)8474     public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
8475         if (mService != null) {
8476             try {
8477                 mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
8478             } catch (RemoteException e) {
8479                 throw e.rethrowFromSystemServer();
8480             }
8481         }
8482     }
8483 
8484     /**
8485      * Determine whether or not features have been disabled in keyguard either by the calling
8486      * admin, if specified, or all admins that set restrictions on this user and its participating
8487      * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
8488      *
8489      * <p>This method can be called on the {@link DevicePolicyManager} instance
8490      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
8491      * restrictions on the parent profile.
8492      *
8493      * @param admin The name of the admin component to check, or {@code null} to check whether any
8494      * admins have disabled features in keyguard.
8495      * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
8496      * for a list.
8497      */
getKeyguardDisabledFeatures(@ullable ComponentName admin)8498     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
8499         return getKeyguardDisabledFeatures(admin, myUserId());
8500     }
8501 
8502     private IpcDataCache<Pair<ComponentName, Integer>, Integer> mGetKeyGuardDisabledFeaturesCache =
8503             new IpcDataCache<>(sDpmCaches.child("getKeyguardDisabledFeatures"),
8504                     (query) -> getService().getKeyguardDisabledFeatures(
8505                             query.first, query.second, isParentInstance()));
8506 
8507     /** @hide per-user version */
8508     @UnsupportedAppUsage
getKeyguardDisabledFeatures(@ullable ComponentName admin, int userHandle)8509     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
8510         if (mService != null) {
8511             return mGetKeyGuardDisabledFeaturesCache.query(new Pair<>(admin, userHandle));
8512         } else {
8513             return KEYGUARD_DISABLE_FEATURES_NONE;
8514         }
8515     }
8516 
8517     /**
8518      * @hide
8519      */
8520     @TestApi
8521     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
8522     @RequiresPermission(allOf = {
8523             android.Manifest.permission.MANAGE_DEVICE_ADMINS,
8524             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL
8525     })
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing, int userHandle)8526     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
8527             int userHandle) {
8528         if (mService != null) {
8529             try {
8530                 mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
8531             } catch (RemoteException e) {
8532                 throw e.rethrowFromSystemServer();
8533             }
8534         }
8535     }
8536 
8537     /**
8538      * @hide
8539      */
8540     @UnsupportedAppUsage
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing)8541     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
8542         setActiveAdmin(policyReceiver, refreshing, myUserId());
8543     }
8544 
8545     /**
8546      * Called by a privileged caller holding {@code BIND_DEVICE_ADMIN} permission to retrieve
8547      * the remove warning for the given device admin.
8548      * @hide
8549      */
getRemoveWarning(@ullable ComponentName admin, RemoteCallback result)8550     public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
8551         if (mService != null) {
8552             try {
8553                 mService.getRemoveWarning(admin, result, myUserId());
8554             } catch (RemoteException e) {
8555                 throw e.rethrowFromSystemServer();
8556             }
8557         }
8558     }
8559 
8560     /**
8561      * @hide
8562      */
8563     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportPasswordChanged(PasswordMetrics metrics, @UserIdInt int userId)8564     public void reportPasswordChanged(PasswordMetrics metrics, @UserIdInt int userId) {
8565         if (mService != null) {
8566             try {
8567                 mService.reportPasswordChanged(metrics, userId);
8568             } catch (RemoteException e) {
8569                 throw e.rethrowFromSystemServer();
8570             }
8571         }
8572     }
8573 
8574     /**
8575      * @hide
8576      */
8577     @UnsupportedAppUsage
8578     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedPasswordAttempt(int userHandle)8579     public void reportFailedPasswordAttempt(int userHandle) {
8580         if (mService != null) {
8581             try {
8582                 mService.reportFailedPasswordAttempt(userHandle);
8583             } catch (RemoteException e) {
8584                 throw e.rethrowFromSystemServer();
8585             }
8586         }
8587     }
8588 
8589     /**
8590      * @hide
8591      */
8592     @UnsupportedAppUsage
8593     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulPasswordAttempt(int userHandle)8594     public void reportSuccessfulPasswordAttempt(int userHandle) {
8595         if (mService != null) {
8596             try {
8597                 mService.reportSuccessfulPasswordAttempt(userHandle);
8598             } catch (RemoteException e) {
8599                 throw e.rethrowFromSystemServer();
8600             }
8601         }
8602     }
8603 
8604     /**
8605      * @hide
8606      */
8607     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedBiometricAttempt(int userHandle)8608     public void reportFailedBiometricAttempt(int userHandle) {
8609         if (mService != null) {
8610             try {
8611                 mService.reportFailedBiometricAttempt(userHandle);
8612             } catch (RemoteException e) {
8613                 throw e.rethrowFromSystemServer();
8614             }
8615         }
8616     }
8617 
8618     /**
8619      * @hide
8620      */
8621     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulBiometricAttempt(int userHandle)8622     public void reportSuccessfulBiometricAttempt(int userHandle) {
8623         if (mService != null) {
8624             try {
8625                 mService.reportSuccessfulBiometricAttempt(userHandle);
8626             } catch (RemoteException e) {
8627                 throw e.rethrowFromSystemServer();
8628             }
8629         }
8630     }
8631 
8632     /**
8633      * Should be called when keyguard has been dismissed.
8634      * @hide
8635      */
reportKeyguardDismissed(int userHandle)8636     public void reportKeyguardDismissed(int userHandle) {
8637         if (mService != null) {
8638             try {
8639                 mService.reportKeyguardDismissed(userHandle);
8640             } catch (RemoteException e) {
8641                 throw e.rethrowFromSystemServer();
8642             }
8643         }
8644     }
8645 
8646     /**
8647      * Should be called when keyguard view has been shown to the user.
8648      * @hide
8649      */
reportKeyguardSecured(int userHandle)8650     public void reportKeyguardSecured(int userHandle) {
8651         if (mService != null) {
8652             try {
8653                 mService.reportKeyguardSecured(userHandle);
8654             } catch (RemoteException e) {
8655                 throw e.rethrowFromSystemServer();
8656             }
8657         }
8658     }
8659 
8660     /**
8661      * Sets the given package as the device owner.
8662      *
8663      * <p>Preconditions:
8664      * <ul>
8665      *   <li>The package must already be installed.
8666      *   <li>There must not already be a device owner.
8667      *   <li>Only apps with the {@code MANAGE_PROFILE_AND_DEVICE_OWNERS} permission or the
8668      *       {@link Process#SHELL_UID Shell UID} can call this method.
8669      * </ul>
8670      *
8671      * <p>Calling this after the setup phase of the device owner user has completed is allowed only
8672      * if the caller is the {@link Process#SHELL_UID Shell UID}, and there are no additional users
8673      * (except when the device runs on headless system user mode, in which case it could have exact
8674      * one extra user, which is the current user - the device owner will be set in the
8675      * {@link UserHandle#SYSTEM system} user and a profile owner will be set in the current user)
8676      * and no accounts.
8677      *
8678      * @param who the component name to be registered as device owner.
8679      * @param ownerName the human readable name of the institution that owns this device.
8680      * @param userId ID of the user on which the device owner runs.
8681      *
8682      * @return whether the package was successfully registered as the device owner.
8683      *
8684      * @throws IllegalArgumentException if the package name is {@code null} or invalid.
8685      * @throws IllegalStateException If the preconditions mentioned are not met.
8686      *
8687      * @hide
8688      */
8689     @TestApi
8690     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setDeviceOwner(@onNull ComponentName who, @Nullable String ownerName, @UserIdInt int userId)8691     public boolean setDeviceOwner(@NonNull ComponentName who, @Nullable String ownerName,
8692             @UserIdInt int userId) {
8693         if (mService != null) {
8694             try {
8695                 return mService.setDeviceOwner(who, ownerName, userId,
8696                         /* setProfileOwnerOnCurrentUserIfNecessary= */ true);
8697             } catch (RemoteException re) {
8698                 throw re.rethrowFromSystemServer();
8699             }
8700         }
8701         return false;
8702     }
8703 
8704     /**
8705      * Same as {@link #setDeviceOwner(ComponentName, String, int)}, but without setting the profile
8706      * owner on current user when running on headless system user mode - should be used only by
8707      * testing infra.
8708      *
8709      * @hide
8710      */
8711     @TestApi
8712     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setDeviceOwnerOnly( @onNull ComponentName who, @Nullable String ownerName, @UserIdInt int userId)8713     public boolean setDeviceOwnerOnly(
8714             @NonNull ComponentName who, @Nullable String ownerName, @UserIdInt int userId) {
8715         if (mService != null) {
8716             try {
8717                 return mService.setDeviceOwner(who, ownerName, userId,
8718                         /* setProfileOwnerOnCurrentUserIfNecessary= */ false);
8719             } catch (RemoteException re) {
8720                 throw re.rethrowFromSystemServer();
8721             }
8722         }
8723         return false;
8724     }
8725 
8726     /**
8727      * Used to determine if a particular package has been registered as a Device Owner app.
8728      * A device owner app is a special device admin that cannot be deactivated by the user, once
8729      * activated as a device admin. It also cannot be uninstalled. To check whether a particular
8730      * package is currently registered as the device owner app, pass in the package name from
8731      * {@link Context#getPackageName()} to this method.<p/>This is useful for device
8732      * admin apps that want to check whether they are also registered as the device owner app. The
8733      * exact mechanism by which a device admin app is registered as a device owner app is defined by
8734      * the setup process.
8735      * @param packageName the package name of the app, to compare with the registered device owner
8736      * app, if any.
8737      * @return whether or not the package is registered as the device owner app.
8738      */
isDeviceOwnerApp(String packageName)8739     public boolean isDeviceOwnerApp(String packageName) {
8740         throwIfParentInstance("isDeviceOwnerApp");
8741         return isDeviceOwnerAppOnCallingUser(packageName);
8742     }
8743 
8744     /**
8745      * @return true if a package is registered as device owner, only when it's running on the
8746      * calling user.
8747      *
8748      * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
8749      * @hide
8750      */
isDeviceOwnerAppOnCallingUser(String packageName)8751     public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
8752         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
8753     }
8754 
8755     /**
8756      * @return true if a package is registered as device owner, even if it's running on a different
8757      * user.
8758      *
8759      * <p>Requires the MANAGE_USERS permission.
8760      *
8761      * @hide
8762      */
isDeviceOwnerAppOnAnyUser(String packageName)8763     public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
8764         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
8765     }
8766 
8767     /**
8768      * @return device owner component name, only when it's running on the calling user.
8769      *
8770      * @hide
8771      */
getDeviceOwnerComponentOnCallingUser()8772     public ComponentName getDeviceOwnerComponentOnCallingUser() {
8773         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
8774     }
8775 
8776     /**
8777      * @return device owner component name, even if it's running on a different user.
8778      *
8779      * @hide
8780      */
8781     @SystemApi
8782     @RequiresPermission(anyOf = {
8783             android.Manifest.permission.MANAGE_USERS,
8784             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
8785     })
getDeviceOwnerComponentOnAnyUser()8786     public ComponentName getDeviceOwnerComponentOnAnyUser() {
8787         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
8788     }
8789 
isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly)8790     private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
8791         if (packageName == null) {
8792             return false;
8793         }
8794         final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
8795         if (deviceOwner == null) {
8796             return false;
8797         }
8798         return packageName.equals(deviceOwner.getPackageName());
8799     }
8800 
getDeviceOwnerComponentInner(boolean callingUserOnly)8801     private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
8802         if (mService != null) {
8803             try {
8804                 return mService.getDeviceOwnerComponent(callingUserOnly);
8805             } catch (RemoteException re) {
8806                 throw re.rethrowFromSystemServer();
8807             }
8808         }
8809         return null;
8810     }
8811 
8812     /**
8813      * @return Handle of the user who runs device owner, or {@code null} if there's no device owner.
8814      *
8815      * @hide
8816      */
8817     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
8818     @SystemApi
getDeviceOwnerUser()8819     public @Nullable UserHandle getDeviceOwnerUser() {
8820         if (mService != null) {
8821             try {
8822                 int userId = mService.getDeviceOwnerUserId();
8823 
8824                 if (userId != UserHandle.USER_NULL) {
8825                     return UserHandle.of(userId);
8826                 }
8827             } catch (RemoteException re) {
8828                 throw re.rethrowFromSystemServer();
8829             }
8830         }
8831         return null;
8832     }
8833 
8834     /**
8835      * @hide
8836      */
getDeviceOwnerUserId()8837     public int getDeviceOwnerUserId() {
8838         if (mService != null) {
8839             try {
8840                 return mService.getDeviceOwnerUserId();
8841             } catch (RemoteException re) {
8842                 throw re.rethrowFromSystemServer();
8843             }
8844         }
8845         return UserHandle.USER_NULL;
8846     }
8847 
8848     /**
8849      * Clears the current device owner. The caller must be the device owner. This function should be
8850      * used cautiously as once it is called it cannot be undone. The device owner can only be set as
8851      * a part of device setup, before it completes.
8852      * <p>
8853      * While some policies previously set by the device owner will be cleared by this method, it is
8854      * a best-effort process and some other policies will still remain in place after the device
8855      * owner is cleared.
8856      *
8857      * @param packageName The package name of the device owner.
8858      * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
8859      *             does not own the current device owner component.
8860      *
8861      * @deprecated This method is expected to be used for testing purposes only. The device owner
8862      * will lose control of the device and its data after calling it. In order to protect any
8863      * sensitive data that remains on the device, it is advised that the device owner factory resets
8864      * the device instead of calling this method. See {@link #wipeData(int)}.
8865      */
8866     @Deprecated
clearDeviceOwnerApp(String packageName)8867     public void clearDeviceOwnerApp(String packageName) {
8868         throwIfParentInstance("clearDeviceOwnerApp");
8869         if (mService != null) {
8870             try {
8871                 mService.clearDeviceOwner(packageName);
8872             } catch (RemoteException re) {
8873                 throw re.rethrowFromSystemServer();
8874             }
8875         }
8876     }
8877 
8878     /**
8879      * Returns the device owner package name, only if it's running on the calling user.
8880      *
8881      * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
8882      *
8883      * @hide
8884      */
8885     @SystemApi
8886     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwner()8887     public @Nullable String getDeviceOwner() {
8888         throwIfParentInstance("getDeviceOwner");
8889         final ComponentName name = getDeviceOwnerComponentOnCallingUser();
8890         return name != null ? name.getPackageName() : null;
8891     }
8892 
8893     private IpcDataCache<Void, Boolean> mHasDeviceOwnerCache =
8894             new IpcDataCache<>(sDpmCaches.child("hasDeviceOwner"),
8895                     (query) -> getService().hasDeviceOwner());
8896 
8897     /**
8898      * Called by the system to find out whether the device is managed by a Device Owner.
8899      *
8900      * @return whether the device is managed by a Device Owner.
8901      * @throws SecurityException if the caller is not the device owner, does not hold
8902      *         MANAGE_USERS or MANAGE_PROFILE_AND_DEVICE_OWNERS permissions and is not the system.
8903      *
8904      * @hide
8905      */
8906     @SystemApi
8907     @SuppressLint("RequiresPermission")
isDeviceManaged()8908     public boolean isDeviceManaged() {
8909         return mHasDeviceOwnerCache.query(null);
8910     }
8911 
8912     /**
8913      * Returns the device owner name.  Note this method *will* return the device owner
8914      * name when it's running on a different user.
8915      *
8916      * @hide
8917      */
8918     @SystemApi
8919     @RequiresPermission(anyOf = {
8920             android.Manifest.permission.MANAGE_USERS,
8921             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
8922     })
getDeviceOwnerNameOnAnyUser()8923     public String getDeviceOwnerNameOnAnyUser() {
8924         throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
8925         if (mService != null) {
8926             try {
8927                 return mService.getDeviceOwnerName();
8928             } catch (RemoteException re) {
8929                 throw re.rethrowFromSystemServer();
8930             }
8931         }
8932         return null;
8933     }
8934 
8935     /**
8936      * @hide
8937      * @deprecated Use #ACTION_SET_PROFILE_OWNER
8938      * Sets the given component as an active admin and registers the package as the profile
8939      * owner for this user. The package must already be installed and there shouldn't be
8940      * an existing profile owner registered for this user. Also, this method must be called
8941      * before the user setup has been completed.
8942      * <p>
8943      * This method can only be called by system apps that hold MANAGE_USERS permission and
8944      * MANAGE_DEVICE_ADMINS permission.
8945      * @param admin The component to register as an active admin and profile owner.
8946      * @param ownerName The user-visible name of the entity that is managing this user.
8947      * @return whether the admin was successfully registered as the profile owner.
8948      * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
8949      *         the user has already been set up.
8950      */
8951     @Deprecated
8952     @SystemApi
8953     @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
setActiveProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName)8954     public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
8955             throws IllegalArgumentException {
8956         throwIfParentInstance("setActiveProfileOwner");
8957         if (mService != null) {
8958             try {
8959                 final int myUserId = myUserId();
8960                 mService.setActiveAdmin(admin, false, myUserId);
8961                 return mService.setProfileOwner(admin, ownerName, myUserId);
8962             } catch (RemoteException re) {
8963                 throw re.rethrowFromSystemServer();
8964             }
8965         }
8966         return false;
8967     }
8968 
8969     /**
8970      * Clears the active profile owner. The caller must be the profile owner of this user, otherwise
8971      * a SecurityException will be thrown. This method is not available to managed profile owners.
8972      * <p>
8973      * While some policies previously set by the profile owner will be cleared by this method, it is
8974      * a best-effort process and some other policies will still remain in place after the profile
8975      * owner is cleared.
8976      *
8977      * @param admin The component to remove as the profile owner.
8978      * @throws SecurityException if {@code admin} is not an active profile owner, or the method is
8979      * being called from a managed profile.
8980      *
8981      * @deprecated This method is expected to be used for testing purposes only. The profile owner
8982      * will lose control of the user and its data after calling it. In order to protect any
8983      * sensitive data that remains on this user, it is advised that the profile owner deletes it
8984      * instead of calling this method. See {@link #wipeData(int)}.
8985      */
8986     @Deprecated
clearProfileOwner(@onNull ComponentName admin)8987     public void clearProfileOwner(@NonNull ComponentName admin) {
8988         throwIfParentInstance("clearProfileOwner");
8989         if (mService != null) {
8990             try {
8991                 mService.clearProfileOwner(admin);
8992             } catch (RemoteException re) {
8993                 throw re.rethrowFromSystemServer();
8994             }
8995         }
8996     }
8997 
8998     /**
8999      * @hide
9000      * Checks whether the user was already setup.
9001      */
hasUserSetupCompleted()9002     public boolean hasUserSetupCompleted() {
9003         if (mService != null) {
9004             try {
9005                 return mService.hasUserSetupCompleted();
9006             } catch (RemoteException re) {
9007                 throw re.rethrowFromSystemServer();
9008             }
9009         }
9010         return true;
9011     }
9012 
9013     /**
9014      * @hide
9015      * Sets the given component as the profile owner of the given user profile. The package must
9016      * already be installed. There must not already be a profile owner for this user.
9017      * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
9018      * this method.
9019      * Calling this after the setup phase of the specified user has completed is allowed only if:
9020      * - the caller is SYSTEM_UID.
9021      * - or the caller is the shell uid, and there are no accounts on the specified user.
9022      * @param admin the component name to be registered as profile owner.
9023      * @param ownerName the human readable name of the organisation associated with this DPM.
9024      * @param userHandle the userId to set the profile owner for.
9025      * @return whether the component was successfully registered as the profile owner.
9026      * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
9027      * preconditions mentioned are not met.
9028      */
setProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName, int userHandle)9029     public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
9030             int userHandle) throws IllegalArgumentException {
9031         if (mService != null) {
9032             try {
9033                 if (ownerName == null) {
9034                     ownerName = "";
9035                 }
9036                 return mService.setProfileOwner(admin, ownerName, userHandle);
9037             } catch (RemoteException re) {
9038                 throw re.rethrowFromSystemServer();
9039             }
9040         }
9041         return false;
9042     }
9043 
9044     /**
9045      * Sets the device owner information to be shown on the lock screen.
9046      * <p>
9047      * Device owner information set using this method overrides any owner information manually set
9048      * by the user and prevents the user from further changing it.
9049      * <p>
9050      * If the device owner information is {@code null} or empty then the device owner info is
9051      * cleared and the user owner info is shown on the lock screen if it is set.
9052      * <p>
9053      * If the device owner information contains only whitespaces then the message on the lock screen
9054      * will be blank and the user will not be allowed to change it.
9055      * <p>
9056      * If the device owner information needs to be localized, it is the responsibility of the
9057      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9058      * and set a new version of this string accordingly.
9059      * <p>
9060      * May be called by the device owner or the profile owner of an organization-owned device.
9061      *
9062      * @param admin The name of the admin component to check.
9063      * @param info Device owner information which will be displayed instead of the user owner info.
9064      * @throws SecurityException if {@code admin} is not a device owner.
9065      */
setDeviceOwnerLockScreenInfo(@onNull ComponentName admin, CharSequence info)9066     public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
9067         throwIfParentInstance("setDeviceOwnerLockScreenInfo");
9068         if (mService != null) {
9069             try {
9070                 mService.setDeviceOwnerLockScreenInfo(admin, info);
9071             } catch (RemoteException re) {
9072                 throw re.rethrowFromSystemServer();
9073             }
9074         }
9075     }
9076 
9077     /**
9078      * @return The device owner information. If it is not set returns {@code null}.
9079      */
getDeviceOwnerLockScreenInfo()9080     public CharSequence getDeviceOwnerLockScreenInfo() {
9081         throwIfParentInstance("getDeviceOwnerLockScreenInfo");
9082         if (mService != null) {
9083             try {
9084                 return mService.getDeviceOwnerLockScreenInfo();
9085             } catch (RemoteException re) {
9086                 throw re.rethrowFromSystemServer();
9087             }
9088         }
9089         return null;
9090     }
9091 
9092     /**
9093      * Called by device or profile owners to suspend packages for this user. This function can be
9094      * called by a device owner, profile owner, or by a delegate given the
9095      * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}.
9096      * <p>
9097      * A suspended package will not be able to start activities. Its notifications will be hidden,
9098      * it will not show up in recents, will not be able to show toasts or dialogs or ring the
9099      * device.
9100      * <p>
9101      * The package must already be installed. If the package is uninstalled while suspended the
9102      * package will no longer be suspended. The admin can block this by using
9103      * {@link #setUninstallBlocked}.
9104      *
9105      * <p>Some apps cannot be suspended, such as device admins, the active launcher, the required
9106      * package installer, the required package uninstaller, the required package verifier, the
9107      * default dialer, and the permission controller.
9108      *
9109      * @param admin The name of the admin component to check, or {@code null} if the caller is a
9110      *            package access delegate.
9111      * @param packageNames The package names to suspend or unsuspend.
9112      * @param suspended If set to {@code true} than the packages will be suspended, if set to
9113      *            {@code false} the packages will be unsuspended.
9114      * @return an array of package names for which the suspended status is not set as requested in
9115      *         this method.
9116      * @throws SecurityException if {@code admin} is not a device or profile owner.
9117      * @see #setDelegatedScopes
9118      * @see #DELEGATION_PACKAGE_ACCESS
9119      */
setPackagesSuspended(@onNull ComponentName admin, @NonNull String[] packageNames, boolean suspended)9120     public @NonNull String[] setPackagesSuspended(@NonNull ComponentName admin,
9121             @NonNull String[] packageNames, boolean suspended) {
9122         throwIfParentInstance("setPackagesSuspended");
9123         if (mService != null) {
9124             try {
9125                 return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames,
9126                         suspended);
9127             } catch (RemoteException re) {
9128                 throw re.rethrowFromSystemServer();
9129             }
9130         }
9131         return packageNames;
9132     }
9133 
9134     /**
9135      * Determine if a package is suspended. This function can be called by a device owner, profile
9136      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
9137      * {@link #setDelegatedScopes}.
9138      *
9139      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9140      *            {@code null} if the caller is a package access delegate.
9141      * @param packageName The name of the package to retrieve the suspended status of.
9142      * @return {@code true} if the package is suspended or {@code false} if the package is not
9143      *         suspended, could not be found or an error occurred.
9144      * @throws SecurityException if {@code admin} is not a device or profile owner.
9145      * @throws NameNotFoundException if the package could not be found.
9146      * @see #setDelegatedScopes
9147      * @see #DELEGATION_PACKAGE_ACCESS
9148      */
isPackageSuspended(@onNull ComponentName admin, String packageName)9149     public boolean isPackageSuspended(@NonNull ComponentName admin, String packageName)
9150             throws NameNotFoundException {
9151         throwIfParentInstance("isPackageSuspended");
9152         if (mService != null) {
9153             try {
9154                 return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName);
9155             } catch (RemoteException e) {
9156                 throw e.rethrowFromSystemServer();
9157             } catch (IllegalArgumentException ex) {
9158                 throw new NameNotFoundException(packageName);
9159             }
9160         }
9161         return false;
9162     }
9163 
9164     /**
9165      * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
9166      * be used. Only the profile owner can call this.
9167      *
9168      * @see #isProfileOwnerApp
9169      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9170      * @throws SecurityException if {@code admin} is not a profile owner.
9171      */
setProfileEnabled(@onNull ComponentName admin)9172     public void setProfileEnabled(@NonNull ComponentName admin) {
9173         throwIfParentInstance("setProfileEnabled");
9174         if (mService != null) {
9175             try {
9176                 mService.setProfileEnabled(admin);
9177             } catch (RemoteException e) {
9178                 throw e.rethrowFromSystemServer();
9179             }
9180         }
9181     }
9182 
9183     /**
9184      * Sets the name of the profile. In the device owner case it sets the name of the user which it
9185      * is called from. Only a profile owner or device owner can call this. If this is never called
9186      * by the profile or device owner, the name will be set to default values.
9187      *
9188      * @see #isProfileOwnerApp
9189      * @see #isDeviceOwnerApp
9190      * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
9191      * @param profileName The name of the profile. If the name is longer than 200 characters
9192      *                    it will be truncated.
9193      * @throws SecurityException if {@code admin} is not a device or profile owner.
9194      */
setProfileName(@onNull ComponentName admin, String profileName)9195     public void setProfileName(@NonNull ComponentName admin, String profileName) {
9196         throwIfParentInstance("setProfileName");
9197         if (mService != null) {
9198             try {
9199                 mService.setProfileName(admin, profileName);
9200             } catch (RemoteException e) {
9201                 throw e.rethrowFromSystemServer();
9202             }
9203         }
9204     }
9205 
9206     /**
9207      * Used to determine if a particular package is registered as the profile owner for the
9208      * user. A profile owner is a special device admin that has additional privileges
9209      * within the profile.
9210      *
9211      * @param packageName The package name of the app to compare with the registered profile owner.
9212      * @return Whether or not the package is registered as the profile owner.
9213      */
isProfileOwnerApp(String packageName)9214     public boolean isProfileOwnerApp(String packageName) {
9215         throwIfParentInstance("isProfileOwnerApp");
9216         if (mService != null) {
9217             try {
9218                 ComponentName profileOwner = mService.getProfileOwnerAsUser(myUserId());
9219                 return profileOwner != null
9220                         && profileOwner.getPackageName().equals(packageName);
9221             } catch (RemoteException re) {
9222                 throw re.rethrowFromSystemServer();
9223             }
9224         }
9225         return false;
9226     }
9227 
9228     /**
9229      * @hide
9230      * @return the packageName of the owner of the given user profile or {@code null} if no profile
9231      * owner has been set for that user.
9232      * @throws IllegalArgumentException if the userId is invalid.
9233      */
9234     @SystemApi
getProfileOwner()9235     public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
9236         throwIfParentInstance("getProfileOwner");
9237         return getProfileOwnerAsUser(mContext.getUserId());
9238     }
9239 
9240     /**
9241      * @see #getProfileOwner()
9242      * @hide
9243      */
9244     @RequiresPermission(value = android.Manifest.permission.INTERACT_ACROSS_USERS,
9245             conditional = true)
getProfileOwnerAsUser(@onNull UserHandle user)9246     public @Nullable ComponentName getProfileOwnerAsUser(@NonNull UserHandle user) {
9247         if (mService != null) {
9248             try {
9249                 return mService.getProfileOwnerAsUser(user.getIdentifier());
9250             } catch (RemoteException re) {
9251                 throw re.rethrowFromSystemServer();
9252             }
9253         }
9254         return null;
9255     }
9256 
9257     /**
9258      * @hide
9259      */
9260     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getProfileOwnerAsUser(final int userId)9261     public @Nullable ComponentName getProfileOwnerAsUser(final int userId) {
9262         if (mService != null) {
9263             try {
9264                 return mService.getProfileOwnerAsUser(userId);
9265             } catch (RemoteException re) {
9266                 throw re.rethrowFromSystemServer();
9267             }
9268         }
9269         return null;
9270     }
9271 
9272     private final IpcDataCache<UserHandle, ComponentName>
9273             mGetProfileOwnerOrDeviceOwnerSupervisionComponentCache =
9274             new IpcDataCache<>(sDpmCaches.child("getProfileOwnerOrDeviceOwnerSupervisionComponent"),
9275                     (arg) -> getService().getProfileOwnerOrDeviceOwnerSupervisionComponent(arg));
9276 
9277     /**
9278      * Returns the configured supervision app if it exists and is the device owner or policy owner.
9279      * @hide
9280      */
getProfileOwnerOrDeviceOwnerSupervisionComponent( @onNull UserHandle user)9281     public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent(
9282             @NonNull UserHandle user) {
9283         if (mService != null) {
9284             return mGetProfileOwnerOrDeviceOwnerSupervisionComponentCache.query(user);
9285         }
9286         return null;
9287     }
9288 
9289     /**
9290      * Checks if the specified component is the supervision component.
9291      * @hide
9292      */
isSupervisionComponent(@onNull ComponentName who)9293     public boolean isSupervisionComponent(@NonNull ComponentName who) {
9294         if (mService != null) {
9295             try {
9296                 return getService().isSupervisionComponent(who);
9297             } catch (RemoteException re) {
9298                 throw re.rethrowFromSystemServer();
9299             }
9300         }
9301         return false;
9302     }
9303 
9304     /**
9305      * @hide
9306      * @return the human readable name of the organisation associated with this DPM or {@code null}
9307      *         if one is not set.
9308      * @throws IllegalArgumentException if the userId is invalid.
9309      */
getProfileOwnerName()9310     public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
9311         if (mService != null) {
9312             try {
9313                 return mService.getProfileOwnerName(mContext.getUserId());
9314             } catch (RemoteException re) {
9315                 throw re.rethrowFromSystemServer();
9316             }
9317         }
9318         return null;
9319     }
9320 
9321     /**
9322      * @hide
9323      * @param userId The user for whom to fetch the profile owner name, if any.
9324      * @return the human readable name of the organisation associated with this profile owner or
9325      *         null if one is not set.
9326      * @throws IllegalArgumentException if the userId is invalid.
9327      */
9328     @SystemApi
9329     @RequiresPermission(anyOf = {
9330             android.Manifest.permission.MANAGE_USERS,
9331             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
9332     })
getProfileOwnerNameAsUser(int userId)9333     public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
9334         throwIfParentInstance("getProfileOwnerNameAsUser");
9335         if (mService != null) {
9336             try {
9337                 return mService.getProfileOwnerName(userId);
9338             } catch (RemoteException re) {
9339                 throw re.rethrowFromSystemServer();
9340             }
9341         }
9342         return null;
9343     }
9344 
9345     private final IpcDataCache<Void, Boolean> mIsOrganizationOwnedDeviceWithManagedProfileCache =
9346             new IpcDataCache(sDpmCaches.child("isOrganizationOwnedDeviceWithManagedProfile"),
9347                     (query) -> getService().isOrganizationOwnedDeviceWithManagedProfile());
9348 
9349     /**
9350      * Apps can use this method to find out if the device was provisioned as
9351      * organization-owend device with a managed profile.
9352      *
9353      * This, together with checking whether the device has a device owner (by calling
9354      * {@link #isDeviceOwnerApp}), could be used to learn whether the device is owned by an
9355      * organization or an individual:
9356      * If this method returns true OR {@link #isDeviceOwnerApp} returns true (for any package),
9357      * then the device is owned by an organization. Otherwise, it's owned by an individual.
9358      *
9359      * @return {@code true} if the device was provisioned as organization-owned device,
9360      * {@code false} otherwise.
9361      */
isOrganizationOwnedDeviceWithManagedProfile()9362     public boolean isOrganizationOwnedDeviceWithManagedProfile() {
9363         throwIfParentInstance("isOrganizationOwnedDeviceWithManagedProfile");
9364         if (mService != null) {
9365             return mIsOrganizationOwnedDeviceWithManagedProfileCache.query(null);
9366         }
9367         return false;
9368     }
9369 
9370     /**
9371      * Returns whether the specified package can read the device identifiers.
9372      *
9373      * @param packageName The package name of the app to check for device identifier access.
9374      * @param pid The process id of the package to be checked.
9375      * @param uid The uid of the package to be checked.
9376      * @return whether the package can read the device identifiers.
9377      *
9378      * @hide
9379      */
hasDeviceIdentifierAccess(@onNull String packageName, int pid, int uid)9380     public boolean hasDeviceIdentifierAccess(@NonNull String packageName, int pid, int uid) {
9381         throwIfParentInstance("hasDeviceIdentifierAccess");
9382         if (packageName == null) {
9383             return false;
9384         }
9385         if (mService != null) {
9386             try {
9387                 return mService.checkDeviceIdentifierAccess(packageName, pid, uid);
9388             } catch (RemoteException re) {
9389                 throw re.rethrowFromSystemServer();
9390             }
9391         }
9392         return false;
9393     }
9394 
9395     /**
9396      * Called by a profile owner or device owner to set a default activity that the system selects
9397      * to handle intents that match the given {@link IntentFilter}. This activity will remain the
9398      * default intent handler even if the set of potential event handlers for the intent filter
9399      * changes and if the intent preferences are reset.
9400      * <p>
9401      * Note that the caller should still declare the activity in the manifest, the API just sets
9402      * the activity to be the default one to handle the given intent filter.
9403      * <p>
9404      * The default disambiguation mechanism takes over if the activity is not installed (anymore).
9405      * When the activity is (re)installed, it is automatically reset as default intent handler for
9406      * the filter.
9407      * <p>
9408      * The calling device admin must be a profile owner or device owner. If it is not, a security
9409      * exception will be thrown.
9410      *
9411      * <p>NOTE: Performs disk I/O and shouldn't be called on the main thread.
9412      *
9413      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9414      * @param filter The IntentFilter for which a default handler is added.
9415      * @param activity The Activity that is added as default intent handler.
9416      * @throws SecurityException if {@code admin} is not a device or profile owner.
9417      */
addPersistentPreferredActivity(@onNull ComponentName admin, IntentFilter filter, @NonNull ComponentName activity)9418     public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
9419             @NonNull ComponentName activity) {
9420         throwIfParentInstance("addPersistentPreferredActivity");
9421         if (mService != null) {
9422             try {
9423                 mService.addPersistentPreferredActivity(admin, filter, activity);
9424             } catch (RemoteException e) {
9425                 throw e.rethrowFromSystemServer();
9426             }
9427         }
9428     }
9429 
9430     /**
9431      * Called by a profile owner or device owner to remove all persistent intent handler preferences
9432      * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
9433      * <p>
9434      * The calling device admin must be a profile owner. If it is not, a security exception will be
9435      * thrown.
9436      *
9437      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9438      * @param packageName The name of the package for which preferences are removed.
9439      * @throws SecurityException if {@code admin} is not a device or profile owner.
9440      */
clearPackagePersistentPreferredActivities(@onNull ComponentName admin, String packageName)9441     public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
9442             String packageName) {
9443         throwIfParentInstance("clearPackagePersistentPreferredActivities");
9444         if (mService != null) {
9445             try {
9446                 mService.clearPackagePersistentPreferredActivities(admin, packageName);
9447             } catch (RemoteException e) {
9448                 throw e.rethrowFromSystemServer();
9449             }
9450         }
9451     }
9452 
9453     /**
9454      * Must be called by a device owner or a profile owner of an organization-owned managed profile
9455      * to set the default SMS application.
9456      * <p>
9457      * This method can be called on the {@link DevicePolicyManager} instance, returned by
9458      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
9459      * of an organization-owned managed profile and the package must be a pre-installed system
9460      * package. If called on the parent instance, then the default SMS application is set on the
9461      * personal profile.
9462      *
9463      * @param admin       Which {@link DeviceAdminReceiver} this request is associated with.
9464      * @param packageName The name of the package to set as the default SMS application.
9465      * @throws SecurityException        if {@code admin} is not a device or profile owner or if
9466      *                                  called on the parent profile and the {@code admin} is not a
9467      *                                  profile owner of an organization-owned managed profile.
9468      * @throws IllegalArgumentException if called on the parent profile and the package
9469      *                                  provided is not a pre-installed system package.
9470      */
setDefaultSmsApplication(@onNull ComponentName admin, @NonNull String packageName)9471     public void setDefaultSmsApplication(@NonNull ComponentName admin,
9472             @NonNull String packageName) {
9473         if (mService != null) {
9474             try {
9475                 mService.setDefaultSmsApplication(admin, packageName, mParentInstance);
9476             } catch (RemoteException e) {
9477                 throw e.rethrowFromSystemServer();
9478             }
9479         }
9480     }
9481 
9482     /**
9483      * Called by a profile owner or device owner to grant permission to a package to manage
9484      * application restrictions for the calling user via {@link #setApplicationRestrictions} and
9485      * {@link #getApplicationRestrictions}.
9486      * <p>
9487      * This permission is persistent until it is later cleared by calling this method with a
9488      * {@code null} value or uninstalling the managing package.
9489      * <p>
9490      * The supplied application restriction managing package must be installed when calling this
9491      * API, otherwise an {@link NameNotFoundException} will be thrown.
9492      *
9493      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9494      * @param packageName The package name which will be given access to application restrictions
9495      *            APIs. If {@code null} is given the current package will be cleared.
9496      * @throws SecurityException if {@code admin} is not a device or profile owner.
9497      * @throws NameNotFoundException if {@code packageName} is not found
9498      *
9499      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
9500      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
9501      */
9502     @Deprecated
setApplicationRestrictionsManagingPackage(@onNull ComponentName admin, @Nullable String packageName)9503     public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
9504             @Nullable String packageName) throws NameNotFoundException {
9505         throwIfParentInstance("setApplicationRestrictionsManagingPackage");
9506         if (mService != null) {
9507             try {
9508                 if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
9509                     throw new NameNotFoundException(packageName);
9510                 }
9511             } catch (RemoteException e) {
9512                 throw e.rethrowFromSystemServer();
9513             }
9514         }
9515     }
9516 
9517     /**
9518      * Called by a profile owner or device owner to retrieve the application restrictions managing
9519      * package for the current user, or {@code null} if none is set. If there are multiple
9520      * delegates this function will return one of them.
9521      *
9522      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9523      * @return The package name allowed to manage application restrictions on the current user, or
9524      *         {@code null} if none is set.
9525      * @throws SecurityException if {@code admin} is not a device or profile owner.
9526      *
9527      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
9528      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
9529      */
9530     @Deprecated
9531     @Nullable
getApplicationRestrictionsManagingPackage( @onNull ComponentName admin)9532     public String getApplicationRestrictionsManagingPackage(
9533             @NonNull ComponentName admin) {
9534         throwIfParentInstance("getApplicationRestrictionsManagingPackage");
9535         if (mService != null) {
9536             try {
9537                 return mService.getApplicationRestrictionsManagingPackage(admin);
9538             } catch (RemoteException e) {
9539                 throw e.rethrowFromSystemServer();
9540             }
9541         }
9542         return null;
9543     }
9544 
9545     /**
9546      * Called by any application to find out whether it has been granted permission via
9547      * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
9548      * for the calling user.
9549      *
9550      * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
9551      * that method.
9552      *
9553      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes}
9554      * instead.
9555      */
9556     @Deprecated
isCallerApplicationRestrictionsManagingPackage()9557     public boolean isCallerApplicationRestrictionsManagingPackage() {
9558         throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
9559         if (mService != null) {
9560             try {
9561                 return mService.isCallerApplicationRestrictionsManagingPackage(
9562                         mContext.getPackageName());
9563             } catch (RemoteException e) {
9564                 throw e.rethrowFromSystemServer();
9565             }
9566         }
9567         return false;
9568     }
9569 
9570     /**
9571      * Sets the application restrictions for a given target application running in the calling user.
9572      * <p>
9573      * The caller must be a profile or device owner on that user, or the package allowed to manage
9574      * application restrictions via {@link #setDelegatedScopes} with the
9575      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
9576      * <p>
9577      * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
9578      * <ul>
9579      * <li>{@code boolean}
9580      * <li>{@code int}
9581      * <li>{@code String} or {@code String[]}
9582      * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
9583      * </ul>
9584      * <p>
9585      * If the restrictions are not available yet, but may be applied in the near future, the caller
9586      * can notify the target application of that by adding
9587      * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
9588      * <p>
9589      * The application restrictions are only made visible to the target application via
9590      * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
9591      * owner, and the application restrictions managing package via
9592      * {@link #getApplicationRestrictions}.
9593      *
9594      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
9595      *
9596      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9597      *            {@code null} if called by the application restrictions managing package.
9598      * @param packageName The name of the package to update restricted settings for.
9599      * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
9600      *            set of active restrictions.
9601      * @throws SecurityException if {@code admin} is not a device or profile owner.
9602      * @see #setDelegatedScopes
9603      * @see #DELEGATION_APP_RESTRICTIONS
9604      * @see UserManager#KEY_RESTRICTIONS_PENDING
9605      */
9606     @WorkerThread
setApplicationRestrictions(@ullable ComponentName admin, String packageName, Bundle settings)9607     public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
9608             Bundle settings) {
9609         throwIfParentInstance("setApplicationRestrictions");
9610         if (mService != null) {
9611             try {
9612                 mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName,
9613                         settings);
9614             } catch (RemoteException e) {
9615                 throw e.rethrowFromSystemServer();
9616             }
9617         }
9618     }
9619 
9620     /**
9621      * Sets a list of configuration features to enable for a trust agent component. This is meant to
9622      * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
9623      * agents but those enabled by this function call. If flag
9624      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
9625      * <p>
9626      * For any specific trust agent, whether it is disabled or not depends on the aggregated state
9627      * of each admin's {@link #KEYGUARD_DISABLE_TRUST_AGENTS} setting and its trust agent
9628      * configuration as set by this function call. In particular: if any admin sets
9629      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and does not additionally set any
9630      * trust agent configuration, the trust agent is disabled completely. Otherwise, the trust agent
9631      * will receive the list of configurations from all admins who set
9632      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and aggregate the configurations to determine its
9633      * behavior. The exact meaning of aggregation is trust-agent-specific.
9634      * <p>
9635      * The calling device admin must have requested
9636      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
9637      * if not, a security exception will be thrown.
9638      * <p>
9639      * This method can be called on the {@link DevicePolicyManager} instance returned by
9640      * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
9641      * the parent profile.
9642      * <p>
9643      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, calling
9644      * this method has no effect - no trust agent configuration will be set.
9645      *
9646      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9647      * @param target Component name of the agent to be configured.
9648      * @param configuration Trust-agent-specific feature configuration bundle. Please consult
9649      *        documentation of the specific trust agent to determine the interpretation of this
9650      *        bundle.
9651      * @throws SecurityException if {@code admin} is not an active administrator or does not use
9652      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
9653      */
9654     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setTrustAgentConfiguration(@onNull ComponentName admin, @NonNull ComponentName target, PersistableBundle configuration)9655     public void setTrustAgentConfiguration(@NonNull ComponentName admin,
9656             @NonNull ComponentName target, PersistableBundle configuration) {
9657         if (mService != null) {
9658             try {
9659                 mService.setTrustAgentConfiguration(admin, target, configuration, mParentInstance);
9660             } catch (RemoteException e) {
9661                 throw e.rethrowFromSystemServer();
9662             }
9663         }
9664     }
9665 
9666     /**
9667      * Gets configuration for the given trust agent based on aggregating all calls to
9668      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
9669      * all device admins.
9670      * <p>
9671      * This method can be called on the {@link DevicePolicyManager} instance returned by
9672      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
9673      * on the parent profile.
9674      * <p>
9675      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, null is
9676      * always returned.
9677      *
9678      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
9679      * this function returns a list of configurations for all admins that declare
9680      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
9681      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
9682      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
9683      * for this {@param agent} or calls it with a null configuration, null is returned.
9684      * @param agent Which component to get enabled features for.
9685      * @return configuration for the given trust agent.
9686      */
9687     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent)9688     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
9689             @Nullable ComponentName admin, @NonNull ComponentName agent) {
9690         return getTrustAgentConfiguration(admin, agent, myUserId());
9691     }
9692 
9693     /** @hide per-user version */
9694     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
9695     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent, int userHandle)9696     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
9697             @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
9698         if (mService != null) {
9699             try {
9700                 return mService.getTrustAgentConfiguration(admin, agent, userHandle,
9701                         mParentInstance);
9702             } catch (RemoteException e) {
9703                 throw e.rethrowFromSystemServer();
9704             }
9705         }
9706         return new ArrayList<PersistableBundle>(); // empty list
9707     }
9708 
9709     /**
9710      * Called by a profile owner of a managed profile to set whether caller-Id information from the
9711      * managed profile will be shown in the parent profile, for incoming calls.
9712      * <p>
9713      * The calling device admin must be a profile owner. If it is not, a security exception will be
9714      * thrown.
9715      *
9716      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9717      * @param disabled If true caller-Id information in the managed profile is not displayed.
9718      * @throws SecurityException if {@code admin} is not a profile owner.
9719      */
setCrossProfileCallerIdDisabled(@onNull ComponentName admin, boolean disabled)9720     public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
9721         throwIfParentInstance("setCrossProfileCallerIdDisabled");
9722         if (mService != null) {
9723             try {
9724                 mService.setCrossProfileCallerIdDisabled(admin, disabled);
9725             } catch (RemoteException e) {
9726                 throw e.rethrowFromSystemServer();
9727             }
9728         }
9729     }
9730 
9731     /**
9732      * Called by a profile owner of a managed profile to determine whether or not caller-Id
9733      * information has been disabled.
9734      * <p>
9735      * The calling device admin must be a profile owner. If it is not, a security exception will be
9736      * thrown.
9737      *
9738      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9739      * @throws SecurityException if {@code admin} is not a profile owner.
9740      */
getCrossProfileCallerIdDisabled(@onNull ComponentName admin)9741     public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
9742         throwIfParentInstance("getCrossProfileCallerIdDisabled");
9743         if (mService != null) {
9744             try {
9745                 return mService.getCrossProfileCallerIdDisabled(admin);
9746             } catch (RemoteException e) {
9747                 throw e.rethrowFromSystemServer();
9748             }
9749         }
9750         return false;
9751     }
9752 
9753     /**
9754      * Determine whether or not caller-Id information has been disabled.
9755      *
9756      * @param userHandle The user for whom to check the caller-id permission
9757      * @hide
9758      */
getCrossProfileCallerIdDisabled(UserHandle userHandle)9759     public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
9760         if (mService != null) {
9761             try {
9762                 return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
9763             } catch (RemoteException e) {
9764                 throw e.rethrowFromSystemServer();
9765             }
9766         }
9767         return false;
9768     }
9769 
9770     /**
9771      * Called by a profile owner of a managed profile to set whether contacts search from the
9772      * managed profile will be shown in the parent profile, for incoming calls.
9773      * <p>
9774      * The calling device admin must be a profile owner. If it is not, a security exception will be
9775      * thrown.
9776      *
9777      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9778      * @param disabled If true contacts search in the managed profile is not displayed.
9779      * @throws SecurityException if {@code admin} is not a profile owner.
9780      */
setCrossProfileContactsSearchDisabled(@onNull ComponentName admin, boolean disabled)9781     public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
9782             boolean disabled) {
9783         throwIfParentInstance("setCrossProfileContactsSearchDisabled");
9784         if (mService != null) {
9785             try {
9786                 mService.setCrossProfileContactsSearchDisabled(admin, disabled);
9787             } catch (RemoteException e) {
9788                 throw e.rethrowFromSystemServer();
9789             }
9790         }
9791     }
9792 
9793     /**
9794      * Called by a profile owner of a managed profile to determine whether or not contacts search
9795      * has been disabled.
9796      * <p>
9797      * The calling device admin must be a profile owner. If it is not, a security exception will be
9798      * thrown.
9799      *
9800      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9801      * @throws SecurityException if {@code admin} is not a profile owner.
9802      */
getCrossProfileContactsSearchDisabled(@onNull ComponentName admin)9803     public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
9804         throwIfParentInstance("getCrossProfileContactsSearchDisabled");
9805         if (mService != null) {
9806             try {
9807                 return mService.getCrossProfileContactsSearchDisabled(admin);
9808             } catch (RemoteException e) {
9809                 throw e.rethrowFromSystemServer();
9810             }
9811         }
9812         return false;
9813     }
9814 
9815 
9816     /**
9817      * Determine whether or not contacts search has been disabled.
9818      *
9819      * @param userHandle The user for whom to check the contacts search permission
9820      * @hide
9821      */
getCrossProfileContactsSearchDisabled(@onNull UserHandle userHandle)9822     public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
9823         if (mService != null) {
9824             try {
9825                 return mService
9826                         .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
9827             } catch (RemoteException e) {
9828                 throw e.rethrowFromSystemServer();
9829             }
9830         }
9831         return false;
9832     }
9833 
9834     /**
9835      * Start Quick Contact on the managed profile for the user, if the policy allows.
9836      *
9837      * @hide
9838      */
startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long directoryId, Intent originalIntent)9839     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
9840             boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
9841         if (mService != null) {
9842             try {
9843                 mService.startManagedQuickContact(actualLookupKey, actualContactId,
9844                         isContactIdIgnored, directoryId, originalIntent);
9845             } catch (RemoteException e) {
9846                 throw e.rethrowFromSystemServer();
9847             }
9848         }
9849     }
9850 
9851     /**
9852      * Start Quick Contact on the managed profile for the user, if the policy allows.
9853      * @hide
9854      */
startManagedQuickContact(String actualLookupKey, long actualContactId, Intent originalIntent)9855     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
9856             Intent originalIntent) {
9857         startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
9858                 originalIntent);
9859     }
9860 
9861     /**
9862      * Called by a profile owner of a managed profile to set whether bluetooth devices can access
9863      * enterprise contacts.
9864      * <p>
9865      * The calling device admin must be a profile owner. If it is not, a security exception will be
9866      * thrown.
9867      * <p>
9868      * This API works on managed profile only.
9869      *
9870      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9871      * @param disabled If true, bluetooth devices cannot access enterprise contacts.
9872      * @throws SecurityException if {@code admin} is not a profile owner.
9873      */
setBluetoothContactSharingDisabled(@onNull ComponentName admin, boolean disabled)9874     public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
9875         throwIfParentInstance("setBluetoothContactSharingDisabled");
9876         if (mService != null) {
9877             try {
9878                 mService.setBluetoothContactSharingDisabled(admin, disabled);
9879             } catch (RemoteException e) {
9880                 throw e.rethrowFromSystemServer();
9881             }
9882         }
9883     }
9884 
9885     /**
9886      * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
9887      * cannot access enterprise contacts.
9888      * <p>
9889      * The calling device admin must be a profile owner. If it is not, a security exception will be
9890      * thrown.
9891      * <p>
9892      * This API works on managed profile only.
9893      *
9894      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9895      * @throws SecurityException if {@code admin} is not a profile owner.
9896      */
getBluetoothContactSharingDisabled(@onNull ComponentName admin)9897     public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
9898         throwIfParentInstance("getBluetoothContactSharingDisabled");
9899         if (mService != null) {
9900             try {
9901                 return mService.getBluetoothContactSharingDisabled(admin);
9902             } catch (RemoteException e) {
9903                 throw e.rethrowFromSystemServer();
9904             }
9905         }
9906         return true;
9907     }
9908 
9909     /**
9910      * Determine whether or not Bluetooth devices cannot access contacts.
9911      * <p>
9912      * This API works on managed profile UserHandle only.
9913      *
9914      * @param userHandle The user for whom to check the caller-id permission
9915      * @hide
9916      */
9917     @SystemApi
9918     @RequiresPermission(permission.INTERACT_ACROSS_USERS)
getBluetoothContactSharingDisabled(@onNull UserHandle userHandle)9919     public boolean getBluetoothContactSharingDisabled(@NonNull UserHandle userHandle) {
9920         if (mService != null) {
9921             try {
9922                 return mService.getBluetoothContactSharingDisabledForUser(userHandle
9923                         .getIdentifier());
9924             } catch (RemoteException e) {
9925                 throw e.rethrowFromSystemServer();
9926             }
9927         }
9928         return true;
9929     }
9930 
9931     /**
9932      * Called by the profile owner of a managed profile so that some intents sent in the managed
9933      * profile can also be resolved in the parent, or vice versa. Only activity intents are
9934      * supported.
9935      *
9936      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9937      * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
9938      *            other profile
9939      * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
9940      *            {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
9941      * @throws SecurityException if {@code admin} is not a device or profile owner.
9942      */
addCrossProfileIntentFilter(@onNull ComponentName admin, IntentFilter filter, int flags)9943     public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
9944         throwIfParentInstance("addCrossProfileIntentFilter");
9945         if (mService != null) {
9946             try {
9947                 mService.addCrossProfileIntentFilter(admin, filter, flags);
9948             } catch (RemoteException e) {
9949                 throw e.rethrowFromSystemServer();
9950             }
9951         }
9952     }
9953 
9954     /**
9955      * Called by a profile owner of a managed profile to remove the cross-profile intent filters
9956      * that go from the managed profile to the parent, or from the parent to the managed profile.
9957      * Only removes those that have been set by the profile owner.
9958      * <p>
9959      * <em>Note</em>: A list of default cross profile intent filters are set up by the system when
9960      * the profile is created, some of them ensure the proper functioning of the profile, while
9961      * others enable sharing of data from the parent to the managed profile for user convenience.
9962      * These default intent filters are not cleared when this API is called. If the default cross
9963      * profile data sharing is not desired, they can be disabled with
9964      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE}.
9965      *
9966      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9967      * @throws SecurityException if {@code admin} is not a profile owner.
9968      */
clearCrossProfileIntentFilters(@onNull ComponentName admin)9969     public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
9970         throwIfParentInstance("clearCrossProfileIntentFilters");
9971         if (mService != null) {
9972             try {
9973                 mService.clearCrossProfileIntentFilters(admin);
9974             } catch (RemoteException e) {
9975                 throw e.rethrowFromSystemServer();
9976             }
9977         }
9978     }
9979 
9980     /**
9981      * Called by a profile or device owner to set the permitted
9982      * {@link android.accessibilityservice.AccessibilityService}. When set by
9983      * a device owner or profile owner the restriction applies to all profiles of the user the
9984      * device owner or profile owner is an admin for. By default, the user can use any accessibility
9985      * service. When zero or more packages have been added, accessibility services that are not in
9986      * the list and not part of the system can not be enabled by the user.
9987      * <p>
9988      * Calling with a {@code null} value for the list disables the restriction so that all services
9989      * can be used, calling with an empty list only allows the built-in system services. Any
9990      * non-system accessibility service that's currently enabled must be included in the list.
9991      * <p>
9992      * System accessibility services are always available to the user and this method can't
9993      * disable them.
9994      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9995      * @param packageNames List of accessibility service package names.
9996      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
9997      *         contain every enabled non-system accessibility service.
9998      * @throws SecurityException if {@code admin} is not a device or profile owner.
9999      */
setPermittedAccessibilityServices(@onNull ComponentName admin, List<String> packageNames)10000     public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
10001             List<String> packageNames) {
10002         throwIfParentInstance("setPermittedAccessibilityServices");
10003         if (mService != null) {
10004             try {
10005                 return mService.setPermittedAccessibilityServices(admin, packageNames);
10006             } catch (RemoteException e) {
10007                 throw e.rethrowFromSystemServer();
10008             }
10009         }
10010         return false;
10011     }
10012 
10013     /**
10014      * Returns the list of permitted accessibility services set by this device or profile owner.
10015      * <p>
10016      * An empty list means no accessibility services except system services are allowed.
10017      * {@code null} means all accessibility services are allowed.
10018      *
10019      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10020      * @return List of accessiblity service package names.
10021      * @throws SecurityException if {@code admin} is not a device or profile owner.
10022      */
getPermittedAccessibilityServices(@onNull ComponentName admin)10023     public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
10024         throwIfParentInstance("getPermittedAccessibilityServices");
10025         if (mService != null) {
10026             try {
10027                 return mService.getPermittedAccessibilityServices(admin);
10028             } catch (RemoteException e) {
10029                 throw e.rethrowFromSystemServer();
10030             }
10031         }
10032         return null;
10033     }
10034 
10035     /**
10036      * Called by the system to check if a specific accessibility service is disabled by admin.
10037      *
10038      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10039      * @param packageName Accessibility service package name that needs to be checked.
10040      * @param userHandle user id the admin is running as.
10041      * @return true if the accessibility service is permitted, otherwise false.
10042      *
10043      * @hide
10044      */
isAccessibilityServicePermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)10045     public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
10046             @NonNull String packageName, int userHandle) {
10047         if (mService != null) {
10048             try {
10049                 return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
10050                         userHandle);
10051             } catch (RemoteException e) {
10052                 throw e.rethrowFromSystemServer();
10053             }
10054         }
10055         return false;
10056     }
10057 
10058     /**
10059      * Returns the list of accessibility services permitted by the device or profiles
10060      * owners of this user.
10061      *
10062      * <p>{@code null} means all accessibility services are allowed, if a non-null list is returned
10063      * it will contain the intersection of the permitted lists for any device or profile
10064      * owners that apply to this user. It will also include any system accessibility services.
10065      *
10066      * @param userId which user to check for.
10067      * @return List of accessiblity service package names.
10068      * @hide
10069      */
10070      @SystemApi
10071      @RequiresPermission(anyOf = {
10072              android.Manifest.permission.MANAGE_USERS,
10073              android.Manifest.permission.QUERY_ADMIN_POLICY})
getPermittedAccessibilityServices(int userId)10074      public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
10075         throwIfParentInstance("getPermittedAccessibilityServices");
10076         if (mService != null) {
10077             try {
10078                 return mService.getPermittedAccessibilityServicesForUser(userId);
10079             } catch (RemoteException e) {
10080                 throw e.rethrowFromSystemServer();
10081             }
10082         }
10083         return null;
10084      }
10085 
10086     /**
10087      * Called by a profile or device owner to set the permitted input methods services for this
10088      * user. By default, the user can use any input method.
10089      * <p>
10090      * This method can be called on the {@link DevicePolicyManager} instance,
10091      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
10092      * a profile owner of an organization-owned device.
10093      * <p>
10094      * If called on the parent instance:
10095      * <ul>
10096      *    <li>The permitted input methods will be applied on the personal profile</li>
10097      *    <li>Can only permit all input methods (calling this method with a {@code null} package
10098      *    list) or only permit system input methods (calling this method with an empty package
10099      *    list). This is to prevent the caller from learning which packages are installed on
10100      *    the personal side</li>
10101      * </ul>
10102      * <p>
10103      * When zero or more packages have been added, input method that are not in the list and not
10104      * part of the system can not be enabled by the user. This method will fail if it is called for
10105      * a admin that is not for the foreground user or a profile of the foreground user. Any
10106      * non-system input method service that's currently enabled must be included in the list.
10107      * <p>
10108      * Calling with a null value for the list disables the restriction so that all input methods can
10109      * be used, calling with an empty list disables all but the system's own input methods.
10110      * <p>
10111      * System input methods are always available to the user - this method can't modify this.
10112      *
10113      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10114      * @param packageNames List of input method package names.
10115      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
10116      *        contain every enabled non-system input method service.
10117      * @throws SecurityException if {@code admin} is not a device, profile owner or if called on
10118      *                           the parent profile and the {@code admin} is not a profile owner
10119      *                           of an organization-owned managed profile.
10120      * @throws IllegalArgumentException if called on the parent profile, the {@code admin} is a
10121      *                           profile owner of an organization-owned managed profile and the
10122      *                           list of permitted input method package names is not null or empty.
10123      */
setPermittedInputMethods( @onNull ComponentName admin, List<String> packageNames)10124     public boolean setPermittedInputMethods(
10125             @NonNull ComponentName admin, List<String> packageNames) {
10126         if (mService != null) {
10127             try {
10128                 return mService.setPermittedInputMethods(admin, packageNames, mParentInstance);
10129             } catch (RemoteException e) {
10130                 throw e.rethrowFromSystemServer();
10131             }
10132         }
10133         return false;
10134     }
10135 
10136 
10137     /**
10138      * Returns the list of permitted input methods set by this device or profile owner.
10139      * <p>
10140      * This method can be called on the {@link DevicePolicyManager} instance,
10141      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
10142      * a profile owner of an organization-owned managed profile. If called on the parent instance,
10143      * then the returned list of permitted input methods are those which are applied on the
10144      * personal profile.
10145      * <p>
10146      * An empty list means no input methods except system input methods are allowed. Null means all
10147      * input methods are allowed.
10148      *
10149      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10150      * @return List of input method package names.
10151      * @throws SecurityException if {@code admin} is not a device, profile owner or if called on
10152      *                           the parent profile and the {@code admin} is not a profile owner
10153      *                           of an organization-owned managed profile.
10154      */
getPermittedInputMethods(@onNull ComponentName admin)10155     public @Nullable List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
10156         if (mService != null) {
10157             try {
10158                 return mService.getPermittedInputMethods(admin, mParentInstance);
10159             } catch (RemoteException e) {
10160                 throw e.rethrowFromSystemServer();
10161             }
10162         }
10163         return null;
10164     }
10165 
10166     /**
10167      * Called by the system to check if a specific input method is disabled by admin.
10168      * <p>
10169      * This method can be called on the {@link DevicePolicyManager} instance,
10170      * returned by {@link #getParentProfileInstance(ComponentName)}. If called on the parent
10171      * instance, this method will check whether the given input method is permitted on
10172      * the personal profile.
10173      *
10174      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10175      * @param packageName Input method package name that needs to be checked.
10176      * @param userHandle user id the admin is running as.
10177      * @return true if the input method is permitted, otherwise false.
10178      *
10179      * @hide
10180      */
isInputMethodPermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)10181     public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
10182             @NonNull String packageName, int userHandle) {
10183         if (mService != null) {
10184             try {
10185                 return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle,
10186                         mParentInstance);
10187             } catch (RemoteException e) {
10188                 throw e.rethrowFromSystemServer();
10189             }
10190         }
10191         return false;
10192     }
10193 
10194     /**
10195      * Returns the list of input methods permitted by the device or profiles owners.
10196      *
10197      * <p>On {@link android.os.Build.VERSION_CODES#Q} and later devices, this method returns the
10198      * result for the calling user.</p>
10199      *
10200      * <p>On Android P and prior devices, this method returns the result for the current user.</p>
10201      *
10202      * <p>Null means all input methods are allowed, if a non-null list is returned
10203      * it will contain the intersection of the permitted lists for any device or profile
10204      * owners that apply to this user. It will also include any system input methods.
10205      *
10206      * @return List of input method package names.
10207      * @hide
10208      *
10209      * @see #setPermittedAccessibilityServices(ComponentName, List)
10210      */
10211     @SystemApi
10212     @RequiresPermission(anyOf = {
10213             android.Manifest.permission.MANAGE_USERS,
10214             android.Manifest.permission.QUERY_ADMIN_POLICY})
getPermittedInputMethodsForCurrentUser()10215     public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
10216         throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
10217         if (mService != null) {
10218             try {
10219                 return mService.getPermittedInputMethodsAsUser(UserHandle.myUserId());
10220             } catch (RemoteException e) {
10221                 throw e.rethrowFromSystemServer();
10222             }
10223         }
10224         return null;
10225     }
10226 
10227     /**
10228      * Returns the list of input methods permitted.
10229      *
10230      * <p>{@code null} means all input methods are allowed, if a non-null list is returned
10231      * it will contain the intersection of the permitted lists for any device or profile
10232      * owners that apply to this user. It will also include any system input methods.
10233      *
10234      * @return List of input method package names.
10235      * @hide
10236      *
10237      * @see #setPermittedAccessibilityServices(ComponentName, List)
10238      */
10239     @UserHandleAware
10240     @RequiresPermission(allOf = {
10241             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10242             android.Manifest.permission.MANAGE_USERS
10243             }, conditional = true)
getPermittedInputMethods()10244     public @Nullable List<String> getPermittedInputMethods() {
10245         throwIfParentInstance("getPermittedInputMethods");
10246         if (mService != null) {
10247             try {
10248                 return mService.getPermittedInputMethodsAsUser(myUserId());
10249             } catch (RemoteException e) {
10250                 throw e.rethrowFromSystemServer();
10251             }
10252         }
10253         return null;
10254     }
10255 
10256     /**
10257      * Called by a profile owner of a managed profile to set the packages that are allowed to use
10258      * a {@link android.service.notification.NotificationListenerService} in the primary user to
10259      * see notifications from the managed profile. By default all packages are permitted by this
10260      * policy. When zero or more packages have been added, notification listeners installed on the
10261      * primary user that are not in the list and are not part of the system won't receive events
10262      * for managed profile notifications.
10263      * <p>
10264      * Calling with a {@code null} value for the list disables the restriction so that all
10265      * notification listener services be used. Calling with an empty list disables all but the
10266      * system's own notification listeners. System notification listener services are always
10267      * available to the user.
10268      * <p>
10269      * If a device or profile owner want to stop notification listeners in their user from seeing
10270      * that user's notifications they should prevent that service from running instead (e.g. via
10271      * {@link #setApplicationHidden(ComponentName, String, boolean)})
10272      *
10273      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10274      * @param packageList List of package names to allowlist
10275      * @return true if setting the restriction succeeded. It will fail if called outside a managed
10276      * profile
10277      * @throws SecurityException if {@code admin} is not a profile owner.
10278      *
10279      * @see android.service.notification.NotificationListenerService
10280      */
setPermittedCrossProfileNotificationListeners( @onNull ComponentName admin, @Nullable List<String> packageList)10281     public boolean setPermittedCrossProfileNotificationListeners(
10282             @NonNull ComponentName admin, @Nullable List<String> packageList) {
10283         throwIfParentInstance("setPermittedCrossProfileNotificationListeners");
10284         if (mService != null) {
10285             try {
10286                 return mService.setPermittedCrossProfileNotificationListeners(admin, packageList);
10287             } catch (RemoteException e) {
10288                 throw e.rethrowFromSystemServer();
10289             }
10290         }
10291         return false;
10292     }
10293 
10294     /**
10295      * Returns the list of packages installed on the primary user that allowed to use a
10296      * {@link android.service.notification.NotificationListenerService} to receive
10297      * notifications from this managed profile, as set by the profile owner.
10298      * <p>
10299      * An empty list means no notification listener services except system ones are allowed.
10300      * A {@code null} return value indicates that all notification listeners are allowed.
10301      */
getPermittedCrossProfileNotificationListeners( @onNull ComponentName admin)10302     public @Nullable List<String> getPermittedCrossProfileNotificationListeners(
10303             @NonNull ComponentName admin) {
10304         throwIfParentInstance("getPermittedCrossProfileNotificationListeners");
10305         if (mService != null) {
10306             try {
10307                 return mService.getPermittedCrossProfileNotificationListeners(admin);
10308             } catch (RemoteException e) {
10309                 throw e.rethrowFromSystemServer();
10310             }
10311         }
10312         return null;
10313     }
10314 
10315     /**
10316      * Returns true if {@code NotificationListenerServices} from the given package are allowed to
10317      * receive events for notifications from the given user id. Can only be called by the system uid
10318      *
10319      * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List)
10320      *
10321      * @hide
10322      */
isNotificationListenerServicePermitted( @onNull String packageName, @UserIdInt int userId)10323     public boolean isNotificationListenerServicePermitted(
10324             @NonNull String packageName, @UserIdInt int userId) {
10325         if (mService != null) {
10326             try {
10327                 return mService.isNotificationListenerServicePermitted(packageName, userId);
10328             } catch (RemoteException e) {
10329                 throw e.rethrowFromSystemServer();
10330             }
10331         }
10332         return true;
10333     }
10334 
10335     /**
10336      * Get the list of apps to keep around as APKs even if no user has currently installed it. This
10337      * function can be called by a device owner or by a delegate given the
10338      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
10339      * <p>
10340      * Please note that packages returned in this method are not automatically pre-cached.
10341      *
10342      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10343      *            {@code null} if the caller is a keep uninstalled packages delegate.
10344      * @return List of package names to keep cached.
10345      * @see #setDelegatedScopes
10346      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
10347      */
getKeepUninstalledPackages(@ullable ComponentName admin)10348     public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) {
10349         throwIfParentInstance("getKeepUninstalledPackages");
10350         if (mService != null) {
10351             try {
10352                 return mService.getKeepUninstalledPackages(admin, mContext.getPackageName());
10353             } catch (RemoteException e) {
10354                 throw e.rethrowFromSystemServer();
10355             }
10356         }
10357         return null;
10358     }
10359 
10360     /**
10361      * Set a list of apps to keep around as APKs even if no user has currently installed it. This
10362      * function can be called by a device owner or by a delegate given the
10363      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
10364      *
10365      * <p>Please note that setting this policy does not imply that specified apps will be
10366      * automatically pre-cached.</p>
10367      *
10368      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10369      *            {@code null} if the caller is a keep uninstalled packages delegate.
10370      * @param packageNames List of package names to keep cached.
10371      * @throws SecurityException if {@code admin} is not a device owner.
10372      * @see #setDelegatedScopes
10373      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
10374      */
setKeepUninstalledPackages(@ullable ComponentName admin, @NonNull List<String> packageNames)10375     public void setKeepUninstalledPackages(@Nullable ComponentName admin,
10376             @NonNull List<String> packageNames) {
10377         throwIfParentInstance("setKeepUninstalledPackages");
10378         if (mService != null) {
10379             try {
10380                 mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames);
10381             } catch (RemoteException e) {
10382                 throw e.rethrowFromSystemServer();
10383             }
10384         }
10385     }
10386 
10387     /**
10388       * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
10389       */
10390     public static final int SKIP_SETUP_WIZARD = 0x0001;
10391 
10392     /**
10393      * Flag used by {@link #createAndManageUser} to specify that the user should be created
10394      * ephemeral. Ephemeral users will be removed after switching to another user or rebooting the
10395      * device.
10396      */
10397     public static final int MAKE_USER_EPHEMERAL = 0x0002;
10398 
10399     /**
10400      * Flag used by {@link #createAndManageUser} to specify that the user should be created as a
10401      * demo user.
10402      * @hide
10403      */
10404     public static final int MAKE_USER_DEMO = 0x0004;
10405 
10406     /**
10407      * Flag used by {@link #createAndManageUser} to specify that the newly created user should skip
10408      * the disabling of system apps during provisioning.
10409      */
10410     public static final int LEAVE_ALL_SYSTEM_APPS_ENABLED = 0x0010;
10411 
10412     /**
10413      * @hide
10414      */
10415     @IntDef(flag = true, prefix = { "SKIP_", "MAKE_USER_", "START_", "LEAVE_" }, value = {
10416             SKIP_SETUP_WIZARD,
10417             MAKE_USER_EPHEMERAL,
10418             MAKE_USER_DEMO,
10419             LEAVE_ALL_SYSTEM_APPS_ENABLED
10420     })
10421     @Retention(RetentionPolicy.SOURCE)
10422     public @interface CreateAndManageUserFlags {}
10423 
10424     /**
10425      * Called by a device owner to create a user with the specified name and a given component of
10426      * the calling package as profile owner. The UserHandle returned by this method should not be
10427      * persisted as user handles are recycled as users are removed and created. If you need to
10428      * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
10429      * user will not be started in the background.
10430      * <p>
10431      * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
10432      * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
10433      * be registered as an active admin on the new user. The profile owner package will be installed
10434      * on the new user.
10435      * <p>
10436      * If the adminExtras are not null, they will be stored on the device until the user is started
10437      * for the first time. Then the extras will be passed to the admin when onEnable is called.
10438      * <p>From {@link android.os.Build.VERSION_CODES#P} onwards, if targeting
10439      * {@link android.os.Build.VERSION_CODES#P}, throws {@link UserOperationException} instead of
10440      * returning {@code null} on failure.
10441      *
10442      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10443      * @param name The user's name.
10444      * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
10445      *            same package as admin, otherwise no user is created and an
10446      *            IllegalArgumentException is thrown.
10447      * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
10448      *            user.
10449      * @param flags {@link #SKIP_SETUP_WIZARD}, {@link #MAKE_USER_EPHEMERAL} and
10450      *        {@link #LEAVE_ALL_SYSTEM_APPS_ENABLED} are supported.
10451      * @see UserHandle
10452      * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
10453      *         user could not be created.
10454      * @throws SecurityException if {@code admin} is not a device owner.
10455      * @throws UserOperationException if the user could not be created and the calling app is
10456      * targeting {@link android.os.Build.VERSION_CODES#P} and running on
10457      * {@link android.os.Build.VERSION_CODES#P}.
10458      */
createAndManageUser(@onNull ComponentName admin, @NonNull String name, @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras, @CreateAndManageUserFlags int flags)10459     public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
10460             @NonNull String name,
10461             @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
10462             @CreateAndManageUserFlags int flags) {
10463         throwIfParentInstance("createAndManageUser");
10464         try {
10465             return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
10466         } catch (ServiceSpecificException e) {
10467             throw new UserOperationException(e.getMessage(), e.errorCode);
10468         } catch (RemoteException re) {
10469             throw re.rethrowFromSystemServer();
10470         }
10471     }
10472 
10473     /**
10474      * Called by a device owner to remove a user/profile and all associated data. The primary user
10475      * can not be removed.
10476      *
10477      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10478      * @param userHandle the user to remove.
10479      * @return {@code true} if the user was removed, {@code false} otherwise.
10480      * @throws SecurityException if {@code admin} is not a device owner.
10481      */
removeUser(@onNull ComponentName admin, @NonNull UserHandle userHandle)10482     public boolean removeUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) {
10483         throwIfParentInstance("removeUser");
10484         try {
10485             return mService.removeUser(admin, userHandle);
10486         } catch (RemoteException re) {
10487             throw re.rethrowFromSystemServer();
10488         }
10489     }
10490 
10491     /**
10492      * Called by a device owner to switch the specified secondary user to the foreground.
10493      *
10494      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10495      * @param userHandle the user to switch to; null will switch to primary.
10496      * @return {@code true} if the switch was successful, {@code false} otherwise.
10497      * @throws SecurityException if {@code admin} is not a device owner.
10498      * @see Intent#ACTION_USER_FOREGROUND
10499      * @see #getSecondaryUsers(ComponentName)
10500      */
switchUser(@onNull ComponentName admin, @Nullable UserHandle userHandle)10501     public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
10502         throwIfParentInstance("switchUser");
10503         try {
10504             return mService.switchUser(admin, userHandle);
10505         } catch (RemoteException re) {
10506             throw re.rethrowFromSystemServer();
10507         }
10508     }
10509 
10510     /**
10511      * Called by a device owner to start the specified secondary user in background.
10512      *
10513      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10514      * @param userHandle the user to be started in background.
10515      * @return one of the following result codes:
10516      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
10517      * {@link UserManager#USER_OPERATION_SUCCESS},
10518      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
10519      * {@link UserManager#USER_OPERATION_ERROR_MAX_RUNNING_USERS},
10520      * @throws SecurityException if {@code admin} is not a device owner.
10521      * @see #getSecondaryUsers(ComponentName)
10522      */
startUserInBackground( @onNull ComponentName admin, @NonNull UserHandle userHandle)10523     public @UserOperationResult int startUserInBackground(
10524             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
10525         throwIfParentInstance("startUserInBackground");
10526         try {
10527             return mService.startUserInBackground(admin, userHandle);
10528         } catch (RemoteException re) {
10529             throw re.rethrowFromSystemServer();
10530         }
10531     }
10532 
10533     /**
10534      * Called by a device owner to stop the specified secondary user.
10535      *
10536      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10537      * @param userHandle the user to be stopped.
10538      * @return one of the following result codes:
10539      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
10540      * {@link UserManager#USER_OPERATION_SUCCESS},
10541      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
10542      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
10543      * @throws SecurityException if {@code admin} is not a device owner.
10544      * @see #getSecondaryUsers(ComponentName)
10545      */
stopUser( @onNull ComponentName admin, @NonNull UserHandle userHandle)10546     public @UserOperationResult int stopUser(
10547             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
10548         throwIfParentInstance("stopUser");
10549         try {
10550             return mService.stopUser(admin, userHandle);
10551         } catch (RemoteException re) {
10552             throw re.rethrowFromSystemServer();
10553         }
10554     }
10555 
10556     /**
10557      * Called by a profile owner of secondary user that is affiliated with the device to stop the
10558      * calling user and switch back to primary user (when the user was
10559      * {@link #switchUser(ComponentName, UserHandle)} switched to) or stop the user (when it was
10560      * {@link #startUserInBackground(ComponentName, UserHandle) started in background}.
10561      *
10562      * <p>Notice that on devices running with
10563      * {@link UserManager#isHeadlessSystemUserMode() headless system user mode}, there is no primary
10564      * user, so it switches back to the user that was in the foreground before the first call to
10565      * {@link #switchUser(ComponentName, UserHandle)} (or fails with
10566      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN} if that method was not called prior to this
10567      * call).
10568      *
10569      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10570      * @return one of the following result codes:
10571      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
10572      * {@link UserManager#USER_OPERATION_SUCCESS},
10573      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
10574      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
10575      * @throws SecurityException if {@code admin} is not a profile owner affiliated with the device.
10576      * @see #getSecondaryUsers(ComponentName)
10577      */
logoutUser(@onNull ComponentName admin)10578     public @UserOperationResult int logoutUser(@NonNull ComponentName admin) {
10579         throwIfParentInstance("logoutUser");
10580         try {
10581             return mService.logoutUser(admin);
10582         } catch (RemoteException re) {
10583             throw re.rethrowFromSystemServer();
10584         }
10585     }
10586 
10587     /**
10588      * Similar to {@link #logoutUser(ComponentName)}, except:
10589      *
10590      * <ul>
10591      *   <li>Called by system (like Settings), not admin.
10592      *   <li>It logs out the current user, not the caller.
10593      * </ul>
10594      *
10595      * @hide
10596      */
10597     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
10598             android.Manifest.permission.INTERACT_ACROSS_USERS})
10599     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
logoutUser()10600     public @UserOperationResult int logoutUser() {
10601         // TODO(b/214336184): add CTS test
10602         try {
10603             return mService.logoutUserInternal();
10604         } catch (RemoteException re) {
10605             throw re.rethrowFromSystemServer();
10606         }
10607     }
10608 
10609     /**
10610      * Gets the user a {@link #logoutUser(ComponentName)} call would switch to,
10611      * or {@code null} if the current user is not in a session (i.e., if it was not
10612      * {@link #switchUser(ComponentName, UserHandle) switched} or
10613      * {@link #startUserInBackground(ComponentName, UserHandle) started in background} by the
10614      * device admin.
10615      *
10616      * @hide
10617      */
10618     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
10619             android.Manifest.permission.INTERACT_ACROSS_USERS})
10620     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
getLogoutUser()10621     public @Nullable UserHandle getLogoutUser() {
10622         // TODO(b/214336184): add CTS test
10623         try {
10624             int userId = mService.getLogoutUserId();
10625             return userId == UserHandle.USER_NULL ? null : UserHandle.of(userId);
10626         } catch (RemoteException re) {
10627             throw re.rethrowFromSystemServer();
10628         }
10629     }
10630 
10631     /**
10632      * Called by a device owner to list all secondary users on the device. Managed profiles are not
10633      * considered as secondary users.
10634      * <p> Used for various user management APIs, including {@link #switchUser}, {@link #removeUser}
10635      * and {@link #stopUser}.
10636      *
10637      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10638      * @return list of other {@link UserHandle}s on the device.
10639      * @throws SecurityException if {@code admin} is not a device owner.
10640      * @see #removeUser(ComponentName, UserHandle)
10641      * @see #switchUser(ComponentName, UserHandle)
10642      * @see #startUserInBackground(ComponentName, UserHandle)
10643      * @see #stopUser(ComponentName, UserHandle)
10644      */
getSecondaryUsers(@onNull ComponentName admin)10645     public List<UserHandle> getSecondaryUsers(@NonNull ComponentName admin) {
10646         throwIfParentInstance("getSecondaryUsers");
10647         try {
10648             return mService.getSecondaryUsers(admin);
10649         } catch (RemoteException re) {
10650             throw re.rethrowFromSystemServer();
10651         }
10652     }
10653 
10654     /**
10655      * Checks if the profile owner is running in an ephemeral user.
10656      *
10657      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10658      * @return whether the profile owner is running in an ephemeral user.
10659      */
isEphemeralUser(@onNull ComponentName admin)10660     public boolean isEphemeralUser(@NonNull ComponentName admin) {
10661         throwIfParentInstance("isEphemeralUser");
10662         try {
10663             return mService.isEphemeralUser(admin);
10664         } catch (RemoteException re) {
10665             throw re.rethrowFromSystemServer();
10666         }
10667     }
10668 
10669     /**
10670      * Retrieves the application restrictions for a given target application running in the calling
10671      * user.
10672      * <p>
10673      * The caller must be a profile or device owner on that user, or the package allowed to manage
10674      * application restrictions via {@link #setDelegatedScopes} with the
10675      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
10676      *
10677      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
10678      *
10679      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10680      *            {@code null} if called by the application restrictions managing package.
10681      * @param packageName The name of the package to fetch restricted settings of.
10682      * @return {@link Bundle} of settings corresponding to what was set last time
10683      *         {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
10684      *         {@link Bundle} if no restrictions have been set.
10685      * @throws SecurityException if {@code admin} is not a device or profile owner.
10686      * @see #setDelegatedScopes
10687      * @see #DELEGATION_APP_RESTRICTIONS
10688      */
10689     @WorkerThread
getApplicationRestrictions( @ullable ComponentName admin, String packageName)10690     public @NonNull Bundle getApplicationRestrictions(
10691             @Nullable ComponentName admin, String packageName) {
10692         throwIfParentInstance("getApplicationRestrictions");
10693         if (mService != null) {
10694             try {
10695                 return mService.getApplicationRestrictions(admin, mContext.getPackageName(),
10696                         packageName);
10697             } catch (RemoteException e) {
10698                 throw e.rethrowFromSystemServer();
10699             }
10700         }
10701         return null;
10702     }
10703 
10704     /**
10705      * Called by a profile or device owner to set a user restriction specified by the key.
10706      * <p>
10707      * The calling device admin must be a profile or device owner; if it is not, a security
10708      * exception will be thrown.
10709      * <p>
10710      * The profile owner of an organization-owned managed profile may invoke this method on
10711      * the {@link DevicePolicyManager} instance it obtained from
10712      * {@link #getParentProfileInstance(ComponentName)}, for enforcing device-wide restrictions.
10713      * <p>
10714      * See the constants in {@link android.os.UserManager} for the list of restrictions that can
10715      * be enforced device-wide.
10716      *
10717      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10718      * @param key   The key of the restriction.
10719      * @throws SecurityException if {@code admin} is not a device or profile owner.
10720      */
addUserRestriction(@onNull ComponentName admin, @UserManager.UserRestrictionKey String key)10721     public void addUserRestriction(@NonNull ComponentName admin,
10722             @UserManager.UserRestrictionKey String key) {
10723         if (mService != null) {
10724             try {
10725                 mService.setUserRestriction(admin, key, true, mParentInstance);
10726             } catch (RemoteException e) {
10727                 throw e.rethrowFromSystemServer();
10728             }
10729         }
10730     }
10731 
10732     /**
10733      * Called by a profile or device owner to clear a user restriction specified by the key.
10734      * <p>
10735      * The calling device admin must be a profile or device owner; if it is not, a security
10736      * exception will be thrown.
10737      * <p>
10738      * The profile owner of an organization-owned managed profile may invoke this method on
10739      * the {@link DevicePolicyManager} instance it obtained from
10740      * {@link #getParentProfileInstance(ComponentName)}, for clearing device-wide restrictions.
10741      * <p>
10742      * See the constants in {@link android.os.UserManager} for the list of restrictions.
10743      *
10744      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10745      * @param key   The key of the restriction.
10746      * @throws SecurityException if {@code admin} is not a device or profile owner.
10747      */
clearUserRestriction(@onNull ComponentName admin, @UserManager.UserRestrictionKey String key)10748     public void clearUserRestriction(@NonNull ComponentName admin,
10749             @UserManager.UserRestrictionKey String key) {
10750         if (mService != null) {
10751             try {
10752                 mService.setUserRestriction(admin, key, false, mParentInstance);
10753             } catch (RemoteException e) {
10754                 throw e.rethrowFromSystemServer();
10755             }
10756         }
10757     }
10758 
10759     /**
10760      * Called by a profile or device owner to get user restrictions set with
10761      * {@link #addUserRestriction(ComponentName, String)}.
10762      * <p>
10763      * The target user may have more restrictions set by the system or other device owner / profile
10764      * owner. To get all the user restrictions currently set, use
10765      * {@link UserManager#getUserRestrictions()}.
10766      * <p>
10767      * The profile owner of an organization-owned managed profile may invoke this method on
10768      * the {@link DevicePolicyManager} instance it obtained from
10769      * {@link #getParentProfileInstance(ComponentName)}, for retrieving device-wide restrictions
10770      * it previously set with {@link #addUserRestriction(ComponentName, String)}.
10771      *
10772      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10773      * @return a {@link Bundle} whose keys are the user restrictions, and the values a
10774      * {@code boolean} indicating whether the restriction is set.
10775      * @throws SecurityException if {@code admin} is not a device or profile owner.
10776      */
getUserRestrictions(@onNull ComponentName admin)10777     public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
10778         Bundle ret = null;
10779         if (mService != null) {
10780             try {
10781                 ret = mService.getUserRestrictions(admin, mParentInstance);
10782             } catch (RemoteException e) {
10783                 throw e.rethrowFromSystemServer();
10784             }
10785         }
10786         return ret == null ? new Bundle() : ret;
10787     }
10788 
10789     /**
10790      * Called by any app to display a support dialog when a feature was disabled by an admin.
10791      * This returns an intent that can be used with {@link Context#startActivity(Intent)} to
10792      * display the dialog. It will tell the user that the feature indicated by {@code restriction}
10793      * was disabled by an admin, and include a link for more information. The default content of
10794      * the dialog can be changed by the restricting admin via
10795      * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not
10796      * set (i.e. the feature is available), then the return value will be {@code null}.
10797      * @param restriction Indicates for which feature the dialog should be displayed. Can be a
10798      *            user restriction from {@link UserManager}, e.g.
10799      *            {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants
10800      *            {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
10801      * @return Intent An intent to be used to start the dialog-activity if the restriction is
10802      *            set by an admin, or null if the restriction does not exist or no admin set it.
10803      */
createAdminSupportIntent(@onNull String restriction)10804     public Intent createAdminSupportIntent(@NonNull String restriction) {
10805         throwIfParentInstance("createAdminSupportIntent");
10806         if (mService != null) {
10807             try {
10808                 return mService.createAdminSupportIntent(restriction);
10809             } catch (RemoteException e) {
10810                 throw e.rethrowFromSystemServer();
10811             }
10812         }
10813         return null;
10814     }
10815 
10816     /**
10817      * @param userId      The user for whom to retrieve information.
10818      * @param restriction The restriction enforced by admin. It could be any user restriction or
10819      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and
10820      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}.
10821      * @return Details of admin and user which enforced the restriction for the userId. If
10822      * restriction is null, profile owner for the user or device owner info is returned.
10823      * @hide
10824      */
getEnforcingAdminAndUserDetails(int userId, @Nullable String restriction)10825     public @Nullable Bundle getEnforcingAdminAndUserDetails(int userId,
10826             @Nullable String restriction) {
10827         if (mService != null) {
10828             try {
10829                 return mService.getEnforcingAdminAndUserDetails(userId, restriction);
10830             } catch (RemoteException e) {
10831                 throw e.rethrowFromSystemServer();
10832             }
10833         }
10834         return null;
10835     }
10836 
10837     /**
10838      * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and
10839      * actual package file remain. This function can be called by a device owner, profile owner, or
10840      * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
10841      * {@link #setDelegatedScopes}.
10842      * <p>
10843      * This method can be called on the {@link DevicePolicyManager} instance, returned by
10844      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
10845      * of an organization-owned managed profile and the package must be a system package. If called
10846      * on the parent instance, then the package is hidden or unhidden in the personal profile.
10847      *
10848      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10849      *            {@code null} if the caller is a package access delegate.
10850      * @param packageName The name of the package to hide or unhide.
10851      * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
10852      *            unhidden.
10853      * @return boolean Whether the hidden setting of the package was successfully updated.
10854      * @throws SecurityException if {@code admin} is not a device or profile owner or if called on
10855      *            the parent profile and the {@code admin} is not a profile owner of an
10856      *            organization-owned managed profile.
10857      * @throws IllegalArgumentException if called on the parent profile and the package provided
10858      *            is not a system package.
10859      * @see #setDelegatedScopes
10860      * @see #DELEGATION_PACKAGE_ACCESS
10861      */
setApplicationHidden(@onNull ComponentName admin, String packageName, boolean hidden)10862     public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
10863             boolean hidden) {
10864         if (mService != null) {
10865             try {
10866                 return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName,
10867                         hidden, mParentInstance);
10868             } catch (RemoteException e) {
10869                 throw e.rethrowFromSystemServer();
10870             }
10871         }
10872         return false;
10873     }
10874 
10875     /**
10876      * Determine if a package is hidden. This function can be called by a device owner, profile
10877      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
10878      * {@link #setDelegatedScopes}.
10879      * <p>
10880      * This method can be called on the {@link DevicePolicyManager} instance, returned by
10881      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
10882      * of an organization-owned managed profile and the package must be a system package. If called
10883      * on the parent instance, this will determine whether the package is hidden or unhidden in the
10884      * personal profile.
10885      *
10886      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10887      *            {@code null} if the caller is a package access delegate.
10888      * @param packageName The name of the package to retrieve the hidden status of.
10889      * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
10890      * @throws SecurityException if {@code admin} is not a device or profile owner or if called on
10891      *            the parent profile and the {@code admin} is not a profile owner of an
10892      *            organization-owned managed profile.
10893      * @throws IllegalArgumentException if called on the parent profile and the package provided
10894      *            is not a system package.
10895      * @see #setDelegatedScopes
10896      * @see #DELEGATION_PACKAGE_ACCESS
10897      */
isApplicationHidden(@onNull ComponentName admin, String packageName)10898     public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
10899         if (mService != null) {
10900             try {
10901                 return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName,
10902                         mParentInstance);
10903             } catch (RemoteException e) {
10904                 throw e.rethrowFromSystemServer();
10905             }
10906         }
10907         return false;
10908     }
10909 
10910     /**
10911      * Re-enable a system app that was disabled by default when the user was initialized. This
10912      * function can be called by a device owner, profile owner, or by a delegate given the
10913      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
10914      *
10915      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10916      *            {@code null} if the caller is an enable system app delegate.
10917      * @param packageName The package to be re-enabled in the calling profile.
10918      * @throws SecurityException if {@code admin} is not a device or profile owner.
10919      * @see #setDelegatedScopes
10920      * @see #DELEGATION_PACKAGE_ACCESS
10921      */
enableSystemApp(@onNull ComponentName admin, String packageName)10922     public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
10923         throwIfParentInstance("enableSystemApp");
10924         if (mService != null) {
10925             try {
10926                 mService.enableSystemApp(admin, mContext.getPackageName(), packageName);
10927             } catch (RemoteException e) {
10928                 throw e.rethrowFromSystemServer();
10929             }
10930         }
10931     }
10932 
10933     /**
10934      * Re-enable system apps by intent that were disabled by default when the user was initialized.
10935      * This function can be called by a device owner, profile owner, or by a delegate given the
10936      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
10937      *
10938      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10939      *            {@code null} if the caller is an enable system app delegate.
10940      * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
10941      *            intent will be re-enabled in the calling profile.
10942      * @return int The number of activities that matched the intent and were installed.
10943      * @throws SecurityException if {@code admin} is not a device or profile owner.
10944      * @see #setDelegatedScopes
10945      * @see #DELEGATION_PACKAGE_ACCESS
10946      */
enableSystemApp(@onNull ComponentName admin, Intent intent)10947     public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
10948         throwIfParentInstance("enableSystemApp");
10949         if (mService != null) {
10950             try {
10951                 return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent);
10952             } catch (RemoteException e) {
10953                 throw e.rethrowFromSystemServer();
10954             }
10955         }
10956         return 0;
10957     }
10958 
10959     /**
10960      * Install an existing package that has been installed in another user, or has been kept after
10961      * removal via {@link #setKeepUninstalledPackages}.
10962      * This function can be called by a device owner, profile owner or a delegate given
10963      * the {@link #DELEGATION_INSTALL_EXISTING_PACKAGE} scope via {@link #setDelegatedScopes}.
10964      * When called in a secondary user or managed profile, the user/profile must be affiliated with
10965      * the device. See {@link #isAffiliatedUser}.
10966      *
10967      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10968      * @param packageName The package to be installed in the calling profile.
10969      * @return {@code true} if the app is installed; {@code false} otherwise.
10970      * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
10971      * an affiliated user or profile.
10972      * @see #setKeepUninstalledPackages
10973      * @see #setDelegatedScopes
10974      * @see #isAffiliatedUser
10975      * @see #DELEGATION_PACKAGE_ACCESS
10976      */
installExistingPackage(@onNull ComponentName admin, String packageName)10977     public boolean installExistingPackage(@NonNull ComponentName admin, String packageName) {
10978         throwIfParentInstance("installExistingPackage");
10979         if (mService != null) {
10980             try {
10981                 return mService.installExistingPackage(admin, mContext.getPackageName(),
10982                         packageName);
10983             } catch (RemoteException e) {
10984                 throw e.rethrowFromSystemServer();
10985             }
10986         }
10987         return false;
10988     }
10989 
10990     /**
10991      * Called by a device owner or profile owner to disable account management for a specific type
10992      * of account.
10993      * <p>
10994      * The calling device admin must be a device owner or profile owner. If it is not, a security
10995      * exception will be thrown.
10996      * <p>
10997      * When account management is disabled for an account type, adding or removing an account of
10998      * that type will not be possible.
10999      * <p>
11000      * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
11001      * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
11002      * management for a specific type is disabled.
11003      * <p>
11004      * This method may be called on the {@code DevicePolicyManager} instance returned from
11005      * {@link #getParentProfileInstance(ComponentName)} by the profile owner on an
11006      * organization-owned device, to restrict accounts that may not be managed on the primary
11007      * profile.
11008      *
11009      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11010      * @param accountType For which account management is disabled or enabled.
11011      * @param disabled The boolean indicating that account management will be disabled (true) or
11012      *            enabled (false).
11013      * @throws SecurityException if {@code admin} is not a device or profile owner.
11014      */
setAccountManagementDisabled(@onNull ComponentName admin, String accountType, boolean disabled)11015     public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
11016             boolean disabled) {
11017         if (mService != null) {
11018             try {
11019                 mService.setAccountManagementDisabled(admin, accountType, disabled,
11020                         mParentInstance);
11021             } catch (RemoteException e) {
11022                 throw e.rethrowFromSystemServer();
11023             }
11024         }
11025     }
11026 
11027     /**
11028      * Gets the array of accounts for which account management is disabled by the profile owner
11029      * or device owner.
11030      *
11031      * <p> Account management can be disabled/enabled by calling
11032      * {@link #setAccountManagementDisabled}.
11033      * <p>
11034      * This method may be called on the {@code DevicePolicyManager} instance returned from
11035      * {@link #getParentProfileInstance(ComponentName)}. Note that only a profile owner on
11036      * an organization-owned device can affect account types on the parent profile instance.
11037      *
11038      * @return a list of account types for which account management has been disabled.
11039      *
11040      * @see #setAccountManagementDisabled
11041      */
getAccountTypesWithManagementDisabled()11042     public @Nullable String[] getAccountTypesWithManagementDisabled() {
11043         return getAccountTypesWithManagementDisabledAsUser(myUserId(), mParentInstance);
11044     }
11045 
11046     /**
11047      * @see #getAccountTypesWithManagementDisabled()
11048      * Note that calling this method on the parent profile instance will return the same
11049      * value as calling it on the main {@code DevicePolicyManager} instance.
11050      * @hide
11051      */
getAccountTypesWithManagementDisabledAsUser(int userId)11052     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
11053         return getAccountTypesWithManagementDisabledAsUser(userId, false);
11054     }
11055 
11056     /**
11057      * @see #getAccountTypesWithManagementDisabled()
11058      * @hide
11059      */
getAccountTypesWithManagementDisabledAsUser( int userId, boolean parentInstance)11060     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(
11061             int userId, boolean parentInstance) {
11062         if (mService != null) {
11063             try {
11064                 return mService.getAccountTypesWithManagementDisabledAsUser(userId, parentInstance);
11065             } catch (RemoteException e) {
11066                 throw e.rethrowFromSystemServer();
11067             }
11068         }
11069 
11070         return null;
11071     }
11072 
11073     /**
11074      * Called by device owner or profile owner to set whether a secondary lockscreen needs to be
11075      * shown.
11076      *
11077      * <p>The secondary lockscreen will by displayed after the primary keyguard security screen
11078      * requirements are met. To provide the lockscreen content the DO/PO will need to provide a
11079      * service handling the {@link #ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE} intent action,
11080      * extending the {@link DevicePolicyKeyguardService} class.
11081      *
11082      * <p>Relevant interactions on the secondary lockscreen should be communicated back to the
11083      * keyguard via {@link IKeyguardCallback}, such as when the screen is ready to be dismissed.
11084      *
11085      * <p>This API, and associated APIs, can only be called by the default supervision app when it
11086      * is set as the device owner or profile owner.
11087      *
11088      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11089      * @param enabled Whether or not the lockscreen needs to be shown.
11090      * @throws SecurityException if {@code admin} is not a device or profile owner.
11091      * @see #isSecondaryLockscreenEnabled
11092      * @hide
11093      **/
11094     @SystemApi
setSecondaryLockscreenEnabled(@onNull ComponentName admin, boolean enabled)11095     public void setSecondaryLockscreenEnabled(@NonNull ComponentName admin, boolean enabled) {
11096         throwIfParentInstance("setSecondaryLockscreenEnabled");
11097         if (mService != null) {
11098             try {
11099                 mService.setSecondaryLockscreenEnabled(admin, enabled);
11100             } catch (RemoteException e) {
11101                 throw e.rethrowFromSystemServer();
11102             }
11103         }
11104     }
11105 
11106     /**
11107      * Returns whether the secondary lock screen needs to be shown.
11108      * @see #setSecondaryLockscreenEnabled
11109      * @hide
11110      */
11111     @SystemApi
isSecondaryLockscreenEnabled(@onNull UserHandle userHandle)11112     public boolean isSecondaryLockscreenEnabled(@NonNull UserHandle userHandle) {
11113         throwIfParentInstance("isSecondaryLockscreenEnabled");
11114         if (mService != null) {
11115             try {
11116                 return mService.isSecondaryLockscreenEnabled(userHandle);
11117             } catch (RemoteException e) {
11118                 throw e.rethrowFromSystemServer();
11119             }
11120         }
11121         return false;
11122     }
11123 
11124     /**
11125      * Sets which packages may enter lock task mode.
11126      * <p>
11127      * Any packages that share uid with an allowed package will also be allowed to activate lock
11128      * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
11129      * package list results in locked tasks belonging to those packages to be finished.
11130      * <p>
11131      * This function can only be called by the device owner, a profile owner of an affiliated user
11132      * or profile, or the profile owner when no device owner is set. See {@link #isAffiliatedUser}.
11133      * Any package set via this method will be cleared if the user becomes unaffiliated.
11134      *
11135      * @param packages The list of packages allowed to enter lock task mode
11136      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11137      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
11138      * affiliated user or profile, or the profile owner when no device owner is set.
11139      * @see #isAffiliatedUser
11140      * @see Activity#startLockTask()
11141      * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
11142      * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
11143      * @see UserManager#DISALLOW_CREATE_WINDOWS
11144      */
setLockTaskPackages(@onNull ComponentName admin, @NonNull String[] packages)11145     public void setLockTaskPackages(@NonNull ComponentName admin, @NonNull String[] packages)
11146             throws SecurityException {
11147         throwIfParentInstance("setLockTaskPackages");
11148         if (mService != null) {
11149             try {
11150                 mService.setLockTaskPackages(admin, packages);
11151             } catch (RemoteException e) {
11152                 throw e.rethrowFromSystemServer();
11153             }
11154         }
11155     }
11156 
11157     /**
11158      * Returns the list of packages allowed to start the lock task mode.
11159      *
11160      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
11161      * affiliated user or profile, or the profile owner when no device owner is set.
11162      * @see #isAffiliatedUser
11163      * @see #setLockTaskPackages
11164      */
getLockTaskPackages(@onNull ComponentName admin)11165     public @NonNull String[] getLockTaskPackages(@NonNull ComponentName admin) {
11166         throwIfParentInstance("getLockTaskPackages");
11167         if (mService != null) {
11168             try {
11169                 return mService.getLockTaskPackages(admin);
11170             } catch (RemoteException e) {
11171                 throw e.rethrowFromSystemServer();
11172             }
11173         }
11174         return new String[0];
11175     }
11176 
11177     /**
11178      * This function lets the caller know whether the given component is allowed to start the
11179      * lock task mode.
11180      * @param pkg The package to check
11181      */
isLockTaskPermitted(String pkg)11182     public boolean isLockTaskPermitted(String pkg) {
11183         throwIfParentInstance("isLockTaskPermitted");
11184         if (mService != null) {
11185             try {
11186                 return mService.isLockTaskPermitted(pkg);
11187             } catch (RemoteException e) {
11188                 throw e.rethrowFromSystemServer();
11189             }
11190         }
11191         return false;
11192     }
11193 
11194     /**
11195      * Sets which system features are enabled when the device runs in lock task mode. This method
11196      * doesn't affect the features when lock task mode is inactive. Any system features not included
11197      * in {@code flags} are implicitly disabled when calling this method. By default, only
11198      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS} is enabled; all the other features are disabled. To
11199      * disable the global actions dialog, call this method omitting
11200      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}.
11201      *
11202      * <p>This method can only be called by the device owner, a profile owner of an affiliated
11203      * user or profile, or the profile owner when no device owner is set. See
11204      * {@link #isAffiliatedUser}.
11205      * Any features set using this method are cleared if the user becomes unaffiliated.
11206      *
11207      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11208      * @param flags The system features enabled during lock task mode.
11209      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
11210      * affiliated user or profile, or the profile owner when no device owner is set.
11211      * @see #isAffiliatedUser
11212      **/
setLockTaskFeatures(@onNull ComponentName admin, @LockTaskFeature int flags)11213     public void setLockTaskFeatures(@NonNull ComponentName admin, @LockTaskFeature int flags) {
11214         throwIfParentInstance("setLockTaskFeatures");
11215         if (mService != null) {
11216             try {
11217                 mService.setLockTaskFeatures(admin, flags);
11218             } catch (RemoteException e) {
11219                 throw e.rethrowFromSystemServer();
11220             }
11221         }
11222     }
11223 
11224     /**
11225      * Gets which system features are enabled for LockTask mode.
11226      *
11227      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11228      * @return bitfield of flags. See {@link #setLockTaskFeatures(ComponentName, int)} for a list.
11229      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
11230      * affiliated user or profile, or the profile owner when no device owner is set.
11231      * @see #isAffiliatedUser
11232      * @see #setLockTaskFeatures
11233      */
getLockTaskFeatures(@onNull ComponentName admin)11234     public @LockTaskFeature int getLockTaskFeatures(@NonNull ComponentName admin) {
11235         throwIfParentInstance("getLockTaskFeatures");
11236         if (mService != null) {
11237             try {
11238                 return mService.getLockTaskFeatures(admin);
11239             } catch (RemoteException e) {
11240                 throw e.rethrowFromSystemServer();
11241             }
11242         }
11243         return 0;
11244     }
11245 
11246     /**
11247      * Sets whether preferential network service is enabled.
11248      * For example, an organization can have a deal/agreement with a carrier that all of
11249      * the work data from its employees’ devices will be sent via a network service dedicated
11250      * for enterprise use.
11251      *
11252      * An example of a supported preferential network service is the Enterprise
11253      * slice on 5G networks. For devices on 4G networks, the profile owner needs to additionally
11254      * configure enterprise APN to set up data call for the preferential network service.
11255      * These APNs can be added using {@link #addOverrideApn}.
11256      *
11257      * By default, preferential network service is disabled on the work profile and
11258      * fully managed devices, on supported carriers and devices.
11259      * Admins can explicitly enable it with this API.
11260      *
11261      * <p> This method enables preferential network service with a default configuration.
11262      * To fine-tune the configuration, use {@link #setPreferentialNetworkServiceConfigs) instead.
11263      * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
11264      * this method can be called by the profile owner of a managed profile.
11265      * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
11266      * This method can be called by the profile owner of a managed profile
11267      * or device owner.
11268      *
11269      * @param enabled whether preferential network service should be enabled.
11270      * @throws SecurityException if the caller is not the profile owner or device owner.
11271      **/
setPreferentialNetworkServiceEnabled(boolean enabled)11272     public void setPreferentialNetworkServiceEnabled(boolean enabled) {
11273         throwIfParentInstance("setPreferentialNetworkServiceEnabled");
11274         PreferentialNetworkServiceConfig.Builder configBuilder =
11275                 new PreferentialNetworkServiceConfig.Builder();
11276         configBuilder.setEnabled(enabled);
11277         if (enabled) {
11278             configBuilder.setNetworkId(NET_ENTERPRISE_ID_1);
11279         }
11280         setPreferentialNetworkServiceConfigs(List.of(configBuilder.build()));
11281     }
11282 
11283     /**
11284      * Indicates whether preferential network service is enabled.
11285      *
11286      * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
11287      * This method can be called by the profile owner of a managed profile.
11288      * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
11289      * This method can be called by the profile owner of a managed profile
11290      * or device owner.
11291      *
11292      * @return whether preferential network service is enabled.
11293      * @throws SecurityException if the caller is not the profile owner or device owner.
11294      */
isPreferentialNetworkServiceEnabled()11295     public boolean isPreferentialNetworkServiceEnabled() {
11296         throwIfParentInstance("isPreferentialNetworkServiceEnabled");
11297         return getPreferentialNetworkServiceConfigs().stream().anyMatch(c -> c.isEnabled());
11298     }
11299 
11300     /**
11301      * Sets preferential network configurations.
11302      * {@see PreferentialNetworkServiceConfig}
11303      *
11304      * An example of a supported preferential network service is the Enterprise
11305      * slice on 5G networks. For devices on 4G networks, the profile owner needs to additionally
11306      * configure enterprise APN to set up data call for the preferential network service.
11307      * These APNs can be added using {@link #addOverrideApn}.
11308      *
11309      * By default, preferential network service is disabled on the work profile and fully managed
11310      * devices, on supported carriers and devices. Admins can explicitly enable it with this API.
11311      * If admin wants to have multiple enterprise slices,
11312      * it can be configured by passing list of {@link PreferentialNetworkServiceConfig} objects.
11313      *
11314      * @param preferentialNetworkServiceConfigs list of preferential network configurations.
11315      * @throws SecurityException if the caller is not the profile owner or device owner.
11316      **/
setPreferentialNetworkServiceConfigs( @onNull List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs)11317     public void setPreferentialNetworkServiceConfigs(
11318             @NonNull List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs) {
11319         throwIfParentInstance("setPreferentialNetworkServiceConfigs");
11320         if (mService == null) {
11321             return;
11322         }
11323         try {
11324             mService.setPreferentialNetworkServiceConfigs(preferentialNetworkServiceConfigs);
11325         } catch (RemoteException e) {
11326             throw e.rethrowFromSystemServer();
11327         }
11328     }
11329 
11330     /**
11331      * Get preferential network configuration
11332      * {@see PreferentialNetworkServiceConfig}
11333      *
11334      * @return preferential network configuration.
11335      * @throws SecurityException if the caller is not the profile owner or device owner.
11336      */
getPreferentialNetworkServiceConfigs()11337     public @NonNull List<PreferentialNetworkServiceConfig> getPreferentialNetworkServiceConfigs() {
11338         throwIfParentInstance("getPreferentialNetworkServiceConfigs");
11339         if (mService == null) {
11340             return List.of(PreferentialNetworkServiceConfig.DEFAULT);
11341         }
11342         try {
11343             return mService.getPreferentialNetworkServiceConfigs();
11344         } catch (RemoteException e) {
11345             throw e.rethrowFromSystemServer();
11346         }
11347     }
11348 
11349     /**
11350      * This method is mostly deprecated.
11351      * Most of the settings that still have an effect have dedicated setter methods or user
11352      * restrictions. See individual settings for details.
11353      * <p>
11354      * Called by device owner to update {@link android.provider.Settings.Global} settings.
11355      * Validation that the value of the setting is in the correct form for the setting type should
11356      * be performed by the caller.
11357      * <p>
11358      * The settings that can be updated with this method are:
11359      * <ul>
11360      * <li>{@link android.provider.Settings.Global#ADB_ENABLED} : use
11361      * {@link UserManager#DISALLOW_DEBUGGING_FEATURES} instead to restrict users from enabling
11362      * debugging features and this setting to turn adb on.</li>
11363      * <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
11364      * <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only
11365      * available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
11366      * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
11367      * <li>{@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This
11368      * setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
11369      * </ul>
11370      * <p>
11371      * The following settings used to be supported, but can be controlled in other ways:
11372      * <ul>
11373      * <li>{@link android.provider.Settings.Global#AUTO_TIME} : Use {@link #setAutoTimeEnabled} and
11374      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} instead.</li>
11375      * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE} : Use
11376      * {@link #setAutoTimeZoneEnabled} and {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
11377      * instead.</li>
11378      * <li>{@link android.provider.Settings.Global#DATA_ROAMING} : Use
11379      * {@link UserManager#DISALLOW_DATA_ROAMING} instead.</li>
11380      * </ul>
11381      * <p>
11382      * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
11383      * <ul>
11384      * <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use
11385      * {@link android.bluetooth.BluetoothAdapter#enable()} and
11386      * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
11387      * <li>{@link android.provider.Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
11388      * <li>{@link android.provider.Settings.Global#MODE_RINGER}. Use
11389      * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
11390      * <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li>
11391      * <li>{@link android.provider.Settings.Global#WIFI_ON}. Use
11392      * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
11393      * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}. No longer has effect.</li>
11394      * </ul>
11395      *
11396      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11397      * @param setting The name of the setting to update.
11398      * @param value The value to update the setting to.
11399      * @throws SecurityException if {@code admin} is not a device owner.
11400      */
setGlobalSetting(@onNull ComponentName admin, String setting, String value)11401     public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
11402         throwIfParentInstance("setGlobalSetting");
11403         if (mService != null) {
11404             try {
11405                 mService.setGlobalSetting(admin, setting, value);
11406             } catch (RemoteException e) {
11407                 throw e.rethrowFromSystemServer();
11408             }
11409         }
11410     }
11411 
11412     /** @hide */
11413     @StringDef({
11414             Settings.System.SCREEN_BRIGHTNESS_MODE,
11415             Settings.System.SCREEN_BRIGHTNESS,
11416             Settings.System.SCREEN_BRIGHTNESS_FLOAT,
11417             Settings.System.SCREEN_OFF_TIMEOUT
11418     })
11419     @Retention(RetentionPolicy.SOURCE)
11420     public @interface SystemSettingsWhitelist {}
11421 
11422     /**
11423      * Called by a device or profile owner to update {@link android.provider.Settings.System}
11424      * settings. Validation that the value of the setting is in the correct form for the setting
11425      * type should be performed by the caller.
11426      * <p>
11427      * The settings that can be updated by a device owner or profile owner of secondary user with
11428      * this method are:
11429      * <ul>
11430      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS}</li>
11431      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS_MODE}</li>
11432      * <li>{@link android.provider.Settings.System#SCREEN_OFF_TIMEOUT}</li>
11433      * </ul>
11434      * <p>
11435      *
11436      * @see android.provider.Settings.System#SCREEN_OFF_TIMEOUT
11437      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11438      * @param setting The name of the setting to update.
11439      * @param value The value to update the setting to.
11440      * @throws SecurityException if {@code admin} is not a device or profile owner.
11441      */
setSystemSetting(@onNull ComponentName admin, @NonNull @SystemSettingsWhitelist String setting, String value)11442     public void setSystemSetting(@NonNull ComponentName admin,
11443             @NonNull @SystemSettingsWhitelist String setting, String value) {
11444         throwIfParentInstance("setSystemSetting");
11445         if (mService != null) {
11446             try {
11447                 mService.setSystemSetting(admin, setting, value);
11448             } catch (RemoteException e) {
11449                 throw e.rethrowFromSystemServer();
11450             }
11451         }
11452     }
11453 
11454     /**
11455      * Called by a device owner or a profile owner of an organization-owned managed profile to
11456      * control whether the user can change networks configured by the admin. When this lockdown is
11457      * enabled, the user can still configure and connect to other Wi-Fi networks, or use other Wi-Fi
11458      * capabilities such as tethering.
11459      * <p>
11460      * WiFi network configuration lockdown is controlled by a global settings
11461      * {@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN} and calling
11462      * this API effectively modifies the global settings. Previously device owners can also
11463      * control this directly via {@link #setGlobalSetting} but they are recommended to switch
11464      * to this API.
11465      *
11466      * @param admin             admin Which {@link DeviceAdminReceiver} this request is associated
11467      *                          with.
11468      * @param lockdown Whether the admin configured networks should be unmodifiable by the
11469      *                          user.
11470      * @throws SecurityException if caller is not a device owner or a profile owner of an
11471      *                           organization-owned managed profile.
11472      */
setConfiguredNetworksLockdownState(@onNull ComponentName admin, boolean lockdown)11473     public void setConfiguredNetworksLockdownState(@NonNull ComponentName admin, boolean lockdown) {
11474         throwIfParentInstance("setConfiguredNetworksLockdownState");
11475         if (mService != null) {
11476             try {
11477                 mService.setConfiguredNetworksLockdownState(admin, lockdown);
11478             } catch (RemoteException e) {
11479                 throw e.rethrowFromSystemServer();
11480             }
11481         }
11482     }
11483 
11484     /**
11485      * Called by a device owner or a profile owner of an organization-owned managed profile to
11486      * determine whether the user is prevented from modifying networks configured by the admin.
11487      *
11488      * @param admin             admin Which {@link DeviceAdminReceiver} this request is associated
11489      *                          with.
11490      * @throws SecurityException if caller is not a device owner or a profile owner of an
11491      *                           organization-owned managed profile.
11492      */
hasLockdownAdminConfiguredNetworks(@onNull ComponentName admin)11493     public boolean hasLockdownAdminConfiguredNetworks(@NonNull ComponentName admin) {
11494         throwIfParentInstance("hasLockdownAdminConfiguredNetworks");
11495         if (mService != null) {
11496             try {
11497                 return mService.hasLockdownAdminConfiguredNetworks(admin);
11498             } catch (RemoteException e) {
11499                 throw e.rethrowFromSystemServer();
11500             }
11501         }
11502         return false;
11503     }
11504 
11505     /**
11506      * Called by a device owner or a profile owner of an organization-owned managed
11507      * profile to set the system wall clock time. This only takes effect if called when
11508      * {@link android.provider.Settings.Global#AUTO_TIME} is 0, otherwise {@code false}
11509      * will be returned.
11510      *
11511      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
11512      * @param millis time in milliseconds since the Epoch
11513      * @return {@code true} if set time succeeded, {@code false} otherwise.
11514      * @throws SecurityException if {@code admin} is not a device owner or a profile owner
11515      * of an organization-owned managed profile.
11516      */
setTime(@onNull ComponentName admin, long millis)11517     public boolean setTime(@NonNull ComponentName admin, long millis) {
11518         throwIfParentInstance("setTime");
11519         if (mService != null) {
11520             try {
11521                 return mService.setTime(admin, millis);
11522             } catch (RemoteException e) {
11523                 throw e.rethrowFromSystemServer();
11524             }
11525         }
11526         return false;
11527     }
11528 
11529     /**
11530      * Called by a device owner or a profile owner of an organization-owned managed
11531      * profile to set the system's persistent default time zone. This only takes
11532      * effect if called when {@link android.provider.Settings.Global#AUTO_TIME_ZONE}
11533      * is 0, otherwise {@code false} will be returned.
11534      *
11535      * @see android.app.AlarmManager#setTimeZone(String)
11536      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
11537      * @param timeZone one of the Olson ids from the list returned by
11538      *     {@link java.util.TimeZone#getAvailableIDs}
11539      * @return {@code true} if set timezone succeeded, {@code false} otherwise.
11540      * @throws SecurityException if {@code admin} is not a device owner or a profile owner
11541      * of an organization-owned managed profile.
11542      */
setTimeZone(@onNull ComponentName admin, String timeZone)11543     public boolean setTimeZone(@NonNull ComponentName admin, String timeZone) {
11544         throwIfParentInstance("setTimeZone");
11545         if (mService != null) {
11546             try {
11547                 return mService.setTimeZone(admin, timeZone);
11548             } catch (RemoteException e) {
11549                 throw e.rethrowFromSystemServer();
11550             }
11551         }
11552         return false;
11553     }
11554 
11555     /**
11556      * Called by device owners to set the user's global location setting.
11557      *
11558      *
11559      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
11560      * @param locationEnabled whether location should be enabled or disabled. <b>Note: </b> on
11561      * {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, calls to
11562      * disable will be ignored.
11563      * @throws SecurityException if {@code admin} is not a device owner.
11564      */
setLocationEnabled(@onNull ComponentName admin, boolean locationEnabled)11565     public void setLocationEnabled(@NonNull ComponentName admin, boolean locationEnabled) {
11566         throwIfParentInstance("setLocationEnabled");
11567         if (mService != null) {
11568             try {
11569                 mService.setLocationEnabled(admin, locationEnabled);
11570             } catch (RemoteException e) {
11571                 throw e.rethrowFromSystemServer();
11572             }
11573         }
11574     }
11575 
11576     /**
11577      * This method is mostly deprecated.
11578      * Most of the settings that still have an effect have dedicated setter methods
11579      * (e.g. {@link #setLocationEnabled}) or user restrictions.
11580      * <p>
11581      *
11582      * Called by profile or device owners to update {@link android.provider.Settings.Secure}
11583      * settings. Validation that the value of the setting is in the correct form for the setting
11584      * type should be performed by the caller.
11585      * <p>
11586      * The settings that can be updated by a profile or device owner with this method are:
11587      * <ul>
11588      * <li>{@link android.provider.Settings.Secure#DEFAULT_INPUT_METHOD}</li>
11589      * <li>{@link android.provider.Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
11590      * </ul>
11591      * <p>
11592      * A device owner can additionally update the following settings:
11593      * <ul>
11594      * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}, but see note below.</li>
11595      * </ul>
11596      *
11597      * <strong>Note: Starting from Android O, apps should no longer call this method with the
11598      * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is
11599      * deprecated. Instead, device owners or profile owners should use the restriction
11600      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}.
11601      * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method
11602      * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS},
11603      * an {@link UnsupportedOperationException} is thrown.
11604      *
11605      * Starting from Android Q, the device and profile owner can also call
11606      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY} to restrict unknown sources for
11607      * all users.
11608      * </strong>
11609      *
11610      * <strong>Note: Starting from Android R, apps should no longer call this method with the
11611      * setting {@link android.provider.Settings.Secure#LOCATION_MODE}, which is deprecated. Instead,
11612      * device owners should call {@link #setLocationEnabled(ComponentName, boolean)}. This will be
11613      * enforced for all apps targeting Android R or above.
11614      * </strong>
11615      *
11616      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11617      * @param setting The name of the setting to update.
11618      * @param value The value to update the setting to.
11619      * @throws SecurityException if {@code admin} is not a device or profile owner.
11620      */
setSecureSetting(@onNull ComponentName admin, String setting, String value)11621     public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
11622         throwIfParentInstance("setSecureSetting");
11623 
11624         if (mService != null) {
11625             try {
11626                 mService.setSecureSetting(admin, setting, value);
11627             } catch (RemoteException e) {
11628                 throw e.rethrowFromSystemServer();
11629             }
11630         }
11631     }
11632 
11633     /**
11634      * Designates a specific service component as the provider for making permission requests of a
11635      * local or remote administrator of the user.
11636      * <p/>
11637      * Only a device owner or profile owner can designate the restrictions provider.
11638      *
11639      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11640      * @param provider The component name of the service that implements
11641      *            {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
11642      *            provider previously assigned.
11643      * @throws SecurityException if {@code admin} is not a device or profile owner.
11644      */
setRestrictionsProvider(@onNull ComponentName admin, @Nullable ComponentName provider)11645     public void setRestrictionsProvider(@NonNull ComponentName admin,
11646             @Nullable ComponentName provider) {
11647         throwIfParentInstance("setRestrictionsProvider");
11648         if (mService != null) {
11649             try {
11650                 mService.setRestrictionsProvider(admin, provider);
11651             } catch (RemoteException re) {
11652                 throw re.rethrowFromSystemServer();
11653             }
11654         }
11655     }
11656 
11657     /**
11658      * Called by profile or device owners to set the global volume mute on or off.
11659      * This has no effect when set on a managed profile.
11660      *
11661      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11662      * @param on {@code true} to mute global volume, {@code false} to turn mute off.
11663      * @throws SecurityException if {@code admin} is not a device or profile owner.
11664      */
setMasterVolumeMuted(@onNull ComponentName admin, boolean on)11665     public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
11666         throwIfParentInstance("setMasterVolumeMuted");
11667         if (mService != null) {
11668             try {
11669                 mService.setMasterVolumeMuted(admin, on);
11670             } catch (RemoteException re) {
11671                 throw re.rethrowFromSystemServer();
11672             }
11673         }
11674     }
11675 
11676     /**
11677      * Called by profile or device owners to check whether the global volume mute is on or off.
11678      *
11679      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11680      * @return {@code true} if global volume is muted, {@code false} if it's not.
11681      * @throws SecurityException if {@code admin} is not a device or profile owner.
11682      */
isMasterVolumeMuted(@onNull ComponentName admin)11683     public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
11684         throwIfParentInstance("isMasterVolumeMuted");
11685         if (mService != null) {
11686             try {
11687                 return mService.isMasterVolumeMuted(admin);
11688             } catch (RemoteException re) {
11689                 throw re.rethrowFromSystemServer();
11690             }
11691         }
11692         return false;
11693     }
11694 
11695     /**
11696      * Change whether a user can uninstall a package. This function can be called by a device owner,
11697      * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via
11698      * {@link #setDelegatedScopes}.
11699      *
11700      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
11701      *             {@code null} if the caller is a block uninstall delegate.
11702      * @param packageName package to change.
11703      * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
11704      * @throws SecurityException if {@code admin} is not a device or profile owner.
11705      * @see #setDelegatedScopes
11706      * @see #DELEGATION_BLOCK_UNINSTALL
11707      */
setUninstallBlocked(@ullable ComponentName admin, String packageName, boolean uninstallBlocked)11708     public void setUninstallBlocked(@Nullable ComponentName admin, String packageName,
11709             boolean uninstallBlocked) {
11710         throwIfParentInstance("setUninstallBlocked");
11711         if (mService != null) {
11712             try {
11713                 mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName,
11714                     uninstallBlocked);
11715             } catch (RemoteException re) {
11716                 throw re.rethrowFromSystemServer();
11717             }
11718         }
11719     }
11720 
11721     /**
11722      * Check whether the user has been blocked by device policy from uninstalling a package.
11723      * Requires the caller to be the profile owner if checking a specific admin's policy.
11724      * <p>
11725      * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
11726      * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
11727      * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
11728      * will cause a NullPointerException to be raised.
11729      * <p>
11730      * <strong>Note:</strong> If your app targets Android 11 (API level 30) or higher,
11731      * this method returns a filtered result. Learn more about how to
11732      * <a href="/training/basics/intents/package-visibility">manage package visibility</a>.
11733      *
11734      * @param admin The name of the admin component whose blocking policy will be checked, or
11735      *            {@code null} to check whether any admin has blocked the uninstallation.
11736      * @param packageName package to check.
11737      * @return true if uninstallation is blocked and the given package is visible to you, false
11738      *         otherwise if uninstallation isn't blocked or the given package isn't visible to you.
11739      * @throws SecurityException if {@code admin} is not a device or profile owner.
11740      */
isUninstallBlocked(@ullable ComponentName admin, String packageName)11741     public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
11742         throwIfParentInstance("isUninstallBlocked");
11743         if (mService != null) {
11744             try {
11745                 return mService.isUninstallBlocked(admin, packageName);
11746             } catch (RemoteException re) {
11747                 throw re.rethrowFromSystemServer();
11748             }
11749         }
11750         return false;
11751     }
11752 
11753     /**
11754      * Called by the profile owner of a managed profile to enable widget providers from a given
11755      * package to be available in the parent profile. As a result the user will be able to add
11756      * widgets from the allowlisted package running under the profile to a widget host which runs
11757      * under the parent profile, for example the home screen. Note that a package may have zero or
11758      * more provider components, where each component provides a different widget type.
11759      * <p>
11760      * <strong>Note:</strong> By default no widget provider package is allowlisted.
11761      *
11762      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11763      * @param packageName The package from which widget providers are allowlisted.
11764      * @return Whether the package was added.
11765      * @throws SecurityException if {@code admin} is not a profile owner.
11766      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
11767      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
11768      */
addCrossProfileWidgetProvider(@onNull ComponentName admin, String packageName)11769     public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
11770         throwIfParentInstance("addCrossProfileWidgetProvider");
11771         if (mService != null) {
11772             try {
11773                 return mService.addCrossProfileWidgetProvider(admin, packageName);
11774             } catch (RemoteException re) {
11775                 throw re.rethrowFromSystemServer();
11776             }
11777         }
11778         return false;
11779     }
11780 
11781     /**
11782      * Called by the profile owner of a managed profile to disable widget providers from a given
11783      * package to be available in the parent profile. For this method to take effect the package
11784      * should have been added via
11785      * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
11786      * <p>
11787      * <strong>Note:</strong> By default no widget provider package is allowlisted.
11788      *
11789      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11790      * @param packageName The package from which widget providers are no longer allowlisted.
11791      * @return Whether the package was removed.
11792      * @throws SecurityException if {@code admin} is not a profile owner.
11793      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
11794      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
11795      */
removeCrossProfileWidgetProvider( @onNull ComponentName admin, String packageName)11796     public boolean removeCrossProfileWidgetProvider(
11797             @NonNull ComponentName admin, String packageName) {
11798         throwIfParentInstance("removeCrossProfileWidgetProvider");
11799         if (mService != null) {
11800             try {
11801                 return mService.removeCrossProfileWidgetProvider(admin, packageName);
11802             } catch (RemoteException re) {
11803                 throw re.rethrowFromSystemServer();
11804             }
11805         }
11806         return false;
11807     }
11808 
11809     /**
11810      * Called by the profile owner of a managed profile to query providers from which packages are
11811      * available in the parent profile.
11812      *
11813      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11814      * @return The allowlisted package list.
11815      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
11816      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
11817      * @throws SecurityException if {@code admin} is not a profile owner.
11818      */
getCrossProfileWidgetProviders(@onNull ComponentName admin)11819     public @NonNull List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
11820         throwIfParentInstance("getCrossProfileWidgetProviders");
11821         if (mService != null) {
11822             try {
11823                 List<String> providers = mService.getCrossProfileWidgetProviders(admin);
11824                 if (providers != null) {
11825                     return providers;
11826                 }
11827             } catch (RemoteException re) {
11828                 throw re.rethrowFromSystemServer();
11829             }
11830         }
11831         return Collections.emptyList();
11832     }
11833 
11834     /**
11835      * Called by profile or device owners to set the user's photo.
11836      *
11837      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11838      * @param icon the bitmap to set as the photo.
11839      * @throws SecurityException if {@code admin} is not a device or profile owner.
11840      */
setUserIcon(@onNull ComponentName admin, Bitmap icon)11841     public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
11842         throwIfParentInstance("setUserIcon");
11843         try {
11844             mService.setUserIcon(admin, icon);
11845         } catch (RemoteException re) {
11846             throw re.rethrowFromSystemServer();
11847         }
11848     }
11849 
11850     /**
11851      * Called by device owners or profile owners of an organization-owned managed profile to to set
11852      * a local system update policy. When a new policy is set,
11853      * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
11854      * <p>
11855      * If the supplied system update policy has freeze periods set but the freeze periods do not
11856      * meet 90-day maximum length or 60-day minimum separation requirement set out in
11857      * {@link SystemUpdatePolicy#setFreezePeriods},
11858      * {@link SystemUpdatePolicy.ValidationFailedException} will the thrown. Note that the system
11859      * keeps a record of freeze periods the device experienced previously, and combines them with
11860      * the new freeze periods to be set when checking the maximum freeze length and minimum freeze
11861      * separation constraints. As a result, freeze periods that passed validation during
11862      * {@link SystemUpdatePolicy#setFreezePeriods} might fail the additional checks here due to
11863      * the freeze period history. If this is causing issues during development,
11864      * {@code adb shell dpm clear-freeze-period-record} can be used to clear the record.
11865      *
11866      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
11867      *            components in the device owner package can set system update policies and the most
11868      *            recent policy takes effect.
11869      * @param policy the new policy, or {@code null} to clear the current policy.
11870      * @throws SecurityException if {@code admin} is not a device owner or a profile owner of an
11871      *      organization-owned managed profile.
11872      * @throws IllegalArgumentException if the policy type or maintenance window is not valid.
11873      * @throws SystemUpdatePolicy.ValidationFailedException if the policy's freeze period does not
11874      *             meet the requirement.
11875      * @see SystemUpdatePolicy
11876      * @see SystemUpdatePolicy#setFreezePeriods(List)
11877      */
setSystemUpdatePolicy(@onNull ComponentName admin, SystemUpdatePolicy policy)11878     public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
11879         throwIfParentInstance("setSystemUpdatePolicy");
11880         if (mService != null) {
11881             try {
11882                 mService.setSystemUpdatePolicy(admin, policy);
11883             } catch (RemoteException re) {
11884                 throw re.rethrowFromSystemServer();
11885             }
11886         }
11887     }
11888 
11889     /**
11890      * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
11891      *
11892      * @return The current policy object, or {@code null} if no policy is set.
11893      */
getSystemUpdatePolicy()11894     public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
11895         throwIfParentInstance("getSystemUpdatePolicy");
11896         if (mService != null) {
11897             try {
11898                 return mService.getSystemUpdatePolicy();
11899             } catch (RemoteException re) {
11900                 throw re.rethrowFromSystemServer();
11901             }
11902         }
11903         return null;
11904     }
11905 
11906     /**
11907      * Reset record of previous system update freeze period the device went through.
11908      * @hide
11909      */
11910     @TestApi
11911     @RequiresPermission(android.Manifest.permission.CLEAR_FREEZE_PERIOD)
clearSystemUpdatePolicyFreezePeriodRecord()11912     public void clearSystemUpdatePolicyFreezePeriodRecord() {
11913         throwIfParentInstance("clearSystemUpdatePolicyFreezePeriodRecord");
11914         if (mService == null) {
11915             return;
11916         }
11917         try {
11918             mService.clearSystemUpdatePolicyFreezePeriodRecord();
11919         } catch (RemoteException re) {
11920             throw re.rethrowFromSystemServer();
11921         }
11922     }
11923 
11924     /**
11925      * Called by a device owner or profile owner of secondary users that is affiliated with the
11926      * device to disable the keyguard altogether.
11927      * <p>
11928      * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
11929      * type. However, this call has no effect if a password, pin or pattern is currently set. If a
11930      * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
11931      * disabled.
11932      *
11933      * <p>
11934      * As of {@link android.os.Build.VERSION_CODES#P}, this call also dismisses the
11935      * keyguard if it is currently shown.
11936      *
11937      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11938      * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
11939      * @return {@code false} if attempting to disable the keyguard while a lock password was in
11940      *         place. {@code true} otherwise.
11941      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
11942      * secondary user that is affiliated with the device.
11943      * @see #isAffiliatedUser
11944      * @see #getSecondaryUsers
11945      */
setKeyguardDisabled(@onNull ComponentName admin, boolean disabled)11946     public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
11947         throwIfParentInstance("setKeyguardDisabled");
11948         try {
11949             return mService.setKeyguardDisabled(admin, disabled);
11950         } catch (RemoteException re) {
11951             throw re.rethrowFromSystemServer();
11952         }
11953     }
11954 
11955     /**
11956      * Called by device owner or profile owner of secondary users that is affiliated with the
11957      * device to disable the status bar. Disabling the status bar blocks notifications and quick
11958      * settings.
11959      * <p>
11960      * <strong>Note:</strong> This method has no effect for LockTask mode. The behavior of the
11961      * status bar in LockTask mode can be configured with
11962      * {@link #setLockTaskFeatures(ComponentName, int)}. Calls to this method when the device is in
11963      * LockTask mode will be registered, but will only take effect when the device leaves LockTask
11964      * mode.
11965      *
11966      * <p>This policy does not have any effect while on the lock screen, where the status bar will
11967      * not be disabled. Using LockTask instead of this method is recommended.
11968      *
11969      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11970      * @param disabled {@code true} disables the status bar, {@code false} reenables it.
11971      * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
11972      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
11973      * secondary user that is affiliated with the device.
11974      * @see #isAffiliatedUser
11975      * @see #getSecondaryUsers
11976      */
setStatusBarDisabled(@onNull ComponentName admin, boolean disabled)11977     public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
11978         throwIfParentInstance("setStatusBarDisabled");
11979         try {
11980             return mService.setStatusBarDisabled(admin, disabled);
11981         } catch (RemoteException re) {
11982             throw re.rethrowFromSystemServer();
11983         }
11984     }
11985 
11986     /**
11987      * Called by the system update service to notify device and profile owners of pending system
11988      * updates.
11989      *
11990      * This method should only be used when it is unknown whether the pending system
11991      * update is a security patch. Otherwise, use
11992      * {@link #notifyPendingSystemUpdate(long, boolean)}.
11993      *
11994      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
11995      *         indicating when the current pending update was first available. {@code -1} if no
11996      *         update is available.
11997      * @see #notifyPendingSystemUpdate(long, boolean)
11998      * @hide
11999      */
12000     @SystemApi
12001     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime)12002     public void notifyPendingSystemUpdate(long updateReceivedTime) {
12003         throwIfParentInstance("notifyPendingSystemUpdate");
12004         if (mService != null) {
12005             try {
12006                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime));
12007             } catch (RemoteException re) {
12008                 throw re.rethrowFromSystemServer();
12009             }
12010         }
12011     }
12012 
12013     /**
12014      * Called by the system update service to notify device and profile owners of pending system
12015      * updates.
12016      *
12017      * This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
12018      * when it is known whether the pending system update is a security patch.
12019      *
12020      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
12021      *         indicating when the current pending update was first available. {@code -1} if no
12022      *         update is available.
12023      * @param isSecurityPatch {@code true} if this system update is purely a security patch;
12024      *         {@code false} if not.
12025      * @see #notifyPendingSystemUpdate(long)
12026      * @hide
12027      */
12028     @SystemApi
12029     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch)12030     public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) {
12031         throwIfParentInstance("notifyPendingSystemUpdate");
12032         if (mService != null) {
12033             try {
12034                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime,
12035                         isSecurityPatch));
12036             } catch (RemoteException re) {
12037                 throw re.rethrowFromSystemServer();
12038             }
12039         }
12040     }
12041 
12042     /**
12043      * Called by device or profile owners to get information about a pending system update.
12044      *
12045      * @param admin Which profile or device owner this request is associated with.
12046      * @return Information about a pending system update or {@code null} if no update pending.
12047      * @throws SecurityException if {@code admin} is not a device or profile owner.
12048      * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long)
12049      */
getPendingSystemUpdate(@onNull ComponentName admin)12050     public @Nullable SystemUpdateInfo getPendingSystemUpdate(@NonNull ComponentName admin) {
12051         throwIfParentInstance("getPendingSystemUpdate");
12052         try {
12053             return mService.getPendingSystemUpdate(admin);
12054         } catch (RemoteException re) {
12055             throw re.rethrowFromSystemServer();
12056         }
12057     }
12058 
12059     /**
12060      * Set the default response for future runtime permission requests by applications. This
12061      * function can be called by a device owner, profile owner, or by a delegate given the
12062      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
12063      * The policy can allow for normal operation which prompts the user to grant a permission, or
12064      * can allow automatic granting or denying of runtime permission requests by an application.
12065      * This also applies to new permissions declared by app updates. When a permission is denied or
12066      * granted this way, the effect is equivalent to setting the permission * grant state via
12067      * {@link #setPermissionGrantState}.
12068      * <p/>
12069      * As this policy only acts on runtime permission requests, it only applies to applications
12070      * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
12071      *
12072      * <p>
12073      * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, an auto-grant
12074      * policy will not apply to certain sensors-related permissions on some configurations.
12075      * See {@link #setPermissionGrantState(ComponentName, String, String, int)} for the list of
12076      * permissions affected, and the behavior change for managed profiles and fully-managed
12077      * devices.
12078      *
12079      * @param admin Which profile or device owner this request is associated with.
12080      * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
12081      *            {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
12082      * @throws SecurityException if {@code admin} is not a device or profile owner.
12083      * @see #setPermissionGrantState
12084      * @see #setDelegatedScopes
12085      * @see #DELEGATION_PERMISSION_GRANT
12086      */
setPermissionPolicy(@onNull ComponentName admin, int policy)12087     public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
12088         throwIfParentInstance("setPermissionPolicy");
12089         try {
12090             mService.setPermissionPolicy(admin, mContext.getPackageName(), policy);
12091         } catch (RemoteException re) {
12092             throw re.rethrowFromSystemServer();
12093         }
12094     }
12095 
12096     /**
12097      * Returns the current runtime permission policy set by the device or profile owner. The
12098      * default is {@link #PERMISSION_POLICY_PROMPT}.
12099      *
12100      * @param admin Which profile or device owner this request is associated with.
12101      * @return the current policy for future permission requests.
12102      */
getPermissionPolicy(ComponentName admin)12103     public int getPermissionPolicy(ComponentName admin) {
12104         throwIfParentInstance("getPermissionPolicy");
12105         try {
12106             return mService.getPermissionPolicy(admin);
12107         } catch (RemoteException re) {
12108             throw re.rethrowFromSystemServer();
12109         }
12110     }
12111 
12112     /**
12113      * Sets the grant state of a runtime permission for a specific application. The state can be
12114      * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
12115      * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
12116      * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
12117      * the permission is granted and the user cannot manage it through the UI. This method can only
12118      * be called by a profile owner, device owner, or a delegate given the
12119      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
12120      * <p/>
12121      * Note that user cannot manage other permissions in the affected group through the UI
12122      * either and their granted state will be kept as the current value. Thus, it's recommended that
12123      * you set the grant state of all the permissions in the affected group.
12124      * <p/>
12125      * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
12126      * the permission. It retains the previous grant, if any.
12127      * <p/>
12128      * Device admins with a {@code targetSdkVersion} &lt; {@link android.os.Build.VERSION_CODES#Q}
12129      * cannot grant and revoke permissions for applications built with a {@code targetSdkVersion}
12130      * &lt; {@link android.os.Build.VERSION_CODES#M}.
12131      * <p/>
12132      * Admins with a {@code targetSdkVersion} &ge; {@link android.os.Build.VERSION_CODES#Q} can
12133      * grant and revoke permissions of all apps. Similar to the user revoking a permission from a
12134      * application built with a {@code targetSdkVersion} &lt;
12135      * {@link android.os.Build.VERSION_CODES#M} the app-op matching the permission is set to
12136      * {@link android.app.AppOpsManager#MODE_IGNORED}, but the permission stays granted.
12137      * <p>
12138      * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, control over
12139      * the following, sensors-related, permissions is restricted:
12140      * <ul>
12141      *    <li>Manifest.permission.ACCESS_FINE_LOCATION</li>
12142      *    <li>Manifest.permission.ACCESS_BACKGROUND_LOCATION</li>
12143      *    <li>Manifest.permission.ACCESS_COARSE_LOCATION</li>
12144      *    <li>Manifest.permission.CAMERA</li>
12145      *    <li>Manifest.permission.RECORD_AUDIO</li>
12146      *    <li>Manifest.permission.RECORD_BACKGROUND_AUDIO</li>
12147      *    <li>Manifest.permission.ACTIVITY_RECOGNITION</li>
12148      *    <li>Manifest.permission.BODY_SENSORS</li>
12149      * </ul>
12150      * <p>
12151      * A profile owner may not grant these permissions (i.e. call this method with any of the
12152      * permissions listed above and {@code grantState} of {@code #PERMISSION_GRANT_STATE_GRANTED}),
12153      * but may deny them.
12154      * <p>
12155      * A device owner, by default, may continue granting these permissions. However, for increased
12156      * user control, the admin may opt out of controlling grants for these permissions by including
12157      * {@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT} in the provisioning parameters.
12158      * In that case the device owner's control will be limited do denying these permissions.
12159      * <p>
12160      * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, control over
12161      * the following permissions are restricted for managed profile owners:
12162      * <ul>
12163      *    <li>Manifest.permission.READ_SMS</li>
12164      * </ul>
12165      * <p>
12166      * A managed profile owner may not grant these permissions (i.e. call this method with any of
12167      * the permissions listed above and {@code grantState} of
12168      * {@code #PERMISSION_GRANT_STATE_GRANTED}), but may deny them.
12169      * <p>
12170      * Attempts by the admin to grant these permissions, when the admin is restricted from doing
12171      * so, will be silently ignored (no exception will be thrown).
12172      *
12173      * Control over the following permissions are restricted for managed profile owners:
12174      * <ul>
12175      *  <li>Manifest.permission.READ_SMS</li>
12176      * </ul>
12177      * <p>
12178      * A managed profile owner may not grant these permissions (i.e. call this method with any of
12179      * the permissions listed above and {@code grantState} of
12180      * {@code #PERMISSION_GRANT_STATE_GRANTED}), but may deny them.
12181      *
12182      * @param admin Which profile or device owner this request is associated with.
12183      * @param packageName The application to grant or revoke a permission to.
12184      * @param permission The permission to grant or revoke.
12185      * @param grantState The permission grant state which is one of
12186      *            {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
12187      *            {@link #PERMISSION_GRANT_STATE_GRANTED},
12188      * @return whether the permission was successfully granted or revoked.
12189      * @throws SecurityException if {@code admin} is not a device or profile owner.
12190      * @see #PERMISSION_GRANT_STATE_DENIED
12191      * @see #PERMISSION_GRANT_STATE_DEFAULT
12192      * @see #PERMISSION_GRANT_STATE_GRANTED
12193      * @see #setDelegatedScopes
12194      * @see #DELEGATION_PERMISSION_GRANT
12195      */
setPermissionGrantState(@onNull ComponentName admin, @NonNull String packageName, @NonNull String permission, @PermissionGrantState int grantState)12196     public boolean setPermissionGrantState(@NonNull ComponentName admin,
12197             @NonNull String packageName, @NonNull String permission,
12198             @PermissionGrantState int grantState) {
12199         throwIfParentInstance("setPermissionGrantState");
12200         try {
12201             CompletableFuture<Boolean> result = new CompletableFuture<>();
12202 
12203             mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName,
12204                     permission, grantState, new RemoteCallback((b) -> result.complete(b != null)));
12205 
12206             // Timeout
12207             BackgroundThread.getHandler().sendMessageDelayed(
12208                     obtainMessage(CompletableFuture::complete, result, false),
12209                     20_000);
12210 
12211             return result.get();
12212         } catch (RemoteException re) {
12213             throw re.rethrowFromSystemServer();
12214         } catch (InterruptedException | ExecutionException e) {
12215             throw new RuntimeException(e);
12216         }
12217     }
12218 
12219     /**
12220      * Returns the current grant state of a runtime permission for a specific application. This
12221      * function can be called by a device owner, profile owner, or by a delegate given the
12222      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
12223      *
12224      * @param admin Which profile or device owner this request is associated with, or {@code null}
12225      *            if the caller is a permission grant delegate.
12226      * @param packageName The application to check the grant state for.
12227      * @param permission The permission to check for.
12228      * @return the current grant state specified by device policy. If the profile or device owner
12229      *         has not set a grant state, the return value is
12230      *         {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
12231      *         permission is currently granted for the package.
12232      *         <p/>
12233      *         If a grant state was set by the profile or device owner, then the return value will
12234      *         be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
12235      *         {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
12236      *         currently denied or granted.
12237      * @throws SecurityException if {@code admin} is not a device or profile owner.
12238      * @see #setPermissionGrantState(ComponentName, String, String, int)
12239      * @see PackageManager#checkPermission(String, String)
12240      * @see #setDelegatedScopes
12241      * @see #DELEGATION_PERMISSION_GRANT
12242      */
getPermissionGrantState(@ullable ComponentName admin, @NonNull String packageName, @NonNull String permission)12243     public @PermissionGrantState int getPermissionGrantState(@Nullable ComponentName admin,
12244             @NonNull String packageName, @NonNull String permission) {
12245         throwIfParentInstance("getPermissionGrantState");
12246         try {
12247             return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName,
12248                     permission);
12249         } catch (RemoteException re) {
12250             throw re.rethrowFromSystemServer();
12251         }
12252     }
12253 
12254     /**
12255      * Returns whether it is possible for the caller to initiate provisioning of a managed profile
12256      * or device, setting itself as the device or profile owner.
12257      *
12258      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
12259      * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
12260      * @return whether provisioning a managed profile or device is possible.
12261      * @throws IllegalArgumentException if the supplied action is not valid.
12262      */
isProvisioningAllowed(@onNull String action)12263     public boolean isProvisioningAllowed(@NonNull String action) {
12264         throwIfParentInstance("isProvisioningAllowed");
12265         try {
12266             return mService.isProvisioningAllowed(action, mContext.getPackageName());
12267         } catch (RemoteException re) {
12268             throw re.rethrowFromSystemServer();
12269         }
12270     }
12271 
12272     /**
12273      * Checks whether it is possible to initiate provisioning a managed device,
12274      * profile or user, setting the given package as owner.
12275      *
12276      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
12277      *        {@link #ACTION_PROVISION_MANAGED_PROFILE}
12278      * @param packageName The package of the component that would be set as device, user, or profile
12279      *        owner.
12280      * @return An int constant value indicating whether provisioning is allowed.
12281      * @hide
12282      */
12283     @SystemApi
12284     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
12285     @ProvisioningPrecondition
checkProvisioningPrecondition( @onNull String action, @NonNull String packageName)12286     public int checkProvisioningPrecondition(
12287             @NonNull String action, @NonNull String packageName) {
12288         try {
12289             return mService.checkProvisioningPrecondition(action, packageName);
12290         } catch (RemoteException re) {
12291             throw re.rethrowFromSystemServer();
12292         }
12293     }
12294 
12295     /**
12296      * Return if this user is a managed profile of another user. An admin can become the profile
12297      * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
12298      * user with {@link #createAndManageUser}
12299      * @param admin Which profile owner this request is associated with.
12300      * @return if this user is a managed profile of another user.
12301      */
isManagedProfile(@onNull ComponentName admin)12302     public boolean isManagedProfile(@NonNull ComponentName admin) {
12303         throwIfParentInstance("isManagedProfile");
12304         try {
12305             return mService.isManagedProfile(admin);
12306         } catch (RemoteException re) {
12307             throw re.rethrowFromSystemServer();
12308         }
12309     }
12310 
12311     /**
12312      * Called by device owner, or profile owner on organization-owned device, to get the MAC
12313      * address of the Wi-Fi device.
12314      *
12315      * NOTE: The MAC address returned here should only be used for inventory management and is
12316      * not likely to be the MAC address used by the device to connect to Wi-Fi networks: MAC
12317      * addresses used for scanning and connecting to Wi-Fi networks are randomized by default.
12318      * To get the randomized MAC address used, call
12319      * {@link android.net.wifi.WifiConfiguration#getRandomizedMacAddress}.
12320      *
12321      * @param admin Which device owner this request is associated with.
12322      * @return the MAC address of the Wi-Fi device, or null when the information is not available.
12323      *         (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
12324      *         <p>
12325      *         The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
12326      * @throws SecurityException if {@code admin} is not a device owner.
12327      */
getWifiMacAddress(@onNull ComponentName admin)12328     public @Nullable String getWifiMacAddress(@NonNull ComponentName admin) {
12329         throwIfParentInstance("getWifiMacAddress");
12330         try {
12331             return mService.getWifiMacAddress(admin);
12332         } catch (RemoteException re) {
12333             throw re.rethrowFromSystemServer();
12334         }
12335     }
12336 
12337     /**
12338      * Called by device owner to reboot the device. If there is an ongoing call on the device,
12339      * throws an {@link IllegalStateException}.
12340      * @param admin Which device owner the request is associated with.
12341      * @throws IllegalStateException if device has an ongoing call.
12342      * @throws SecurityException if {@code admin} is not a device owner.
12343      * @see TelephonyManager#CALL_STATE_IDLE
12344      */
reboot(@onNull ComponentName admin)12345     public void reboot(@NonNull ComponentName admin) {
12346         throwIfParentInstance("reboot");
12347         try {
12348             mService.reboot(admin);
12349         } catch (RemoteException re) {
12350             throw re.rethrowFromSystemServer();
12351         }
12352     }
12353 
12354     /**
12355      * Called by a device admin to set the short support message. This will be displayed to the user
12356      * in settings screens where funtionality has been disabled by the admin. The message should be
12357      * limited to a short statement such as "This setting is disabled by your administrator. Contact
12358      * someone@example.com for support." If the message is longer than 200 characters it may be
12359      * truncated.
12360      * <p>
12361      * If the short support message needs to be localized, it is the responsibility of the
12362      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
12363      * and set a new version of this string accordingly.
12364      *
12365      * @see #setLongSupportMessage
12366      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12367      * @param message Short message to be displayed to the user in settings or null to clear the
12368      *            existing message.
12369      * @throws SecurityException if {@code admin} is not an active administrator.
12370      */
setShortSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)12371     public void setShortSupportMessage(@NonNull ComponentName admin,
12372             @Nullable CharSequence message) {
12373         throwIfParentInstance("setShortSupportMessage");
12374         if (mService != null) {
12375             try {
12376                 mService.setShortSupportMessage(admin, message);
12377             } catch (RemoteException e) {
12378                 throw e.rethrowFromSystemServer();
12379             }
12380         }
12381     }
12382 
12383     /**
12384      * Called by a device admin to get the short support message.
12385      *
12386      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12387      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
12388      *         null if no message has been set.
12389      * @throws SecurityException if {@code admin} is not an active administrator.
12390      */
getShortSupportMessage(@onNull ComponentName admin)12391     public CharSequence getShortSupportMessage(@NonNull ComponentName admin) {
12392         throwIfParentInstance("getShortSupportMessage");
12393         if (mService != null) {
12394             try {
12395                 return mService.getShortSupportMessage(admin);
12396             } catch (RemoteException e) {
12397                 throw e.rethrowFromSystemServer();
12398             }
12399         }
12400         return null;
12401     }
12402 
12403     /**
12404      * Called by a device admin to set the long support message. This will be displayed to the user
12405      * in the device administrators settings screen. If the message is longer than 20000 characters
12406      * it may be truncated.
12407      * <p>
12408      * If the long support message needs to be localized, it is the responsibility of the
12409      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
12410      * and set a new version of this string accordingly.
12411      *
12412      * @see #setShortSupportMessage
12413      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12414      * @param message Long message to be displayed to the user in settings or null to clear the
12415      *            existing message.
12416      * @throws SecurityException if {@code admin} is not an active administrator.
12417      */
setLongSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)12418     public void setLongSupportMessage(@NonNull ComponentName admin,
12419             @Nullable CharSequence message) {
12420         throwIfParentInstance("setLongSupportMessage");
12421         if (mService != null) {
12422             try {
12423                 mService.setLongSupportMessage(admin, message);
12424             } catch (RemoteException e) {
12425                 throw e.rethrowFromSystemServer();
12426             }
12427         }
12428     }
12429 
12430     /**
12431      * Called by a device admin to get the long support message.
12432      *
12433      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12434      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
12435      *         null if no message has been set.
12436      * @throws SecurityException if {@code admin} is not an active administrator.
12437      */
getLongSupportMessage(@onNull ComponentName admin)12438     public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
12439         throwIfParentInstance("getLongSupportMessage");
12440         if (mService != null) {
12441             try {
12442                 return mService.getLongSupportMessage(admin);
12443             } catch (RemoteException e) {
12444                 throw e.rethrowFromSystemServer();
12445             }
12446         }
12447         return null;
12448     }
12449 
12450     /**
12451      * Called by the system to get the short support message.
12452      *
12453      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12454      * @param userHandle user id the admin is running as.
12455      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
12456      *
12457      * @hide
12458      */
getShortSupportMessageForUser(@onNull ComponentName admin, int userHandle)12459     public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
12460             int userHandle) {
12461         if (mService != null) {
12462             try {
12463                 return mService.getShortSupportMessageForUser(admin, userHandle);
12464             } catch (RemoteException e) {
12465                 throw e.rethrowFromSystemServer();
12466             }
12467         }
12468         return null;
12469     }
12470 
12471 
12472     /**
12473      * Called by the system to get the long support message.
12474      *
12475      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12476      * @param userHandle user id the admin is running as.
12477      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
12478      *
12479      * @hide
12480      */
getLongSupportMessageForUser( @onNull ComponentName admin, int userHandle)12481     public @Nullable CharSequence getLongSupportMessageForUser(
12482             @NonNull ComponentName admin, int userHandle) {
12483         if (mService != null) {
12484             try {
12485                 return mService.getLongSupportMessageForUser(admin, userHandle);
12486             } catch (RemoteException e) {
12487                 throw e.rethrowFromSystemServer();
12488             }
12489         }
12490         return null;
12491     }
12492 
12493     /**
12494      * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
12495      * whose calls act on the parent profile.
12496      *
12497      * <p>The following methods are supported for the parent instance, all other methods will
12498      * throw a SecurityException when called on the parent instance:
12499      * <ul>
12500      * <li>{@link #getPasswordQuality}</li>
12501      * <li>{@link #setPasswordQuality}</li>
12502      * <li>{@link #getPasswordMinimumLength}</li>
12503      * <li>{@link #setPasswordMinimumLength}</li>
12504      * <li>{@link #getPasswordMinimumUpperCase}</li>
12505      * <li>{@link #setPasswordMinimumUpperCase}</li>
12506      * <li>{@link #getPasswordMinimumLowerCase}</li>
12507      * <li>{@link #setPasswordMinimumLowerCase}</li>
12508      * <li>{@link #getPasswordMinimumLetters}</li>
12509      * <li>{@link #setPasswordMinimumLetters}</li>
12510      * <li>{@link #getPasswordMinimumNumeric}</li>
12511      * <li>{@link #setPasswordMinimumNumeric}</li>
12512      * <li>{@link #getPasswordMinimumSymbols}</li>
12513      * <li>{@link #setPasswordMinimumSymbols}</li>
12514      * <li>{@link #getPasswordMinimumNonLetter}</li>
12515      * <li>{@link #setPasswordMinimumNonLetter}</li>
12516      * <li>{@link #getPasswordHistoryLength}</li>
12517      * <li>{@link #setPasswordHistoryLength}</li>
12518      * <li>{@link #getPasswordExpirationTimeout}</li>
12519      * <li>{@link #setPasswordExpirationTimeout}</li>
12520      * <li>{@link #getPasswordExpiration}</li>
12521      * <li>{@link #getPasswordMaximumLength}</li>
12522      * <li>{@link #isActivePasswordSufficient}</li>
12523      * <li>{@link #getCurrentFailedPasswordAttempts}</li>
12524      * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
12525      * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
12526      * <li>{@link #getMaximumTimeToLock}</li>
12527      * <li>{@link #setMaximumTimeToLock}</li>
12528      * <li>{@link #lockNow}</li>
12529      * <li>{@link #getKeyguardDisabledFeatures}</li>
12530      * <li>{@link #setKeyguardDisabledFeatures}</li>
12531      * <li>{@link #getTrustAgentConfiguration}</li>
12532      * <li>{@link #setTrustAgentConfiguration}</li>
12533      * <li>{@link #getRequiredStrongAuthTimeout}</li>
12534      * <li>{@link #setRequiredStrongAuthTimeout}</li>
12535      * <li>{@link #getAccountTypesWithManagementDisabled}</li>
12536      * <li>{@link #setRequiredPasswordComplexity(int)} </li>
12537      * <li>{@link #getRequiredPasswordComplexity()}</li>
12538      * </ul>
12539      * <p>
12540      * The following methods are supported for the parent instance but can only be called by the
12541      * profile owner of a managed profile that was created during the device provisioning flow:
12542      * <ul>
12543      * <li>{@link #getPasswordComplexity}</li>
12544      * <li>{@link #setCameraDisabled}</li>
12545      * <li>{@link #getCameraDisabled}</li>
12546      * <li>{@link #setAccountManagementDisabled(ComponentName, String, boolean)}</li>
12547      * <li>{@link #setPermittedInputMethods}</li>
12548      * <li>{@link #getPermittedInputMethods}</li>
12549      * </ul>
12550      *
12551      * <p>The following methods can be called by the profile owner of a managed profile
12552      * on an organization-owned device:
12553      * <ul>
12554      * <li>{@link #wipeData}</li>
12555      * </ul>
12556      *
12557      * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
12558      * @throws SecurityException if {@code admin} is not a profile owner.
12559      */
getParentProfileInstance(@onNull ComponentName admin)12560     public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
12561         throwIfParentInstance("getParentProfileInstance");
12562         try {
12563             if (!mService.isManagedProfile(admin)) {
12564                 throw new SecurityException("The current user does not have a parent profile.");
12565             }
12566             return new DevicePolicyManager(mContext, mService, true);
12567         } catch (RemoteException e) {
12568             throw e.rethrowFromSystemServer();
12569         }
12570     }
12571 
12572     /**
12573      * Called by device owner or a profile owner of an organization-owned managed profile to
12574      * control the security logging feature.
12575      *
12576      * <p> Security logs contain various information intended for security auditing purposes.
12577      * When security logging is enabled by a profile owner of
12578      * an organization-owned managed profile, certain security logs are not visible (for example
12579      * personal app launch events) or they will be redacted (for example, details of the physical
12580      * volume mount events). Please see {@link SecurityEvent} for details.
12581      *
12582      * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there
12583      * are unaffiliated secondary users or profiles on the device, regardless of whether the
12584      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
12585      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
12586      * new users as soon as possible after provisioning via {@link #setAffiliationIds}. Profile
12587      * owner of organization-owned managed profile is not subject to this restriction since all
12588      * privacy-sensitive events happening outside the managed profile would have been redacted
12589      * already.
12590      *
12591      * @param admin Which device admin this request is associated with.
12592      * @param enabled whether security logging should be enabled or not.
12593      * @throws SecurityException if {@code admin} is not allowed to control security logging.
12594      * @see #setAffiliationIds
12595      * @see #retrieveSecurityLogs
12596      */
setSecurityLoggingEnabled(@onNull ComponentName admin, boolean enabled)12597     public void setSecurityLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
12598         throwIfParentInstance("setSecurityLoggingEnabled");
12599         try {
12600             mService.setSecurityLoggingEnabled(admin, mContext.getPackageName(), enabled);
12601         } catch (RemoteException re) {
12602             throw re.rethrowFromSystemServer();
12603         }
12604     }
12605 
12606     /**
12607      * Return whether security logging is enabled or not by the admin.
12608      *
12609      * <p>Can only be called by the device owner or a profile owner of an organization-owned
12610      * managed profile, otherwise a {@link SecurityException} will be thrown.
12611      *
12612      * @param admin Which device admin this request is associated with.
12613      * @return {@code true} if security logging is enabled by device owner, {@code false} otherwise.
12614      * @throws SecurityException if {@code admin} is not allowed to control security logging.
12615      */
isSecurityLoggingEnabled(@ullable ComponentName admin)12616     public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) {
12617         throwIfParentInstance("isSecurityLoggingEnabled");
12618         try {
12619             return mService.isSecurityLoggingEnabled(admin, mContext.getPackageName());
12620         } catch (RemoteException re) {
12621             throw re.rethrowFromSystemServer();
12622         }
12623     }
12624 
12625     /**
12626      * Called by device owner or profile owner of an organization-owned managed profile to retrieve
12627      * all new security logging entries since the last call to this API after device boots.
12628      *
12629      * <p> Access to the logs is rate limited and it will only return new logs after the device
12630      * owner has been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
12631      *
12632      * <p> When called by a device owner, if there is any other user or profile on the device,
12633      * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown.
12634      * See {@link #isAffiliatedUser}.
12635      *
12636      * @param admin Which device admin this request is associated with.
12637      * @return the new batch of security logs which is a list of {@link SecurityEvent},
12638      * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
12639      * @throws SecurityException if {@code admin} is not allowed to access security logging,
12640      * or there is at least one profile or secondary user that is not affiliated with the device.
12641      * @see #isAffiliatedUser
12642      * @see DeviceAdminReceiver#onSecurityLogsAvailable
12643      */
12644     @SuppressLint("NullableCollection")
retrieveSecurityLogs(@onNull ComponentName admin)12645     public @Nullable List<SecurityEvent> retrieveSecurityLogs(@NonNull ComponentName admin) {
12646         throwIfParentInstance("retrieveSecurityLogs");
12647         try {
12648             ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(
12649                     admin, mContext.getPackageName());
12650             if (list != null) {
12651                 return list.getList();
12652             } else {
12653                 // Rate limit exceeded.
12654                 return null;
12655             }
12656         } catch (RemoteException re) {
12657             throw re.rethrowFromSystemServer();
12658         }
12659     }
12660 
12661     /**
12662      * Makes all accumulated network logs available to DPC in a new batch.
12663      * If throttled, returns time to wait in milliseconds, otherwise 0.
12664      * @hide
12665      */
12666     @TestApi
12667     @RequiresPermission(android.Manifest.permission.FORCE_DEVICE_POLICY_MANAGER_LOGS)
forceNetworkLogs()12668     public long forceNetworkLogs() {
12669         if (mService == null) {
12670             return -1;
12671         }
12672         try {
12673             return mService.forceNetworkLogs();
12674         } catch (RemoteException re) {
12675             throw re.rethrowFromSystemServer();
12676         }
12677     }
12678 
12679     /**
12680      * Forces a batch of security logs to be fetched from logd and makes it available for DPC.
12681      * If throttled, returns time to wait in milliseconds, otherwise 0.
12682      * @hide
12683      */
12684     @TestApi
12685     @RequiresPermission(android.Manifest.permission.FORCE_DEVICE_POLICY_MANAGER_LOGS)
forceSecurityLogs()12686     public long forceSecurityLogs() {
12687         if (mService == null) {
12688             return 0;
12689         }
12690         try {
12691             return mService.forceSecurityLogs();
12692         } catch (RemoteException re) {
12693             throw re.rethrowFromSystemServer();
12694         }
12695     }
12696 
12697     /**
12698      * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
12699      * profile.
12700      *
12701      * @hide
12702      */
getParentProfileInstance(UserInfo uInfo)12703     public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
12704         mContext.checkSelfPermission(
12705                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
12706         if (!uInfo.isManagedProfile()) {
12707             throw new SecurityException("The user " + uInfo.id
12708                     + " does not have a parent profile.");
12709         }
12710         return new DevicePolicyManager(mContext, mService, true);
12711     }
12712 
12713     /**
12714      * Called by a device or profile owner to restrict packages from using metered data.
12715      *
12716      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12717      * @param packageNames the list of package names to be restricted.
12718      * @return a list of package names which could not be restricted.
12719      * @throws SecurityException if {@code admin} is not a device or profile owner.
12720      */
setMeteredDataDisabledPackages(@onNull ComponentName admin, @NonNull List<String> packageNames)12721     public @NonNull List<String> setMeteredDataDisabledPackages(@NonNull ComponentName admin,
12722             @NonNull List<String> packageNames) {
12723         throwIfParentInstance("setMeteredDataDisabled");
12724         if (mService != null) {
12725             try {
12726                 return mService.setMeteredDataDisabledPackages(admin, packageNames);
12727             } catch (RemoteException re) {
12728                 throw re.rethrowFromSystemServer();
12729             }
12730         }
12731         return packageNames;
12732     }
12733 
12734     /**
12735      * Called by a device or profile owner to retrieve the list of packages which are restricted
12736      * by the admin from using metered data.
12737      *
12738      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12739      * @return the list of restricted package names.
12740      * @throws SecurityException if {@code admin} is not a device or profile owner.
12741      */
getMeteredDataDisabledPackages(@onNull ComponentName admin)12742     public @NonNull List<String> getMeteredDataDisabledPackages(@NonNull ComponentName admin) {
12743         throwIfParentInstance("getMeteredDataDisabled");
12744         if (mService != null) {
12745             try {
12746                 return mService.getMeteredDataDisabledPackages(admin);
12747             } catch (RemoteException re) {
12748                 throw re.rethrowFromSystemServer();
12749             }
12750         }
12751         return new ArrayList<>();
12752     }
12753 
12754     /**
12755      * Called by the system to check if a package is restricted from using metered data
12756      * by {@param admin}.
12757      *
12758      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12759      * @param packageName the package whose restricted status is needed.
12760      * @param userId the user to which {@param packageName} belongs.
12761      * @return {@code true} if the package is restricted by admin, otherwise {@code false}
12762      * @throws SecurityException if the caller doesn't run with {@link Process#SYSTEM_UID}
12763      * @hide
12764      */
isMeteredDataDisabledPackageForUser(@onNull ComponentName admin, String packageName, @UserIdInt int userId)12765     public boolean isMeteredDataDisabledPackageForUser(@NonNull ComponentName admin,
12766             String packageName, @UserIdInt int userId) {
12767         throwIfParentInstance("getMeteredDataDisabledForUser");
12768         if (mService != null) {
12769             try {
12770                 return mService.isMeteredDataDisabledPackageForUser(admin, packageName, userId);
12771             } catch (RemoteException re) {
12772                 throw re.rethrowFromSystemServer();
12773             }
12774         }
12775         return false;
12776     }
12777 
12778     /**
12779      * Called by device owner or profile owner of an organization-owned managed profile to retrieve
12780      * device logs from before the device's last reboot.
12781      * <p>
12782      * <strong> This API is not supported on all devices. Calling this API on unsupported devices
12783      * will result in {@code null} being returned. The device logs are retrieved from a RAM region
12784      * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
12785      * about data corruption when parsing. </strong>
12786      *
12787      * <p> When called by a device owner, if there is any other user or profile on the device,
12788      * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown.
12789      * See {@link #isAffiliatedUser}.
12790      *
12791      * @param admin Which device admin this request is associated with.
12792      * @return Device logs from before the latest reboot of the system, or {@code null} if this API
12793      *         is not supported on the device.
12794      * @throws SecurityException if {@code admin} is not allowed to access security logging, or
12795      * there is at least one profile or secondary user that is not affiliated with the device.
12796      * @see #isAffiliatedUser
12797      * @see #retrieveSecurityLogs
12798      */
12799     @SuppressLint("NullableCollection")
retrievePreRebootSecurityLogs( @onNull ComponentName admin)12800     public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
12801             @NonNull ComponentName admin) {
12802         throwIfParentInstance("retrievePreRebootSecurityLogs");
12803         try {
12804             ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(
12805                     admin, mContext.getPackageName());
12806             if (list != null) {
12807                 return list.getList();
12808             } else {
12809                 return null;
12810             }
12811         } catch (RemoteException re) {
12812             throw re.rethrowFromSystemServer();
12813         }
12814     }
12815 
12816     /**
12817      * Called by a profile owner of a managed profile to set the color used for customization. This
12818      * color is used as background color of the confirm credentials screen for that user. The
12819      * default color is teal (#00796B).
12820      * <p>
12821      * The confirm credentials screen can be created using
12822      * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
12823      * <p>
12824      * Starting from Android R, the organization color will no longer be used as the background
12825      * color of the confirm credentials screen.
12826      *
12827      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12828      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
12829      * @throws SecurityException if {@code admin} is not a profile owner.
12830      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
12831      * used as the background color of the confirm credentials screen.
12832      */
12833     @Deprecated
setOrganizationColor(@onNull ComponentName admin, int color)12834     public void setOrganizationColor(@NonNull ComponentName admin, int color) {
12835         throwIfParentInstance("setOrganizationColor");
12836         try {
12837             // always enforce alpha channel to have 100% opacity
12838             color |= 0xFF000000;
12839             mService.setOrganizationColor(admin, color);
12840         } catch (RemoteException re) {
12841             throw re.rethrowFromSystemServer();
12842         }
12843     }
12844 
12845     /**
12846      * @hide
12847      *
12848      * Sets the color used for customization.
12849      *
12850      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
12851      * @param userId which user to set the color to.
12852      * @RequiresPermission(allOf = {
12853      *       Manifest.permission.MANAGE_USERS,
12854      *       Manifest.permission.INTERACT_ACROSS_USERS_FULL})
12855      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
12856      * used as the background color of the confirm credentials screen.
12857      */
12858     @Deprecated
setOrganizationColorForUser(@olorInt int color, @UserIdInt int userId)12859     public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
12860         try {
12861             // always enforce alpha channel to have 100% opacity
12862             color |= 0xFF000000;
12863             mService.setOrganizationColorForUser(color, userId);
12864         } catch (RemoteException re) {
12865             throw re.rethrowFromSystemServer();
12866         }
12867     }
12868 
12869     /**
12870      * Called by a profile owner of a managed profile to retrieve the color used for customization.
12871      * This color is used as background color of the confirm credentials screen for that user.
12872      *
12873      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12874      * @return The 24bit (0xRRGGBB) representation of the color to be used.
12875      * @throws SecurityException if {@code admin} is not a profile owner.
12876      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
12877      * used as the background color of the confirm credentials screen.
12878      */
12879     @Deprecated
getOrganizationColor(@onNull ComponentName admin)12880     public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
12881         throwIfParentInstance("getOrganizationColor");
12882         try {
12883             return mService.getOrganizationColor(admin);
12884         } catch (RemoteException re) {
12885             throw re.rethrowFromSystemServer();
12886         }
12887     }
12888 
12889     /**
12890      * @hide
12891      * Retrieve the customization color for a given user.
12892      *
12893      * @param userHandle The user id of the user we're interested in.
12894      * @return The 24bit (0xRRGGBB) representation of the color to be used.
12895      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
12896      * used as the background color of the confirm credentials screen.
12897      */
12898     @Deprecated
getOrganizationColorForUser(int userHandle)12899     public @ColorInt int getOrganizationColorForUser(int userHandle) {
12900         try {
12901             return mService.getOrganizationColorForUser(userHandle);
12902         } catch (RemoteException re) {
12903             throw re.rethrowFromSystemServer();
12904         }
12905     }
12906 
12907     /**
12908      * Called by the device owner (since API 26) or profile owner (since API 24) to set the name of
12909      * the organization under management.
12910      *
12911      * <p>If the organization name needs to be localized, it is the responsibility of the {@link
12912      * DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast and set
12913      * a new version of this string accordingly.
12914      *
12915      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12916      * @param title The organization name or {@code null} to clear a previously set name.
12917      * @throws SecurityException if {@code admin} is not a device or profile owner.
12918      */
setOrganizationName(@onNull ComponentName admin, @Nullable CharSequence title)12919     public void setOrganizationName(@NonNull ComponentName admin, @Nullable CharSequence title) {
12920         throwIfParentInstance("setOrganizationName");
12921         try {
12922             mService.setOrganizationName(admin, title);
12923         } catch (RemoteException re) {
12924             throw re.rethrowFromSystemServer();
12925         }
12926     }
12927 
12928     /**
12929      * Called by a profile owner of a managed profile to retrieve the name of the organization under
12930      * management.
12931      *
12932      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12933      * @return The organization name or {@code null} if none is set.
12934      * @throws SecurityException if {@code admin} is not a profile owner.
12935      */
getOrganizationName(@onNull ComponentName admin)12936     public @Nullable CharSequence getOrganizationName(@NonNull ComponentName admin) {
12937         throwIfParentInstance("getOrganizationName");
12938         try {
12939             return mService.getOrganizationName(admin);
12940         } catch (RemoteException re) {
12941             throw re.rethrowFromSystemServer();
12942         }
12943     }
12944 
12945     private final IpcDataCache<Void, CharSequence> mGetDeviceOwnerOrganizationNameCache =
12946             new IpcDataCache(sDpmCaches.child("getDeviceOwnerOrganizationName"),
12947                     (query) -> getService().getDeviceOwnerOrganizationName());
12948 
12949     /**
12950      * Called by the system to retrieve the name of the organization managing the device.
12951      *
12952      * @return The organization name or {@code null} if none is set.
12953      * @throws SecurityException if the caller is not the device owner, does not hold the
12954      *         MANAGE_USERS permission and is not the system.
12955      *
12956      * @hide
12957      */
12958     @SystemApi
12959     @SuppressLint("RequiresPermission")
getDeviceOwnerOrganizationName()12960     public @Nullable CharSequence getDeviceOwnerOrganizationName() {
12961         return mGetDeviceOwnerOrganizationNameCache.query(null);
12962     }
12963 
12964     private final IpcDataCache<Integer, CharSequence> mGetOrganizationNameForUserCache =
12965             new IpcDataCache<>(sDpmCaches.child("getOrganizationNameForUser"),
12966                     (query) -> getService().getOrganizationNameForUser(query));
12967 
12968     /**
12969      * Retrieve the default title message used in the confirm credentials screen for a given user.
12970      *
12971      * @param userHandle The user id of the user we're interested in.
12972      * @return The organization name or {@code null} if none is set.
12973      *
12974      * @hide
12975      */
getOrganizationNameForUser(int userHandle)12976     public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
12977         return mGetOrganizationNameForUserCache.query(userHandle);
12978     }
12979 
12980     /**
12981      * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
12982      *         return {@link #STATE_USER_UNMANAGED}
12983      * @hide
12984      */
12985     @SystemApi
12986     @RequiresPermission(anyOf = {
12987             android.Manifest.permission.MANAGE_USERS,
12988             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
12989     })
12990     @UserProvisioningState
getUserProvisioningState()12991     public int getUserProvisioningState() {
12992         throwIfParentInstance("getUserProvisioningState");
12993         if (mService != null) {
12994             try {
12995                 return mService.getUserProvisioningState();
12996             } catch (RemoteException e) {
12997                 throw e.rethrowFromSystemServer();
12998             }
12999         }
13000         return STATE_USER_UNMANAGED;
13001     }
13002 
13003     /**
13004      * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
13005      *
13006      * @param state to store
13007      * @param userHandle for user
13008      *
13009      * @hide
13010      */
13011     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setUserProvisioningState(@serProvisioningState int state, int userHandle)13012     public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
13013         if (mService != null) {
13014             try {
13015                 mService.setUserProvisioningState(state, userHandle);
13016             } catch (RemoteException e) {
13017                 throw e.rethrowFromSystemServer();
13018             }
13019         }
13020     }
13021 
13022     /**
13023      * Set the {@link UserProvisioningState} for the supplied user. The supplied user has to be
13024      * manged, otherwise it will throw an {@link IllegalStateException}.
13025      *
13026      * <p> For managed users/profiles/devices, only the following state changes are allowed:
13027      * <ul>
13028      *     <li>{@link #STATE_USER_UNMANAGED} can change to any other state except itself
13029      *     <li>{@link #STATE_USER_SETUP_INCOMPLETE} and {@link #STATE_USER_SETUP_COMPLETE} can only
13030      *     change to {@link #STATE_USER_SETUP_FINALIZED}</li>
13031      *     <li>{@link #STATE_USER_PROFILE_COMPLETE} can only change to
13032      *     {@link #STATE_USER_PROFILE_FINALIZED}</li>
13033      *     <li>{@link #STATE_USER_SETUP_FINALIZED} can't be changed to any other state</li>
13034      *     <li>{@link #STATE_USER_PROFILE_FINALIZED} can only change to
13035      *     {@link #STATE_USER_UNMANAGED}</li>
13036      * </ul>
13037      * @param state to store
13038      * @param userHandle for user
13039      * @throws IllegalStateException if called with an invalid state change.
13040      *
13041      * @hide
13042      */
13043     @SystemApi
13044     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setUserProvisioningState( @serProvisioningState int state, @NonNull UserHandle userHandle)13045     public void setUserProvisioningState(
13046             @UserProvisioningState int state, @NonNull UserHandle userHandle) {
13047         setUserProvisioningState(state, userHandle.getIdentifier());
13048     }
13049 
13050     /**
13051      * Indicates the entity that controls the device. Two users are
13052      * affiliated if the set of ids set by the device owner and the admin of the secondary user.
13053      *
13054      * <p>A user that is affiliated with the device owner user is considered to be
13055      * affiliated with the device.
13056      *
13057      * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
13058      * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user
13059      * is created, until it becomes affiliated. Therefore it is recommended that the appropriate
13060      * affiliation ids are set by its owner as soon as possible after the user is
13061      * created.
13062      * <p>
13063      * Note: This method used to be available for affiliating device owner and profile
13064      * owner. However, since Android 11, this combination is not possible. This method is now
13065      * only useful for affiliating the primary user with managed secondary users.
13066      *
13067      * @param admin Which device owner, or owner of secondary user, this request is associated with.
13068      * @param ids A set of opaque non-empty affiliation ids.
13069      *
13070      * @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
13071      * @see #isAffiliatedUser
13072      */
setAffiliationIds(@onNull ComponentName admin, @NonNull Set<String> ids)13073     public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) {
13074         throwIfParentInstance("setAffiliationIds");
13075         if (ids == null) {
13076             throw new IllegalArgumentException("ids must not be null");
13077         }
13078         try {
13079             mService.setAffiliationIds(admin, new ArrayList<>(ids));
13080         } catch (RemoteException e) {
13081             throw e.rethrowFromSystemServer();
13082         }
13083     }
13084 
13085     /**
13086      * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
13087      * empty set if none have been set.
13088      */
getAffiliationIds(@onNull ComponentName admin)13089     public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
13090         throwIfParentInstance("getAffiliationIds");
13091         try {
13092             return new ArraySet<>(mService.getAffiliationIds(admin));
13093         } catch (RemoteException e) {
13094             throw e.rethrowFromSystemServer();
13095         }
13096     }
13097 
13098     /**
13099      * Returns whether this user is affiliated with the device.
13100      * <p>
13101      * By definition, the user that the device owner runs on is always affiliated with the device.
13102      * Any other user is considered affiliated with the device if the set specified by its
13103      * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
13104      * @see #setAffiliationIds
13105      */
isAffiliatedUser()13106     public boolean isAffiliatedUser() {
13107         throwIfParentInstance("isAffiliatedUser");
13108         try {
13109             return mService.isCallingUserAffiliated();
13110         } catch (RemoteException e) {
13111             throw e.rethrowFromSystemServer();
13112         }
13113     }
13114 
13115     /**
13116      * @hide
13117      * Returns whether target user is affiliated with the device.
13118      */
isAffiliatedUser(@serIdInt int userId)13119     public boolean isAffiliatedUser(@UserIdInt int userId) {
13120         try {
13121             return mService.isAffiliatedUser(userId);
13122         } catch (RemoteException e) {
13123             throw e.rethrowFromSystemServer();
13124         }
13125     }
13126 
13127     /**
13128      * @hide
13129      * Returns whether the uninstall for {@code packageName} for the current user is in queue
13130      * to be started
13131      * @param packageName the package to check for
13132      * @return whether the uninstall intent for {@code packageName} is pending
13133      */
isUninstallInQueue(String packageName)13134     public boolean isUninstallInQueue(String packageName) {
13135         try {
13136             return mService.isUninstallInQueue(packageName);
13137         } catch (RemoteException re) {
13138             throw re.rethrowFromSystemServer();
13139         }
13140     }
13141 
13142     /**
13143      * @hide
13144      * @param packageName the package containing active DAs to be uninstalled
13145      */
uninstallPackageWithActiveAdmins(String packageName)13146     public void uninstallPackageWithActiveAdmins(String packageName) {
13147         try {
13148             mService.uninstallPackageWithActiveAdmins(packageName);
13149         } catch (RemoteException re) {
13150             throw re.rethrowFromSystemServer();
13151         }
13152     }
13153 
13154     /**
13155      * @hide
13156      * Remove a test admin synchronously without sending it a broadcast about being removed.
13157      * If the admin is a profile owner or device owner it will still be removed.
13158      *
13159      * @param userHandle user id to remove the admin for.
13160      * @param admin The administration compononent to remove.
13161      * @throws SecurityException if the caller is not shell / root or the admin package
13162      *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
13163      */
13164     @TestApi
13165     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
forceRemoveActiveAdmin( @onNull ComponentName adminReceiver, @UserIdInt int userHandle)13166     public void forceRemoveActiveAdmin(
13167             @NonNull ComponentName adminReceiver, @UserIdInt int userHandle) {
13168         try {
13169             mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
13170         } catch (RemoteException re) {
13171             throw re.rethrowFromSystemServer();
13172         }
13173     }
13174 
13175     /**
13176      * Returns whether the device has been provisioned.
13177      *
13178      * <p>Not for use by third-party applications.
13179      *
13180      * @hide
13181      */
13182     @SystemApi
13183     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioned()13184     public boolean isDeviceProvisioned() {
13185         try {
13186             return mService.isDeviceProvisioned();
13187         } catch (RemoteException re) {
13188             throw re.rethrowFromSystemServer();
13189         }
13190     }
13191 
13192     /**
13193       * Writes that the provisioning configuration has been applied.
13194       *
13195       * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
13196       * permission.
13197       *
13198       * <p>Not for use by third-party applications.
13199       *
13200       * @hide
13201       */
13202     @SystemApi
13203     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
setDeviceProvisioningConfigApplied()13204     public void setDeviceProvisioningConfigApplied() {
13205         try {
13206             mService.setDeviceProvisioningConfigApplied();
13207         } catch (RemoteException re) {
13208             throw re.rethrowFromSystemServer();
13209         }
13210     }
13211 
13212     /**
13213      * Returns whether the provisioning configuration has been applied.
13214      *
13215      * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
13216      *
13217      * <p>Not for use by third-party applications.
13218      *
13219      * @return whether the provisioning configuration has been applied.
13220      *
13221      * @hide
13222      */
13223     @SystemApi
13224     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioningConfigApplied()13225     public boolean isDeviceProvisioningConfigApplied() {
13226         try {
13227             return mService.isDeviceProvisioningConfigApplied();
13228         } catch (RemoteException re) {
13229             throw re.rethrowFromSystemServer();
13230         }
13231     }
13232 
13233     /**
13234      * @hide
13235      * Force update user setup completed status for the given {@code userId}.
13236      * @throws {@link SecurityException} if the caller has no
13237      *         {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS}.
13238      */
13239     @TestApi
forceUpdateUserSetupComplete(@serIdInt int userId)13240     public void forceUpdateUserSetupComplete(@UserIdInt int userId) {
13241         try {
13242             mService.forceUpdateUserSetupComplete(userId);
13243         } catch (RemoteException re) {
13244             throw re.rethrowFromSystemServer();
13245         }
13246     }
13247 
13248     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
throwIfParentInstance(String functionName)13249     private void throwIfParentInstance(String functionName) {
13250         if (mParentInstance) {
13251             throw new SecurityException(functionName + " cannot be called on the parent instance");
13252         }
13253     }
13254 
13255     /**
13256      * Allows the device owner or profile owner to enable or disable the backup service.
13257      *
13258      * <p> Each user has its own backup service which manages the backup and restore mechanisms in
13259      * that user. Disabling the backup service will prevent data from being backed up or restored.
13260      *
13261      * <p> Device owner calls this API to control backup services across all users on the device.
13262      * Profile owner can use this API to enable or disable the profile's backup service. However,
13263      * for a managed profile its backup functionality is only enabled if both the device owner
13264      * and the profile owner have enabled the backup service.
13265      *
13266      * <p> By default, backup service is disabled on a device with device owner, and within a
13267      * managed profile.
13268      *
13269      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13270      * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
13271      * @throws SecurityException if {@code admin} is not a device owner or a profile owner.
13272      */
setBackupServiceEnabled(@onNull ComponentName admin, boolean enabled)13273     public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
13274         throwIfParentInstance("setBackupServiceEnabled");
13275         try {
13276             mService.setBackupServiceEnabled(admin, enabled);
13277         } catch (RemoteException re) {
13278             throw re.rethrowFromSystemServer();
13279         }
13280     }
13281 
13282     /**
13283      * Return whether the backup service is enabled by the device owner or profile owner for the
13284      * current user, as previously set by {@link #setBackupServiceEnabled(ComponentName, boolean)}.
13285      *
13286      * <p> Whether the backup functionality is actually enabled or not depends on settings from both
13287      * the current user and the device owner, please see
13288      * {@link #setBackupServiceEnabled(ComponentName, boolean)} for details.
13289      *
13290      * <p> Backup service manages all backup and restore mechanisms on the device.
13291      *
13292      * @return {@code true} if backup service is enabled, {@code false} otherwise.
13293      * @see #setBackupServiceEnabled
13294      */
isBackupServiceEnabled(@onNull ComponentName admin)13295     public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
13296         throwIfParentInstance("isBackupServiceEnabled");
13297         try {
13298             return mService.isBackupServiceEnabled(admin);
13299         } catch (RemoteException re) {
13300             throw re.rethrowFromSystemServer();
13301         }
13302     }
13303 
13304     /**
13305      * Called by a device owner, profile owner of a managed profile or delegated app with
13306      * {@link #DELEGATION_NETWORK_LOGGING} to control the network logging feature.
13307      *
13308      * <p> Supported for a device owner from Android 8 and a delegated app granted by a device
13309      * owner from Android 10. Supported for a profile owner of a managed profile and a delegated
13310      * app granted by a profile owner from Android 12. When network logging is enabled by a
13311      * profile owner, the network logs will only include work profile network activity, not
13312      * activity on the personal profile.
13313      *
13314      * <p> Network logs contain DNS lookup and connect() library call events. The following library
13315      *     functions are recorded while network logging is active:
13316      *     <ul>
13317      *       <li>{@code getaddrinfo()}</li>
13318      *       <li>{@code gethostbyname()}</li>
13319      *       <li>{@code connect()}</li>
13320      *     </ul>
13321      *
13322      * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
13323      *     full system call logging; event reporting is enabled by default for all processes but not
13324      *     strongly enforced.
13325      *     Events from applications using alternative implementations of libc, making direct kernel
13326      *     calls, or deliberately obfuscating traffic may not be recorded.
13327      *
13328      * <p> Some common network events may not be reported. For example:
13329      *     <ul>
13330      *       <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
13331      *           an alternative system for name resolution, and so avoid calling
13332      *           {@code getaddrinfo()} or {@code gethostbyname}.</li>
13333      *       <li>Applications may use datagram sockets for performance reasons, for example
13334      *           for a game client. Calling {@code connect()} is unnecessary for this kind of
13335      *           socket, so it will not trigger a network event.</li>
13336      *     </ul>
13337      *
13338      * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
13339      *     always-on VPN service.
13340      *     See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
13341      *     and {@link android.net.VpnService} for details.
13342      *
13343      * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
13344      * are unaffiliated secondary users or profiles on the device, regardless of whether the
13345      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
13346      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
13347      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
13348      *
13349      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
13350      *        {@code null} if called by a delegated app.
13351      * @param enabled whether network logging should be enabled or not.
13352      * @throws SecurityException if {@code admin} is not a device owner or profile owner.
13353      * @see #setAffiliationIds
13354      * @see #retrieveNetworkLogs
13355      */
setNetworkLoggingEnabled(@ullable ComponentName admin, boolean enabled)13356     public void setNetworkLoggingEnabled(@Nullable ComponentName admin, boolean enabled) {
13357         throwIfParentInstance("setNetworkLoggingEnabled");
13358         try {
13359             mService.setNetworkLoggingEnabled(admin, mContext.getPackageName(), enabled);
13360         } catch (RemoteException re) {
13361             throw re.rethrowFromSystemServer();
13362         }
13363     }
13364 
13365     private IpcDataCache<ComponentName, Boolean> mIsNetworkLoggingEnabledCache =
13366             new IpcDataCache<>(sDpmCaches.child("isNetworkLoggingEnabled"),
13367                     (admin) -> getService().isNetworkLoggingEnabled(admin,
13368                             getContext().getPackageName()));
13369 
13370     /**
13371      * Return whether network logging is enabled by a device owner or profile owner of
13372      * a managed profile.
13373      *
13374      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
13375      * be {@code null} if the caller is a delegated app with {@link #DELEGATION_NETWORK_LOGGING}
13376      * or has MANAGE_USERS permission.
13377      * @return {@code true} if network logging is enabled by device owner or profile owner,
13378      * {@code false} otherwise.
13379      * @throws SecurityException if {@code admin} is not a device owner or profile owner and
13380      * caller has no MANAGE_USERS permission
13381      */
isNetworkLoggingEnabled(@ullable ComponentName admin)13382     public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
13383         throwIfParentInstance("isNetworkLoggingEnabled");
13384         return mIsNetworkLoggingEnabledCache.query(admin);
13385     }
13386 
13387     /**
13388      * Called by device owner, profile owner of a managed profile or delegated app with
13389      * {@link #DELEGATION_NETWORK_LOGGING} to retrieve the most recent batch of
13390      * network logging events.
13391      *
13392      * <p> When network logging is enabled by a profile owner, the network logs will only include
13393      * work profile network activity, not activity on the personal profile.
13394      *
13395      * A device owner or profile owner has to provide a batchToken provided as part of
13396      * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
13397      * token of the most recent available batch of logs, {@code null} will be returned.
13398      *
13399      * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
13400      *
13401      * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
13402      *
13403      * <p> Access to the logs is rate limited and this method will only return a new batch of logs
13404      * after the device device owner has been notified via
13405      * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
13406      *
13407      * <p>If the caller is not a profile owner and a secondary user or profile is created, calling
13408      * this method will throw a {@link SecurityException} until all users become affiliated again.
13409      * It will also no longer be possible to retrieve the network logs batch with the most recent
13410      * batchToken provided by {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
13411      * See {@link DevicePolicyManager#setAffiliationIds}.
13412      *
13413      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
13414      *        {@code null} if called by a delegated app.
13415      * @param batchToken A token of the batch to retrieve
13416      * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
13417      *        {@code null} if the batch represented by batchToken is no longer available or if
13418      *        logging is disabled.
13419      * @throws SecurityException if {@code admin} is not a device owner, profile owner or if the
13420      * {@code admin} is not a profile owner and there is at least one profile or secondary user
13421      * that is not affiliated with the device.
13422      * @see #setAffiliationIds
13423      * @see DeviceAdminReceiver#onNetworkLogsAvailable
13424      */
retrieveNetworkLogs(@ullable ComponentName admin, long batchToken)13425     public @Nullable List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin,
13426             long batchToken) {
13427         throwIfParentInstance("retrieveNetworkLogs");
13428         try {
13429             return mService.retrieveNetworkLogs(admin, mContext.getPackageName(), batchToken);
13430         } catch (RemoteException re) {
13431             throw re.rethrowFromSystemServer();
13432         }
13433     }
13434 
13435     /**
13436      * Called by a device owner to bind to a service from a secondary managed user or vice versa.
13437      * See {@link #getBindDeviceAdminTargetUsers} for the pre-requirements of a
13438      * device owner to bind to services of another managed user.
13439      * <p>
13440      * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
13441      * Note that the {@link Context} used to obtain this
13442      * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
13443      * to bind to the {@link android.app.Service}.
13444      * <p>
13445      * Note: This method used to be available for communication between device owner and profile
13446      * owner. However, since Android 11, this combination is not possible. This method is now
13447      * only useful for communication between device owner and managed secondary users.
13448      *
13449      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13450      * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
13451      *        explicit component name or a package name to match an
13452      *        {@link IntentFilter} published by a service.
13453      * @param conn Receives information as the service is started and stopped in main thread. This
13454      *        must be a valid {@link ServiceConnection} object; it must not be {@code null}.
13455      * @param flags Operation options for the binding operation. See
13456      *        {@link Context#bindService(Intent, ServiceConnection, int)}.
13457      * @param targetUser Which user to bind to. Must be one of the users returned by
13458      *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
13459      *        be thrown.
13460      * @return If you have successfully bound to the service, {@code true} is returned;
13461      *         {@code false} is returned if the connection is not made and you will not
13462      *         receive the service object.
13463      *
13464      * @see Context#bindService(Intent, ServiceConnection, int)
13465      * @see #getBindDeviceAdminTargetUsers(ComponentName)
13466      */
bindDeviceAdminServiceAsUser( @onNull ComponentName admin, Intent serviceIntent, @NonNull ServiceConnection conn, @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser)13467     public boolean bindDeviceAdminServiceAsUser(
13468             @NonNull ComponentName admin,  Intent serviceIntent, @NonNull ServiceConnection conn,
13469             @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser) {
13470         throwIfParentInstance("bindDeviceAdminServiceAsUser");
13471         // Keep this in sync with ContextImpl.bindServiceCommon.
13472         try {
13473             final IServiceConnection sd = mContext.getServiceDispatcher(
13474                     conn, mContext.getMainThreadHandler(), flags);
13475             serviceIntent.prepareToLeaveProcess(mContext);
13476             return mService.bindDeviceAdminServiceAsUser(admin,
13477                     mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
13478                     sd, flags, targetUser.getIdentifier());
13479         } catch (RemoteException re) {
13480             throw re.rethrowFromSystemServer();
13481         }
13482     }
13483 
13484     /**
13485      * Returns the list of target users that the calling device owner or owner of secondary user
13486      * can use when calling {@link #bindDeviceAdminServiceAsUser}.
13487      * <p>
13488      * A device owner can bind to a service from a secondary managed user and vice versa, provided
13489      * that both users are affiliated. See {@link #setAffiliationIds}.
13490      */
getBindDeviceAdminTargetUsers(@onNull ComponentName admin)13491     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
13492         throwIfParentInstance("getBindDeviceAdminTargetUsers");
13493         try {
13494             return mService.getBindDeviceAdminTargetUsers(admin);
13495         } catch (RemoteException re) {
13496             throw re.rethrowFromSystemServer();
13497         }
13498     }
13499 
13500     /**
13501      * Called by the system to get the time at which the device owner last retrieved security
13502      * logging entries.
13503      *
13504      * @return the time at which the device owner most recently retrieved security logging entries,
13505      *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
13506      * @throws SecurityException if the caller is not the device owner, does not hold the
13507      *         MANAGE_USERS permission and is not the system.
13508      *
13509      * @hide
13510      */
13511     @TestApi
getLastSecurityLogRetrievalTime()13512     public long getLastSecurityLogRetrievalTime() {
13513         try {
13514             return mService.getLastSecurityLogRetrievalTime();
13515         } catch (RemoteException re) {
13516             throw re.rethrowFromSystemServer();
13517         }
13518     }
13519 
13520     /**
13521      * Called by the system to get the time at which the device owner last requested a bug report.
13522      *
13523      * @return the time at which the device owner most recently requested a bug report, in
13524      *         milliseconds since epoch; -1 if a bug report was never requested.
13525      * @throws SecurityException if the caller is not the device owner, does not hold the
13526      *         MANAGE_USERS permission and is not the system.
13527      *
13528      * @hide
13529      */
13530     @TestApi
getLastBugReportRequestTime()13531     public long getLastBugReportRequestTime() {
13532         try {
13533             return mService.getLastBugReportRequestTime();
13534         } catch (RemoteException re) {
13535             throw re.rethrowFromSystemServer();
13536         }
13537     }
13538 
13539     /**
13540      * Called by the system to get the time at which the device owner or profile owner of a
13541      * managed profile last retrieved network logging events.
13542      *
13543      * @return the time at which the device owner or profile owner most recently retrieved network
13544      *         logging events, in milliseconds since epoch; -1 if network logging events were
13545      *         never retrieved.
13546      * @throws SecurityException if the caller is not the device owner, does not hold the
13547      *         MANAGE_USERS permission and is not the system.
13548      *
13549      * @hide
13550      */
13551     @TestApi
getLastNetworkLogRetrievalTime()13552     public long getLastNetworkLogRetrievalTime() {
13553         try {
13554             return mService.getLastNetworkLogRetrievalTime();
13555         } catch (RemoteException re) {
13556             throw re.rethrowFromSystemServer();
13557         }
13558     }
13559 
13560     /**
13561      * Called by the system to find out whether the current user's IME was set by the device/profile
13562      * owner or the user.
13563      *
13564      * @return {@code true} if the user's IME was set by the device or profile owner, {@code false}
13565      *         otherwise.
13566      * @throws SecurityException if the caller is not the device owner/profile owner.
13567      *
13568      * @hide
13569      */
13570     @TestApi
isCurrentInputMethodSetByOwner()13571     public boolean isCurrentInputMethodSetByOwner() {
13572         try {
13573             return mService.isCurrentInputMethodSetByOwner();
13574         } catch (RemoteException re) {
13575             throw re.rethrowFromSystemServer();
13576         }
13577     }
13578 
13579     /**
13580      * Called by the system to get a list of CA certificates that were installed by the device or
13581      * profile owner.
13582      *
13583      * <p> The caller must be the target user's device owner/profile Owner or hold the
13584      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
13585      *
13586      * @param user The user for whom to retrieve information.
13587      * @return list of aliases identifying CA certificates installed by the device or profile owner
13588      * @throws SecurityException if the caller does not have permission to retrieve information
13589      *         about the given user's CA certificates.
13590      *
13591      * @hide
13592      */
13593     @TestApi
getOwnerInstalledCaCerts(@onNull UserHandle user)13594     public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
13595         try {
13596             return mService.getOwnerInstalledCaCerts(user).getList();
13597         } catch (RemoteException re) {
13598             throw re.rethrowFromSystemServer();
13599         }
13600     }
13601 
13602     /**
13603      * Returns whether factory reset protection policy is supported on the device.
13604      *
13605      * @return {@code true} if the device support factory reset protection policy.
13606      *
13607      * @hide
13608      */
13609     @TestApi
isFactoryResetProtectionPolicySupported()13610     public boolean isFactoryResetProtectionPolicySupported() {
13611         try {
13612             return mService.isFactoryResetProtectionPolicySupported();
13613         } catch (RemoteException re) {
13614             throw re.rethrowFromSystemServer();
13615         }
13616     }
13617 
13618     /**
13619      * Called by the device owner or profile owner to clear application user data of a given
13620      * package. The behaviour of this is equivalent to the target application calling
13621      * {@link android.app.ActivityManager#clearApplicationUserData()}.
13622      *
13623      * <p><strong>Note:</strong> an application can store data outside of its application data, e.g.
13624      * external storage or user dictionary. This data will not be wiped by calling this API.
13625      *
13626      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13627      * @param packageName The name of the package which will have its user data wiped.
13628      * @param executor The executor through which the listener should be invoked.
13629      * @param listener A callback object that will inform the caller when the clearing is done.
13630      * @throws SecurityException if the caller is not the device owner/profile owner.
13631      */
clearApplicationUserData(@onNull ComponentName admin, @NonNull String packageName, @NonNull @CallbackExecutor Executor executor, @NonNull OnClearApplicationUserDataListener listener)13632     public void clearApplicationUserData(@NonNull ComponentName admin,
13633             @NonNull String packageName, @NonNull @CallbackExecutor Executor executor,
13634             @NonNull OnClearApplicationUserDataListener listener) {
13635         throwIfParentInstance("clearAppData");
13636         Objects.requireNonNull(executor);
13637         Objects.requireNonNull(listener);
13638         try {
13639             mService.clearApplicationUserData(admin, packageName,
13640                     new IPackageDataObserver.Stub() {
13641                         public void onRemoveCompleted(String pkg, boolean succeeded) {
13642                             executor.execute(() ->
13643                                     listener.onApplicationUserDataCleared(pkg, succeeded));
13644                         }
13645                     });
13646         } catch (RemoteException re) {
13647             throw re.rethrowFromSystemServer();
13648         }
13649     }
13650 
13651     /**
13652      * Called by a device owner to specify whether logout is enabled for all secondary users. The
13653      * system may show a logout button that stops the user and switches back to the primary user.
13654      *
13655      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13656      * @param enabled whether logout should be enabled or not.
13657      * @throws SecurityException if {@code admin} is not a device owner.
13658      */
setLogoutEnabled(@onNull ComponentName admin, boolean enabled)13659     public void setLogoutEnabled(@NonNull ComponentName admin, boolean enabled) {
13660         throwIfParentInstance("setLogoutEnabled");
13661         try {
13662             mService.setLogoutEnabled(admin, enabled);
13663         } catch (RemoteException re) {
13664             throw re.rethrowFromSystemServer();
13665         }
13666     }
13667 
13668     /**
13669      * Returns whether logout is enabled by a device owner.
13670      *
13671      * @return {@code true} if logout is enabled by device owner, {@code false} otherwise.
13672      */
isLogoutEnabled()13673     public boolean isLogoutEnabled() {
13674         throwIfParentInstance("isLogoutEnabled");
13675         try {
13676             return mService.isLogoutEnabled();
13677         } catch (RemoteException re) {
13678             throw re.rethrowFromSystemServer();
13679         }
13680     }
13681 
13682     /**
13683      * Callback used in {@link #clearApplicationUserData}
13684      * to indicate that the clearing of an application's user data is done.
13685      */
13686     public interface OnClearApplicationUserDataListener {
13687         /**
13688          * Method invoked when clearing the application user data has completed.
13689          *
13690          * @param packageName The name of the package which had its user data cleared.
13691          * @param succeeded Whether the clearing succeeded. Clearing fails for device administrator
13692          *                  apps and protected system packages.
13693          */
onApplicationUserDataCleared(String packageName, boolean succeeded)13694         void onApplicationUserDataCleared(String packageName, boolean succeeded);
13695     }
13696 
13697     /**
13698      * Returns set of system apps that should be removed during provisioning.
13699      *
13700      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13701      * @param userId ID of the user to be provisioned.
13702      * @param provisioningAction action indicating type of provisioning, should be one of
13703      * {@link #ACTION_PROVISION_MANAGED_DEVICE}, {@link #ACTION_PROVISION_MANAGED_PROFILE} or
13704      * {@link #ACTION_PROVISION_MANAGED_USER}.
13705      *
13706      * @hide
13707      */
13708     @TestApi
getDisallowedSystemApps(@onNull ComponentName admin, @UserIdInt int userId, @NonNull String provisioningAction)13709     public @NonNull Set<String> getDisallowedSystemApps(@NonNull ComponentName admin,
13710             @UserIdInt int userId, @NonNull String provisioningAction) {
13711         try {
13712             return new ArraySet<>(
13713                     mService.getDisallowedSystemApps(admin, userId, provisioningAction));
13714         } catch (RemoteException re) {
13715             throw re.rethrowFromSystemServer();
13716         }
13717     }
13718 
13719     /**
13720      * Changes the current administrator to another one. All policies from the current
13721      * administrator are migrated to the new administrator. The whole operation is atomic -
13722      * the transfer is either complete or not done at all.
13723      *
13724      * <p>Depending on the current administrator (device owner, profile owner), you have the
13725      * following expected behaviour:
13726      * <ul>
13727      *     <li>A device owner can only be transferred to a new device owner</li>
13728      *     <li>A profile owner can only be transferred to a new profile owner</li>
13729      * </ul>
13730      *
13731      * <p>Use the {@code bundle} parameter to pass data to the new administrator. The data
13732      * will be received in the
13733      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}
13734      * callback of the new administrator.
13735      *
13736      * <p>The transfer has failed if the original administrator is still the corresponding owner
13737      * after calling this method.
13738      *
13739      * <p>The incoming target administrator must have the
13740      * <code>&lt;support-transfer-ownership /&gt;</code> tag inside the
13741      * <code>&lt;device-admin&gt;&lt;/device-admin&gt;</code> tags in the xml file referenced by
13742      * {@link DeviceAdminReceiver#DEVICE_ADMIN_META_DATA}. Otherwise an
13743      * {@link IllegalArgumentException} will be thrown.
13744      *
13745      * @param admin which {@link DeviceAdminReceiver} this request is associated with
13746      * @param target which {@link DeviceAdminReceiver} we want the new administrator to be
13747      * @param bundle data to be sent to the new administrator
13748      * @throws SecurityException if {@code admin} is not a device owner nor a profile owner
13749      * @throws IllegalArgumentException if {@code admin} or {@code target} is {@code null}, they
13750      * are components in the same package or {@code target} is not an active admin
13751      */
transferOwnership(@onNull ComponentName admin, @NonNull ComponentName target, @Nullable PersistableBundle bundle)13752     public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
13753             @Nullable PersistableBundle bundle) {
13754         throwIfParentInstance("transferOwnership");
13755         try {
13756             mService.transferOwnership(admin, target, bundle);
13757         } catch (RemoteException re) {
13758             throw re.rethrowFromSystemServer();
13759         }
13760     }
13761 
13762     /**
13763      * Called by a device owner to specify the user session start message. This may be displayed
13764      * during a user switch.
13765      * <p>
13766      * The message should be limited to a short statement or it may be truncated.
13767      * <p>
13768      * If the message needs to be localized, it is the responsibility of the
13769      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
13770      * and set a new version of this message accordingly.
13771      *
13772      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
13773      * @param startUserSessionMessage message for starting user session, or {@code null} to use
13774      * system default message.
13775      * @throws SecurityException if {@code admin} is not a device owner.
13776      */
setStartUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence startUserSessionMessage)13777     public void setStartUserSessionMessage(
13778             @NonNull ComponentName admin, @Nullable CharSequence startUserSessionMessage) {
13779         throwIfParentInstance("setStartUserSessionMessage");
13780         try {
13781             mService.setStartUserSessionMessage(admin, startUserSessionMessage);
13782         } catch (RemoteException re) {
13783             throw re.rethrowFromSystemServer();
13784         }
13785     }
13786 
13787     /**
13788      * Called by a device owner to specify the user session end message. This may be displayed
13789      * during a user switch.
13790      * <p>
13791      * The message should be limited to a short statement or it may be truncated.
13792      * <p>
13793      * If the message needs to be localized, it is the responsibility of the
13794      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
13795      * and set a new version of this message accordingly.
13796      *
13797      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
13798      * @param endUserSessionMessage message for ending user session, or {@code null} to use system
13799      * default message.
13800      * @throws SecurityException if {@code admin} is not a device owner.
13801      */
setEndUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence endUserSessionMessage)13802     public void setEndUserSessionMessage(
13803             @NonNull ComponentName admin, @Nullable CharSequence endUserSessionMessage) {
13804         throwIfParentInstance("setEndUserSessionMessage");
13805         try {
13806             mService.setEndUserSessionMessage(admin, endUserSessionMessage);
13807         } catch (RemoteException re) {
13808             throw re.rethrowFromSystemServer();
13809         }
13810     }
13811 
13812     /**
13813      * Returns the user session start message.
13814      *
13815      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
13816      * @throws SecurityException if {@code admin} is not a device owner.
13817      */
getStartUserSessionMessage(@onNull ComponentName admin)13818     public CharSequence getStartUserSessionMessage(@NonNull ComponentName admin) {
13819         throwIfParentInstance("getStartUserSessionMessage");
13820         try {
13821             return mService.getStartUserSessionMessage(admin);
13822         } catch (RemoteException re) {
13823             throw re.rethrowFromSystemServer();
13824         }
13825     }
13826 
13827     /**
13828      * Returns the user session end message.
13829      *
13830      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
13831      * @throws SecurityException if {@code admin} is not a device owner.
13832      */
getEndUserSessionMessage(@onNull ComponentName admin)13833     public CharSequence getEndUserSessionMessage(@NonNull ComponentName admin) {
13834         throwIfParentInstance("getEndUserSessionMessage");
13835         try {
13836             return mService.getEndUserSessionMessage(admin);
13837         } catch (RemoteException re) {
13838             throw re.rethrowFromSystemServer();
13839         }
13840     }
13841 
13842     /**
13843      * Called by device owner or managed profile owner to add an override APN.
13844      *
13845      * <p>This method may returns {@code -1} if {@code apnSetting} conflicts with an existing
13846      * override APN. Update the existing conflicted APN with
13847      * {@link #updateOverrideApn(ComponentName, int, ApnSetting)} instead of adding a new entry.
13848      * <p>Two override APNs are considered to conflict when all the following APIs return
13849      * the same values on both override APNs:
13850      * <ul>
13851      *   <li>{@link ApnSetting#getOperatorNumeric()}</li>
13852      *   <li>{@link ApnSetting#getApnName()}</li>
13853      *   <li>{@link ApnSetting#getProxyAddressAsString()}</li>
13854      *   <li>{@link ApnSetting#getProxyPort()}</li>
13855      *   <li>{@link ApnSetting#getMmsProxyAddressAsString()}</li>
13856      *   <li>{@link ApnSetting#getMmsProxyPort()}</li>
13857      *   <li>{@link ApnSetting#getMmsc()}</li>
13858      *   <li>{@link ApnSetting#isEnabled()}</li>
13859      *   <li>{@link ApnSetting#getMvnoType()}</li>
13860      *   <li>{@link ApnSetting#getProtocol()}</li>
13861      *   <li>{@link ApnSetting#getRoamingProtocol()}</li>
13862      * </ul>
13863      *
13864      * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
13865      * Only device owners can add APNs.
13866      * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
13867      * Both device owners and managed profile owners can add enterprise APNs
13868      * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can add other type of APNs.
13869      * Enterprise APNs are specific to the managed profile and do not override any user-configured
13870      * VPNs. They are prerequisites for enabling preferential network service on the managed
13871      * profile on 4G networks ({@link #setPreferentialNetworkServiceConfigs}).
13872      *
13873      * @param admin which {@link DeviceAdminReceiver} this request is associated with
13874      * @param apnSetting the override APN to insert
13875      * @return The {@code id} of inserted override APN. Or {@code -1} when failed to insert into
13876      *         the database.
13877      * @throws SecurityException If request is for enterprise APN {@code admin} is either device
13878      * owner or profile owner and in all other types of APN if {@code admin} is not a device owner.
13879      *
13880      * @see #setOverrideApnsEnabled(ComponentName, boolean)
13881      */
addOverrideApn(@onNull ComponentName admin, @NonNull ApnSetting apnSetting)13882     public int addOverrideApn(@NonNull ComponentName admin, @NonNull ApnSetting apnSetting) {
13883         throwIfParentInstance("addOverrideApn");
13884         if (mService != null) {
13885             try {
13886                 return mService.addOverrideApn(admin, apnSetting);
13887             } catch (RemoteException e) {
13888                 throw e.rethrowFromSystemServer();
13889             }
13890         }
13891         return -1;
13892     }
13893 
13894     /**
13895      * Called by device owner or managed profile owner to update an override APN.
13896      *
13897      * <p>This method may returns {@code false} if there is no override APN with the given
13898      * {@code apnId}.
13899      * <p>This method may also returns {@code false} if {@code apnSetting} conflicts with an
13900      * existing override APN. Update the existing conflicted APN instead.
13901      * <p>See {@link #addOverrideApn} for the definition of conflict.
13902      * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
13903      * Only device owners can update APNs.
13904      * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
13905      * Both device owners and managed profile owners can update enterprise APNs
13906      * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can update other type of APNs.
13907      *
13908      * @param admin which {@link DeviceAdminReceiver} this request is associated with
13909      * @param apnId the {@code id} of the override APN to update
13910      * @param apnSetting the override APN to update
13911      * @return {@code true} if the required override APN is successfully updated,
13912      *         {@code false} otherwise.
13913      * @throws SecurityException If request is for enterprise APN {@code admin} is either device
13914      * owner or profile owner and in all other types of APN if {@code admin} is not a device owner.
13915      *
13916      * @see #setOverrideApnsEnabled(ComponentName, boolean)
13917      */
updateOverrideApn(@onNull ComponentName admin, int apnId, @NonNull ApnSetting apnSetting)13918     public boolean updateOverrideApn(@NonNull ComponentName admin, int apnId,
13919             @NonNull ApnSetting apnSetting) {
13920         throwIfParentInstance("updateOverrideApn");
13921         if (mService != null) {
13922             try {
13923                 return mService.updateOverrideApn(admin, apnId, apnSetting);
13924             } catch (RemoteException e) {
13925                 throw e.rethrowFromSystemServer();
13926             }
13927         }
13928         return false;
13929     }
13930 
13931     /**
13932      * Called by device owner or managed profile owner to remove an override APN.
13933      *
13934      * <p>This method may returns {@code false} if there is no override APN with the given
13935      * {@code apnId}.
13936      * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
13937      * Only device owners can remove APNs.
13938      * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
13939      * Both device owners and managed profile owners can remove enterprise APNs
13940      * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can remove other type of APNs.
13941      *
13942      * @param admin which {@link DeviceAdminReceiver} this request is associated with
13943      * @param apnId the {@code id} of the override APN to remove
13944      * @return {@code true} if the required override APN is successfully removed, {@code false}
13945      *         otherwise.
13946      * @throws SecurityException If request is for enterprise APN {@code admin} is either device
13947      * owner or profile owner and in all other types of APN if {@code admin} is not a device owner.
13948      *
13949      * @see #setOverrideApnsEnabled(ComponentName, boolean)
13950      */
removeOverrideApn(@onNull ComponentName admin, int apnId)13951     public boolean removeOverrideApn(@NonNull ComponentName admin, int apnId) {
13952         throwIfParentInstance("removeOverrideApn");
13953         if (mService != null) {
13954             try {
13955                 return mService.removeOverrideApn(admin, apnId);
13956             } catch (RemoteException e) {
13957                 throw e.rethrowFromSystemServer();
13958             }
13959         }
13960         return false;
13961     }
13962 
13963     /**
13964      * Called by device owner or managed profile owner to get all override APNs inserted by
13965      * device owner or managed profile owner previously using {@link #addOverrideApn}.
13966      *
13967      * @param admin which {@link DeviceAdminReceiver} this request is associated with
13968      * @return A list of override APNs inserted by device owner.
13969      * @throws SecurityException if {@code admin} is not a device owner.
13970      *
13971      * @see #setOverrideApnsEnabled(ComponentName, boolean)
13972      */
getOverrideApns(@onNull ComponentName admin)13973     public List<ApnSetting> getOverrideApns(@NonNull ComponentName admin) {
13974         throwIfParentInstance("getOverrideApns");
13975         if (mService != null) {
13976             try {
13977                 return mService.getOverrideApns(admin);
13978             } catch (RemoteException e) {
13979                 throw e.rethrowFromSystemServer();
13980             }
13981         }
13982         return Collections.emptyList();
13983     }
13984 
13985     /**
13986      * Called by device owner to set if override APNs should be enabled.
13987      * <p> Override APNs are separated from other APNs on the device, and can only be inserted or
13988      * modified by the device owner. When enabled, only override APNs are in use, any other APNs
13989      * are ignored.
13990      * <p>Note: Enterprise APNs added by managed profile owners do not need to be enabled by
13991      * this API. They are part of the preferential network service config and is controlled by
13992      * {@link #setPreferentialNetworkServiceConfigs}.
13993      *
13994      * @param admin which {@link DeviceAdminReceiver} this request is associated with
13995      * @param enabled {@code true} if override APNs should be enabled, {@code false} otherwise
13996      * @throws SecurityException if {@code admin} is not a device owner.
13997      */
setOverrideApnsEnabled(@onNull ComponentName admin, boolean enabled)13998     public void setOverrideApnsEnabled(@NonNull ComponentName admin, boolean enabled) {
13999         throwIfParentInstance("setOverrideApnEnabled");
14000         if (mService != null) {
14001             try {
14002                 mService.setOverrideApnsEnabled(admin, enabled);
14003             } catch (RemoteException e) {
14004                 throw e.rethrowFromSystemServer();
14005             }
14006         }
14007     }
14008 
14009     /**
14010      * Called by device owner to check if override APNs are currently enabled.
14011      *
14012      * @param admin which {@link DeviceAdminReceiver} this request is associated with
14013      * @return {@code true} if override APNs are currently enabled, {@code false} otherwise.
14014      * @throws SecurityException if {@code admin} is not a device owner.
14015      *
14016      * @see #setOverrideApnsEnabled(ComponentName, boolean)
14017      */
isOverrideApnEnabled(@onNull ComponentName admin)14018     public boolean isOverrideApnEnabled(@NonNull ComponentName admin) {
14019         throwIfParentInstance("isOverrideApnEnabled");
14020         if (mService != null) {
14021             try {
14022                 return mService.isOverrideApnEnabled(admin);
14023             } catch (RemoteException e) {
14024                 throw e.rethrowFromSystemServer();
14025             }
14026         }
14027         return false;
14028     }
14029 
14030     /**
14031      * Returns the data passed from the current administrator to the new administrator during an
14032      * ownership transfer. This is the same {@code bundle} passed in
14033      * {@link #transferOwnership(ComponentName, ComponentName, PersistableBundle)}. The bundle is
14034      * persisted until the profile owner or device owner is removed.
14035      *
14036      * <p>This is the same <code>bundle</code> received in the
14037      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}.
14038      * Use this method to retrieve it after the transfer as long as the new administrator is the
14039      * active device or profile owner.
14040      *
14041      * <p>Returns <code>null</code> if no ownership transfer was started for the calling user.
14042      *
14043      * @see #transferOwnership
14044      * @see DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)
14045      * @throws SecurityException if the caller is not a device or profile owner.
14046      */
14047     @Nullable
getTransferOwnershipBundle()14048     public PersistableBundle getTransferOwnershipBundle() {
14049         throwIfParentInstance("getTransferOwnershipBundle");
14050         try {
14051             return mService.getTransferOwnershipBundle();
14052         } catch (RemoteException re) {
14053             throw re.rethrowFromSystemServer();
14054         }
14055     }
14056 
14057     /**
14058      * Sets the global Private DNS mode to opportunistic.
14059      * May only be called by the device owner.
14060      *
14061      * <p>In this mode, the DNS subsystem will attempt a TLS handshake to the network-supplied
14062      * resolver prior to attempting name resolution in cleartext.
14063      *
14064      * <p>Note: The device owner won't be able to set the global private DNS mode if there are
14065      * unaffiliated secondary users or profiles on the device. It's recommended that affiliation
14066      * ids are set for new users as soon as possible after provisioning via
14067      * {@link #setAffiliationIds}.
14068      *
14069      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
14070      *
14071      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully, or
14072      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set.
14073      *
14074      * @throws SecurityException if the caller is not the device owner.
14075      */
setGlobalPrivateDnsModeOpportunistic( @onNull ComponentName admin)14076     public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeOpportunistic(
14077             @NonNull ComponentName admin) {
14078         throwIfParentInstance("setGlobalPrivateDnsModeOpportunistic");
14079 
14080         if (mService == null) {
14081             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
14082         }
14083 
14084         try {
14085             return mService.setGlobalPrivateDns(admin, PRIVATE_DNS_MODE_OPPORTUNISTIC, null);
14086         } catch (RemoteException re) {
14087             throw re.rethrowFromSystemServer();
14088         }
14089     }
14090 
14091     /**
14092      * Sets the global Private DNS host to be used.
14093      * May only be called by the device owner.
14094      *
14095      * <p>Note that the method is blocking as it will perform a connectivity check to the resolver,
14096      * to ensure it is valid. Because of that, the method should not be called on any thread that
14097      * relates to user interaction, such as the UI thread.
14098      *
14099      * <p>In case a VPN is used in conjunction with Private DNS resolver, the Private DNS resolver
14100      * must be reachable both from within and outside the VPN. Otherwise, the device may lose
14101      * the ability to resolve hostnames as system traffic to the resolver may not go through the
14102      * VPN.
14103      *
14104      * <p>Note: The device owner won't be able to set the global private DNS mode if there are
14105      * unaffiliated secondary users or profiles on the device. It's recommended that affiliation
14106      * ids are set for new users as soon as possible after provisioning via
14107      * {@link #setAffiliationIds}.
14108      *
14109      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
14110      * @param privateDnsHost The hostname of a server that implements DNS over TLS (RFC7858).
14111      *
14112      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully,
14113      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set or
14114      *         {@code PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING} if the specified host does not
14115      *         implement RFC7858.
14116      *
14117      * @throws IllegalArgumentException if the {@code privateDnsHost} is not a valid hostname.
14118      *
14119      * @throws SecurityException if the caller is not the device owner.
14120      */
setGlobalPrivateDnsModeSpecifiedHost( @onNull ComponentName admin, @NonNull String privateDnsHost)14121     @WorkerThread public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeSpecifiedHost(
14122             @NonNull ComponentName admin, @NonNull String privateDnsHost) {
14123         throwIfParentInstance("setGlobalPrivateDnsModeSpecifiedHost");
14124         Objects.requireNonNull(privateDnsHost, "dns resolver is null");
14125 
14126         if (mService == null) {
14127             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
14128         }
14129 
14130         if (NetworkUtilsInternal.isWeaklyValidatedHostname(privateDnsHost)) {
14131             if (!PrivateDnsConnectivityChecker.canConnectToPrivateDnsServer(privateDnsHost)) {
14132                 return PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING;
14133             }
14134         }
14135 
14136         try {
14137             return mService.setGlobalPrivateDns(
14138                     admin, PRIVATE_DNS_MODE_PROVIDER_HOSTNAME, privateDnsHost);
14139         } catch (RemoteException re) {
14140             throw re.rethrowFromSystemServer();
14141         }
14142     }
14143 
14144     /**
14145      * Called by device owner or profile owner of an organization-owned managed profile to install
14146      * a system update from the given file. The device will be
14147      * rebooted in order to finish installing the update. Note that if the device is rebooted, this
14148      * doesn't necessarily mean that the update has been applied successfully. The caller should
14149      * additionally check the system version with {@link android.os.Build#FINGERPRINT} or {@link
14150      * android.os.Build.VERSION}. If an error occurs during processing the OTA before the reboot,
14151      * the caller will be notified by {@link InstallSystemUpdateCallback}. If device does not have
14152      * sufficient battery level, the installation will fail with error {@link
14153      * InstallSystemUpdateCallback#UPDATE_ERROR_BATTERY_LOW}.
14154      *
14155      * @param admin The {@link DeviceAdminReceiver} that this request is associated with.
14156      * @param updateFilePath An Uri of the file that contains the update. The file should be
14157      * readable by the calling app.
14158      * @param executor The executor through which the callback should be invoked.
14159      * @param callback A callback object that will inform the caller when installing an update
14160      * fails.
14161      */
installSystemUpdate( @onNull ComponentName admin, @NonNull Uri updateFilePath, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)14162     public void installSystemUpdate(
14163             @NonNull ComponentName admin, @NonNull Uri updateFilePath,
14164             @NonNull @CallbackExecutor Executor executor,
14165             @NonNull InstallSystemUpdateCallback callback) {
14166         throwIfParentInstance("installUpdate");
14167         if (mService == null) {
14168             return;
14169         }
14170         try (ParcelFileDescriptor fileDescriptor = mContext.getContentResolver()
14171                     .openFileDescriptor(updateFilePath, "r")) {
14172             mService.installUpdateFromFile(
14173                     admin, fileDescriptor, new StartInstallingUpdateCallback.Stub() {
14174                         @Override
14175                         public void onStartInstallingUpdateError(
14176                                 int errorCode, String errorMessage) {
14177                             executeCallback(errorCode, errorMessage, executor, callback);
14178                         }
14179                     });
14180         } catch (RemoteException e) {
14181             throw e.rethrowFromSystemServer();
14182         } catch (FileNotFoundException e) {
14183             Log.w(TAG, e);
14184             executeCallback(
14185                     InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
14186                     Log.getStackTraceString(e),
14187                     executor, callback);
14188         } catch (IOException e) {
14189             Log.w(TAG, e);
14190             executeCallback(
14191                     InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN, Log.getStackTraceString(e),
14192                     executor, callback);
14193         }
14194     }
14195 
executeCallback(int errorCode, String errorMessage, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)14196     private void executeCallback(int errorCode, String errorMessage,
14197             @NonNull @CallbackExecutor Executor executor,
14198             @NonNull InstallSystemUpdateCallback callback) {
14199         executor.execute(() -> callback.onInstallUpdateError(errorCode, errorMessage));
14200     }
14201 
14202     /**
14203      * Returns the system-wide Private DNS mode.
14204      *
14205      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
14206      * @return one of {@code PRIVATE_DNS_MODE_OFF}, {@code PRIVATE_DNS_MODE_OPPORTUNISTIC},
14207      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} or {@code PRIVATE_DNS_MODE_UNKNOWN}.
14208      * @throws SecurityException if the caller is not the device owner.
14209      */
getGlobalPrivateDnsMode(@onNull ComponentName admin)14210     public int getGlobalPrivateDnsMode(@NonNull ComponentName admin) {
14211         throwIfParentInstance("setGlobalPrivateDns");
14212         if (mService == null) {
14213             return PRIVATE_DNS_MODE_UNKNOWN;
14214         }
14215 
14216         try {
14217             return mService.getGlobalPrivateDnsMode(admin);
14218         } catch (RemoteException re) {
14219             throw re.rethrowFromSystemServer();
14220         }
14221     }
14222 
14223     /**
14224      * Returns the system-wide Private DNS host.
14225      *
14226      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
14227      * @return The hostname used for Private DNS queries, null if none is set.
14228      * @throws SecurityException if the caller is not the device owner.
14229      */
getGlobalPrivateDnsHost(@onNull ComponentName admin)14230     public @Nullable String getGlobalPrivateDnsHost(@NonNull ComponentName admin) {
14231         throwIfParentInstance("setGlobalPrivateDns");
14232         if (mService == null) {
14233             return null;
14234         }
14235 
14236         try {
14237             return mService.getGlobalPrivateDnsHost(admin);
14238         } catch (RemoteException re) {
14239             throw re.rethrowFromSystemServer();
14240         }
14241     }
14242 
14243     /**
14244      * Deprecated. Use {@code markProfileOwnerOnOrganizationOwnedDevice} instead.
14245      * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#Q} or
14246      * below, will behave the same as {@link #setProfileOwnerOnOrganizationOwnedDevice}.
14247      *
14248      * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#R}
14249      * or above, will throw an UnsupportedOperationException when called.
14250      *
14251      * @deprecated Use {@link #setProfileOwnerOnOrganizationOwnedDevice} instead.
14252      *
14253      * @hide
14254      */
14255     @Deprecated
14256     @SystemApi
14257     @RequiresPermission(value = android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS,
14258             conditional = true)
setProfileOwnerCanAccessDeviceIds(@onNull ComponentName who)14259     public void setProfileOwnerCanAccessDeviceIds(@NonNull ComponentName who) {
14260         ApplicationInfo ai = mContext.getApplicationInfo();
14261         if (ai.targetSdkVersion > Build.VERSION_CODES.Q) {
14262             throw new UnsupportedOperationException(
14263                     "This method is deprecated. use markProfileOwnerOnOrganizationOwnedDevice"
14264                     + " instead.");
14265         } else {
14266             setProfileOwnerOnOrganizationOwnedDevice(who, true);
14267         }
14268     }
14269 
14270     /**
14271      * Sets whether the profile owner of the given user as managing an organization-owned device.
14272      * Managing an organization-owned device will give it access to device identifiers (such as
14273      * serial number, IMEI and MEID) as well as other privileges.
14274      *
14275      * @hide
14276      */
14277     @TestApi
14278     @RequiresPermission(anyOf = {
14279             android.Manifest.permission.MARK_DEVICE_ORGANIZATION_OWNED,
14280             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
14281             }, conditional = true)
setProfileOwnerOnOrganizationOwnedDevice(@onNull ComponentName who, boolean isProfileOwnerOnOrganizationOwnedDevice)14282     public void setProfileOwnerOnOrganizationOwnedDevice(@NonNull ComponentName who,
14283             boolean isProfileOwnerOnOrganizationOwnedDevice) {
14284         if (mService == null) {
14285             return;
14286         }
14287         try {
14288             mService.setProfileOwnerOnOrganizationOwnedDevice(who, myUserId(),
14289                     isProfileOwnerOnOrganizationOwnedDevice);
14290         } catch (RemoteException re) {
14291             throw re.rethrowFromSystemServer();
14292         }
14293     }
14294 
14295     /**
14296      * Allows a set of packages to access cross-profile calendar APIs.
14297      *
14298      * <p>Called by a profile owner of a managed profile.
14299      *
14300      * <p>Calling with a {@code null} value for the set disables the restriction so that all
14301      * packages are allowed to access cross-profile calendar APIs. Calling with an empty set
14302      * disallows all packages from accessing cross-profile calendar APIs. If this method isn't
14303      * called, no package is allowed to access cross-profile calendar APIs by default.
14304      *
14305      * @param admin which {@link DeviceAdminReceiver} this request is associated with
14306      * @param packageNames set of packages to be allowlisted
14307      * @throws SecurityException if {@code admin} is not a profile owner
14308      *
14309      * @see #getCrossProfileCalendarPackages(ComponentName)
14310      */
setCrossProfileCalendarPackages(@onNull ComponentName admin, @Nullable Set<String> packageNames)14311     public void setCrossProfileCalendarPackages(@NonNull ComponentName admin,
14312             @Nullable Set<String> packageNames) {
14313         throwIfParentInstance("setCrossProfileCalendarPackages");
14314         if (mService != null) {
14315             try {
14316                 mService.setCrossProfileCalendarPackages(admin, packageNames == null ? null
14317                         : new ArrayList<>(packageNames));
14318             } catch (RemoteException e) {
14319                 throw e.rethrowFromSystemServer();
14320             }
14321         }
14322     }
14323 
14324     /**
14325      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
14326      *
14327      * <p>Called by a profile owner of a managed profile.
14328      *
14329      * @param admin which {@link DeviceAdminReceiver} this request is associated with
14330      * @return the set of names of packages that were previously allowed via
14331      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
14332      * empty set if none have been allowed
14333      * @throws SecurityException if {@code admin} is not a profile owner
14334      *
14335      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
14336      */
getCrossProfileCalendarPackages(@onNull ComponentName admin)14337     public @Nullable Set<String> getCrossProfileCalendarPackages(@NonNull ComponentName admin) {
14338         throwIfParentInstance("getCrossProfileCalendarPackages");
14339         if (mService != null) {
14340             try {
14341                 final List<String> packageNames = mService.getCrossProfileCalendarPackages(admin);
14342                 return packageNames == null ? null : new ArraySet<>(packageNames);
14343             } catch (RemoteException e) {
14344                 throw e.rethrowFromSystemServer();
14345             }
14346         }
14347         return Collections.emptySet();
14348     }
14349 
14350     /**
14351      * Returns if a package is allowed to access cross-profile calendar APIs.
14352      *
14353      * <p>A package is allowed to access cross-profile calendar APIs if it's allowed by
14354      * admins via {@link #setCrossProfileCalendarPackages(ComponentName, Set)} and
14355      * {@link android.provider.Settings.Secure#CROSS_PROFILE_CALENDAR_ENABLED}
14356      * is turned on in the managed profile.
14357      *
14358      * <p>To query for a specific user, use
14359      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
14360      * that user, and get a {@link DevicePolicyManager} from this context.
14361      *
14362      * @param packageName the name of the package
14363      * @return {@code true} if the package is allowed to access cross-profile calendar APIs,
14364      * {@code false} otherwise
14365      *
14366      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
14367      * @see #getCrossProfileCalendarPackages(ComponentName)
14368      * @hide
14369      */
14370     @RequiresPermission(anyOf = {
14371             permission.INTERACT_ACROSS_USERS_FULL,
14372             permission.INTERACT_ACROSS_USERS
14373     }, conditional = true)
isPackageAllowedToAccessCalendar(@onNull String packageName)14374     public boolean isPackageAllowedToAccessCalendar(@NonNull  String packageName) {
14375         throwIfParentInstance("isPackageAllowedToAccessCalendar");
14376         if (mService != null) {
14377             try {
14378                 return mService.isPackageAllowedToAccessCalendarForUser(packageName,
14379                         myUserId());
14380             } catch (RemoteException e) {
14381                 throw e.rethrowFromSystemServer();
14382             }
14383         }
14384         return false;
14385     }
14386 
14387     /**
14388      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
14389      *
14390      * <p>To query for a specific user, use
14391      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
14392      * that user, and get a {@link DevicePolicyManager} from this context.
14393      *
14394      * @return the set of names of packages that were previously allowed via
14395      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
14396      * empty set if none have been allowed
14397      *
14398      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
14399      * @see #getCrossProfileCalendarPackages(ComponentName)
14400      * @hide
14401      */
14402     @RequiresPermission(anyOf = {
14403             permission.INTERACT_ACROSS_USERS_FULL,
14404             permission.INTERACT_ACROSS_USERS
14405     })
getCrossProfileCalendarPackages()14406     public @Nullable Set<String> getCrossProfileCalendarPackages() {
14407         throwIfParentInstance("getCrossProfileCalendarPackages");
14408         if (mService != null) {
14409             try {
14410                 final List<String> packageNames = mService.getCrossProfileCalendarPackagesForUser(
14411                         myUserId());
14412                 return packageNames == null ? null : new ArraySet<>(packageNames);
14413             } catch (RemoteException e) {
14414                 throw e.rethrowFromSystemServer();
14415             }
14416         }
14417         return Collections.emptySet();
14418     }
14419 
14420     /**
14421      * Sets the set of admin-allowlisted package names that are allowed to request user consent for
14422      * cross-profile communication.
14423      *
14424      * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
14425      *
14426      * <p>Previous calls are overridden by each subsequent call to this method.
14427      *
14428      * <p>Note that other apps may be able to request user consent for cross-profile communication
14429      * if they have been explicitly allowlisted by the OEM.
14430      *
14431      * <p>When previously-set cross-profile packages are missing from {@code packageNames}, the
14432      * app-op for {@code INTERACT_ACROSS_PROFILES} will be reset for those packages. This will not
14433      * occur for packages that are allowlisted by the OEM.
14434      *
14435      * @param admin the {@link DeviceAdminReceiver} this request is associated with
14436      * @param packageNames the new cross-profile package names
14437      */
setCrossProfilePackages( @onNull ComponentName admin, @NonNull Set<String> packageNames)14438     public void setCrossProfilePackages(
14439             @NonNull ComponentName admin, @NonNull Set<String> packageNames) {
14440         throwIfParentInstance("setCrossProfilePackages");
14441         if (mService != null) {
14442             try {
14443                 mService.setCrossProfilePackages(admin, new ArrayList<>(packageNames));
14444             } catch (RemoteException e) {
14445                 throw e.rethrowFromSystemServer();
14446             }
14447         }
14448     }
14449 
14450     /**
14451      * Returns the set of package names that the admin has previously set as allowed to request user
14452      * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
14453      * Set)}.
14454      *
14455      * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
14456      *
14457      * <p>Note that other apps not included in the returned set may be able to request user consent
14458      * for cross-profile communication if they have been explicitly allowlisted by the OEM.
14459      *
14460      * @param admin the {@link DeviceAdminReceiver} this request is associated with
14461      * @return the set of package names the admin has previously set as allowed to request user
14462      * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
14463      * Set)}
14464      */
getCrossProfilePackages(@onNull ComponentName admin)14465     public @NonNull Set<String> getCrossProfilePackages(@NonNull ComponentName admin) {
14466         throwIfParentInstance("getCrossProfilePackages");
14467         if (mService != null) {
14468             try {
14469                 return new ArraySet<>(mService.getCrossProfilePackages(admin));
14470             } catch (RemoteException e) {
14471                 throw e.rethrowFromSystemServer();
14472             }
14473         }
14474         return Collections.emptySet();
14475     }
14476 
14477     /**
14478      * Returns the combined set of the following:
14479      * <ul>
14480      * <li>The package names that the admin has previously set as allowed to request user consent
14481      * for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
14482      * Set)}.</li>
14483      * <li>The default package names set by the OEM that are allowed to request user consent for
14484      * cross-profile communication without being explicitly enabled by the admin, via {@link
14485      * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array
14486      * #vendor_cross_profile_apps}.</li>
14487      * </ul>
14488      *
14489      * @return the combined set of allowlisted package names set via
14490      * {@link #setCrossProfilePackages(ComponentName, Set)}, {@link com.android.internal.R.array
14491      * #cross_profile_apps}, and {@link com.android.internal.R.array#vendor_cross_profile_apps}.
14492      *
14493      * @hide
14494      */
14495     @RequiresPermission(anyOf = {
14496             permission.INTERACT_ACROSS_USERS_FULL,
14497             permission.INTERACT_ACROSS_USERS,
14498             permission.INTERACT_ACROSS_PROFILES
14499     })
getAllCrossProfilePackages()14500     public @NonNull Set<String> getAllCrossProfilePackages() {
14501         throwIfParentInstance("getAllCrossProfilePackages");
14502         if (mService != null) {
14503             try {
14504                 return new ArraySet<>(mService.getAllCrossProfilePackages());
14505             } catch (RemoteException e) {
14506                 throw e.rethrowFromSystemServer();
14507             }
14508         }
14509         return Collections.emptySet();
14510     }
14511 
14512     /**
14513      * Returns the default package names set by the OEM that are allowed to communicate
14514      * cross-profile without being explicitly enabled by the admin, via {@link
14515      * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array
14516      * #vendor_cross_profile_apps}.
14517      *
14518      * @hide
14519      */
14520     @TestApi
getDefaultCrossProfilePackages()14521     public @NonNull Set<String> getDefaultCrossProfilePackages() {
14522         throwIfParentInstance("getDefaultCrossProfilePackages");
14523         if (mService != null) {
14524             try {
14525                 return new ArraySet<>(mService.getDefaultCrossProfilePackages());
14526             } catch (RemoteException e) {
14527                 throw e.rethrowFromSystemServer();
14528             }
14529         }
14530         return Collections.emptySet();
14531     }
14532 
14533     /**
14534      * Returns whether the device is being used as a managed kiosk. These requirements are as
14535      * follows:
14536      * <ul>
14537      *     <li>The device is in Lock Task (therefore there is also a Device Owner app on the
14538      *     device)</li>
14539      *     <li>The Lock Task feature {@link DevicePolicyManager#LOCK_TASK_FEATURE_SYSTEM_INFO} is
14540      *     not enabled, so the system info in the status bar is not visible</li>
14541      *     <li>The device does not have a secure lock screen (e.g. it has no lock screen or has
14542      *     swipe-to-unlock)</li>
14543      *     <li>The device is not in the middle of an ephemeral user session</li>
14544      * </ul>
14545      *
14546      * <p>Publicly-accessible dedicated devices don't have the same privacy model as
14547      * personally-used devices. In particular, user consent popups don't make sense as a barrier to
14548      * accessing persistent data on these devices since the user giving consent and the user whose
14549      * data is on the device are unlikely to be the same. These consent popups prevent the true
14550      * remote management of these devices.
14551      *
14552      * <p>This condition is not sufficient to cover APIs that would access data that only lives for
14553      * the duration of the user's session, since the user has an expectation of privacy in these
14554      * conditions that more closely resembles use of a personal device. In those cases, see {@link
14555      * #isUnattendedManagedKiosk()}.
14556      *
14557      * @hide
14558      */
14559     @SystemApi
14560     @RequiresPermission(anyOf = {
14561             android.Manifest.permission.MANAGE_USERS,
14562             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
14563     })
isManagedKiosk()14564     public boolean isManagedKiosk() {
14565         throwIfParentInstance("isManagedKiosk");
14566         if (mService != null) {
14567             try {
14568                 return mService.isManagedKiosk();
14569             } catch (RemoteException e) {
14570                 throw e.rethrowFromSystemServer();
14571             }
14572         }
14573         return false;
14574     }
14575 
14576     /**
14577      * Returns whether the device is being used as an unattended managed kiosk. These requirements
14578      * are as follows:
14579      * <ul>
14580      *     <li>The device is being used as a managed kiosk, as defined at {@link
14581      *     #isManagedKiosk()}</li>
14582      *     <li>The device has not received user input for at least 30 minutes</li>
14583      * </ul>
14584      *
14585      * <p>See {@link #isManagedKiosk()} for context. This is a stronger requirement that also
14586      * ensures that the device hasn't been interacted with recently, making it an appropriate check
14587      * for privacy-sensitive APIs that wouldn't be appropriate during an active user session.
14588      *
14589      * @hide
14590      */
14591     @SystemApi
14592     @RequiresPermission(anyOf = {
14593             android.Manifest.permission.MANAGE_USERS,
14594             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
14595     })
isUnattendedManagedKiosk()14596     public boolean isUnattendedManagedKiosk() {
14597         throwIfParentInstance("isUnattendedManagedKiosk");
14598         if (mService != null) {
14599             try {
14600                 return mService.isUnattendedManagedKiosk();
14601             } catch (RemoteException e) {
14602                 throw e.rethrowFromSystemServer();
14603             }
14604         }
14605         return false;
14606     }
14607 
14608     /**
14609      * Starts an activity to view calendar events in the managed profile.
14610      *
14611      * @param eventId the id of the event to be viewed
14612      * @param start the start time of the event
14613      * @param end the end time of the event
14614      * @param allDay if the event is an all-day event
14615      * @param flags flags to be set for the intent
14616      * @return {@code true} if the activity is started successfully, {@code false} otherwise
14617      *
14618      * @see CalendarContract#startViewCalendarEventInManagedProfile(Context, String, long, long,
14619      * long, boolean, int)
14620      *
14621      * @hide
14622      */
startViewCalendarEventInManagedProfile(long eventId, long start, long end, boolean allDay, int flags)14623     public boolean startViewCalendarEventInManagedProfile(long eventId, long start, long end,
14624             boolean allDay, int flags) {
14625         throwIfParentInstance("startViewCalendarEventInManagedProfile");
14626         if (mService != null) {
14627             try {
14628                 return mService.startViewCalendarEventInManagedProfile(mContext.getPackageName(),
14629                         eventId, start, end, allDay, flags);
14630             } catch (RemoteException e) {
14631                 throw e.rethrowFromSystemServer();
14632             }
14633         }
14634         return false;
14635     }
14636 
14637     /**
14638      * Called by a device owner or a profile owner to disable user control over apps. User will not
14639      * be able to clear app data or force-stop packages. When called by a device owner, applies to
14640      * all users on the device. Packages with user control disabled are exempted from
14641      * App Standby Buckets.
14642      *
14643      * @param admin which {@link DeviceAdminReceiver} this request is associated with
14644      * @param packages The package names for the apps.
14645      * @throws SecurityException if {@code admin} is not a device owner or a profile owner.
14646      */
setUserControlDisabledPackages(@onNull ComponentName admin, @NonNull List<String> packages)14647     public void setUserControlDisabledPackages(@NonNull ComponentName admin,
14648             @NonNull List<String> packages) {
14649         throwIfParentInstance("setUserControlDisabledPackages");
14650         if (mService != null) {
14651             try {
14652                 mService.setUserControlDisabledPackages(admin, packages);
14653             } catch (RemoteException re) {
14654                 throw re.rethrowFromSystemServer();
14655             }
14656         }
14657     }
14658 
14659     /**
14660      * Returns the list of packages over which user control is disabled by a device or profile
14661      * owner.
14662      *
14663      * @param admin which {@link DeviceAdminReceiver} this request is associated with
14664      * @throws SecurityException if {@code admin} is not a device or profile owner.
14665      */
14666     @NonNull
getUserControlDisabledPackages(@onNull ComponentName admin)14667     public List<String> getUserControlDisabledPackages(@NonNull ComponentName admin) {
14668         throwIfParentInstance("getUserControlDisabledPackages");
14669         if (mService != null) {
14670             try {
14671                 return mService.getUserControlDisabledPackages(admin);
14672             } catch (RemoteException re) {
14673                 throw re.rethrowFromSystemServer();
14674             }
14675         }
14676         return Collections.emptyList();
14677     }
14678 
14679     /**
14680      * Called by device owner or profile owner of an organization-owned managed profile to toggle
14681      * Common Criteria mode for the device. When the device is in Common Criteria mode,
14682      * certain device functionalities are tuned to meet the higher
14683      * security level required by Common Criteria certification. For example:
14684      * <ul>
14685      * <li> Bluetooth long term key material is additionally integrity-protected with AES-GCM. </li>
14686      * <li> WiFi configuration store is additionally integrity-protected with AES-GCM. </li>
14687      * </ul>
14688      * Common Criteria mode is disabled by default.
14689      *
14690      * <p><em>Note:</em> if Common Critera mode is turned off after being enabled previously,
14691      * all existing WiFi configurations will be lost.
14692      *
14693      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
14694      * @param enabled whether Common Criteria mode should be enabled or not.
14695      */
setCommonCriteriaModeEnabled(@onNull ComponentName admin, boolean enabled)14696     public void setCommonCriteriaModeEnabled(@NonNull ComponentName admin, boolean enabled) {
14697         throwIfParentInstance("setCommonCriteriaModeEnabled");
14698         if (mService != null) {
14699             try {
14700                 mService.setCommonCriteriaModeEnabled(admin, enabled);
14701             } catch (RemoteException e) {
14702                 throw e.rethrowFromSystemServer();
14703             }
14704         }
14705     }
14706 
14707     /**
14708      * Returns whether Common Criteria mode is currently enabled. Device owner and profile owner of
14709      * an organization-owned managed profile can query its own Common Criteria mode setting by
14710      * calling this method with its admin {@link ComponentName}. Any caller can obtain the
14711      * aggregated device-wide Common Criteria mode state by passing {@code null} as the
14712      * {@code admin} argument.
14713      *
14714      * @param admin which {@link DeviceAdminReceiver} this request is associated with, or
14715      *     {@code null} if the caller is not a device admin.
14716      * @return {@code true} if Common Criteria mode is enabled, {@code false} otherwise.
14717      */
isCommonCriteriaModeEnabled(@ullable ComponentName admin)14718     public boolean isCommonCriteriaModeEnabled(@Nullable ComponentName admin) {
14719         throwIfParentInstance("isCommonCriteriaModeEnabled");
14720         if (mService != null) {
14721             try {
14722                 return mService.isCommonCriteriaModeEnabled(admin);
14723             } catch (RemoteException e) {
14724                 throw e.rethrowFromSystemServer();
14725             }
14726         }
14727         return false;
14728     }
14729 
14730     /**
14731      * Called by profile owner of an organization-owned managed profile to check whether
14732      * personal apps are suspended.
14733      *
14734      * @return a bitmask of reasons for personal apps suspension or
14735      *     {@link #PERSONAL_APPS_NOT_SUSPENDED} if apps are not suspended.
14736      * @see #setPersonalAppsSuspended
14737      */
getPersonalAppsSuspendedReasons( @onNull ComponentName admin)14738     public @PersonalAppsSuspensionReason int getPersonalAppsSuspendedReasons(
14739             @NonNull ComponentName admin) {
14740         throwIfParentInstance("getPersonalAppsSuspendedReasons");
14741         if (mService != null) {
14742             try {
14743                 return mService.getPersonalAppsSuspendedReasons(admin);
14744             } catch (RemoteException re) {
14745                 throw re.rethrowFromSystemServer();
14746             }
14747         }
14748         return 0;
14749     }
14750 
14751     /**
14752      * Called by a profile owner of an organization-owned managed profile to suspend personal
14753      * apps on the device. When personal apps are suspended the device can only be used for calls.
14754      *
14755      * <p>When personal apps are suspended, an ongoing notification about that is shown to the user.
14756      * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE}
14757      * in the profile owner package. Profile owner implementation that uses personal apps suspension
14758      * must handle this intent.
14759      *
14760      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
14761      * @param suspended Whether personal apps should be suspended.
14762      * @throws IllegalStateException if the profile owner doesn't have an activity that handles
14763      *        {@link #ACTION_CHECK_POLICY_COMPLIANCE}
14764      */
setPersonalAppsSuspended(@onNull ComponentName admin, boolean suspended)14765     public void setPersonalAppsSuspended(@NonNull ComponentName admin, boolean suspended) {
14766         throwIfParentInstance("setPersonalAppsSuspended");
14767         if (mService != null) {
14768             try {
14769                 mService.setPersonalAppsSuspended(admin, suspended);
14770             } catch (RemoteException re) {
14771                 throw re.rethrowFromSystemServer();
14772             }
14773         }
14774     }
14775 
14776     /**
14777      * Called by a profile owner of an organization-owned managed profile to set maximum time
14778      * the profile is allowed to be turned off. If the profile is turned off for longer, personal
14779      * apps are suspended on the device.
14780      *
14781      * <p>When personal apps are suspended, an ongoing notification about that is shown to the user.
14782      * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE}
14783      * in the profile owner package. Profile owner implementation that uses personal apps suspension
14784      * must handle this intent.
14785      *
14786      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
14787      * @param timeoutMillis Maximum time the profile is allowed to be off in milliseconds or 0 if
14788      *        not limited. The minimum non-zero value corresponds to 72 hours. If an admin sets a
14789      *        smaller non-zero vaulue, 72 hours will be set instead.
14790      * @throws IllegalStateException if the profile owner doesn't have an activity that handles
14791      *        {@link #ACTION_CHECK_POLICY_COMPLIANCE}
14792      * @see #setPersonalAppsSuspended
14793      */
setManagedProfileMaximumTimeOff(@onNull ComponentName admin, long timeoutMillis)14794     public void setManagedProfileMaximumTimeOff(@NonNull ComponentName admin, long timeoutMillis) {
14795         throwIfParentInstance("setManagedProfileMaximumTimeOff");
14796         if (mService != null) {
14797             try {
14798                 mService.setManagedProfileMaximumTimeOff(admin, timeoutMillis);
14799             } catch (RemoteException re) {
14800                 throw re.rethrowFromSystemServer();
14801             }
14802         }
14803     }
14804 
14805      /**
14806      * Called by a profile owner of an organization-owned managed profile to get maximum time
14807      * the profile is allowed to be turned off.
14808      *
14809      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
14810      * @return Maximum time the profile is allowed to be off in milliseconds or 0 if not limited.
14811      * @see #setPersonalAppsSuspended
14812      */
getManagedProfileMaximumTimeOff(@onNull ComponentName admin)14813     public long getManagedProfileMaximumTimeOff(@NonNull ComponentName admin) {
14814         throwIfParentInstance("getManagedProfileMaximumTimeOff");
14815         if (mService != null) {
14816             try {
14817                 return mService.getManagedProfileMaximumTimeOff(admin);
14818             } catch (RemoteException re) {
14819                 throw re.rethrowFromSystemServer();
14820             }
14821         }
14822         return 0;
14823     }
14824 
14825     /**
14826      * Called by a profile owner of an organization-owned managed profile to acknowledge that the
14827      * device is compliant and the user can turn the profile off if needed according to the maximum
14828      * time off policy.
14829      *
14830      * This method should be called when the device is deemed compliant after getting
14831      * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)} callback in
14832      * case it is overridden. Before this method is called the user is still free to turn the
14833      * profile off, but the timer won't be reset, so personal apps will be suspended sooner.
14834      *
14835      * DPCs only need acknowledging device compliance if they override
14836      * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)}, otherwise
14837      * compliance is acknowledged automatically.
14838      *
14839      * @throws IllegalStateException if the user isn't unlocked
14840      * @see #isComplianceAcknowledgementRequired()
14841      * @see #setManagedProfileMaximumTimeOff(ComponentName, long)
14842      * @see DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)
14843      */
acknowledgeDeviceCompliant()14844     public void acknowledgeDeviceCompliant() {
14845         throwIfParentInstance("acknowledgeDeviceCompliant");
14846         if (mService != null) {
14847             try {
14848                 mService.acknowledgeDeviceCompliant();
14849             } catch (RemoteException re) {
14850                 throw re.rethrowFromSystemServer();
14851             }
14852         }
14853     }
14854 
14855     /**
14856      * Called by a profile owner of an organization-owned managed profile to query whether it needs
14857      * to acknowledge device compliance to allow the user to turn the profile off if needed
14858      * according to the maximum profile time off policy.
14859      *
14860      * Normally when acknowledgement is needed the DPC gets a
14861      * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)} callback.
14862      * But if the callback was not delivered or handled for some reason, this method can be used to
14863      * verify if acknowledgement is needed.
14864      *
14865      * @throws IllegalStateException if the user isn't unlocked
14866      * @see #acknowledgeDeviceCompliant()
14867      * @see #setManagedProfileMaximumTimeOff(ComponentName, long)
14868      * @see DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)
14869      */
isComplianceAcknowledgementRequired()14870     public boolean isComplianceAcknowledgementRequired() {
14871         throwIfParentInstance("isComplianceAcknowledgementRequired");
14872         if (mService != null) {
14873             try {
14874                 return mService.isComplianceAcknowledgementRequired();
14875             } catch (RemoteException re) {
14876                 throw re.rethrowFromSystemServer();
14877             }
14878         }
14879         return false;
14880     }
14881 
14882     /**
14883      * Returns {@code true} when {@code userId} has a profile owner that is capable of resetting
14884      * password in RUNNING_LOCKED state. For that it should have at least one direct boot aware
14885      * component and have an active password reset token. Can only be called by the system.
14886      * @hide
14887      */
canProfileOwnerResetPasswordWhenLocked(int userId)14888     public boolean canProfileOwnerResetPasswordWhenLocked(int userId) {
14889         if (mService != null) {
14890             try {
14891                 return mService.canProfileOwnerResetPasswordWhenLocked(userId);
14892             } catch (RemoteException re) {
14893                 throw re.rethrowFromSystemServer();
14894             }
14895         }
14896         return false;
14897     }
14898 
14899     /**
14900      * Used by CTS to set the result of the next safety operation check.
14901      *
14902      * @hide
14903      */
14904     @TestApi
14905     @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
setNextOperationSafety(@evicePolicyOperation int operation, @OperationSafetyReason int reason)14906     public void setNextOperationSafety(@DevicePolicyOperation int operation,
14907             @OperationSafetyReason int reason) {
14908         if (mService != null) {
14909             try {
14910                 mService.setNextOperationSafety(operation, reason);
14911             } catch (RemoteException re) {
14912                 throw re.rethrowFromSystemServer();
14913             }
14914         }
14915     }
14916 
14917     /**
14918      * Returns an enrollment-specific identifier of this device, which is guaranteed to be the same
14919      * value for the same device, enrolled into the same organization by the same managing app.
14920      * This identifier is high-entropy, useful for uniquely identifying individual devices within
14921      * the same organisation.
14922      * It is available both in a work profile and on a fully-managed device.
14923      * The identifier would be consistent even if the work profile is removed and enrolled again
14924      * (to the same organization), or the device is factory reset and re-enrolled.
14925      *
14926      * Can only be called by the Profile Owner or Device Owner, if the
14927      * {@link #setOrganizationId(String)} was previously called.
14928      * If {@link #setOrganizationId(String)} was not called, then the returned value will be an
14929      * empty string.
14930      *
14931      * <p>Note about access to device identifiers: a device owner, a profile owner of an
14932      * organization-owned device or the delegated certificate installer (holding the
14933      * {@link #DELEGATION_CERT_INSTALL} delegation) on such a device can still obtain hardware
14934      * identifiers by calling e.g. {@link android.os.Build#getSerial()}, in addition to using
14935      * this method. However, a profile owner on a personal (non organization-owned) device, or the
14936      * delegated certificate installer on such a device, cannot obtain hardware identifiers anymore
14937      * and must switch to using this method.
14938      *
14939      * @return A stable, enrollment-specific identifier.
14940      * @throws SecurityException if the caller is not a profile owner or device owner.
14941      */
getEnrollmentSpecificId()14942     @NonNull public String getEnrollmentSpecificId() {
14943         throwIfParentInstance("getEnrollmentSpecificId");
14944         if (mService == null) {
14945             return "";
14946         }
14947 
14948         try {
14949             return mService.getEnrollmentSpecificId(mContext.getPackageName());
14950         } catch (RemoteException re) {
14951             throw re.rethrowFromSystemServer();
14952         }
14953     }
14954 
14955     /**
14956      * Sets the Enterprise ID for the work profile or managed device. This is a requirement for
14957      * generating an enrollment-specific ID for the device, see {@link #getEnrollmentSpecificId()}.
14958      *
14959      * It is recommended that the Enterprise ID is at least 6 characters long, and no more than
14960      * 64 characters.
14961      *
14962      * @param enterpriseId An identifier of the organization this work profile or device is
14963      *                     enrolled into.
14964      */
setOrganizationId(@onNull String enterpriseId)14965     public void setOrganizationId(@NonNull String enterpriseId) {
14966         throwIfParentInstance("setOrganizationId");
14967         setOrganizationIdForUser(mContext.getPackageName(), enterpriseId, myUserId());
14968     }
14969 
14970     /**
14971      * Sets the Enterprise ID for the work profile or managed device. This is a requirement for
14972      * generating an enrollment-specific ID for the device, see
14973      * {@link #getEnrollmentSpecificId()}.
14974      *
14975      * @hide
14976      */
setOrganizationIdForUser(@onNull String packageName, @NonNull String enterpriseId, @UserIdInt int userId)14977     public void setOrganizationIdForUser(@NonNull String packageName,
14978             @NonNull String enterpriseId, @UserIdInt int userId) {
14979         if (mService == null) {
14980             return;
14981         }
14982         try {
14983             mService.setOrganizationIdForUser(packageName, enterpriseId, userId);
14984         } catch (RemoteException re) {
14985             throw re.rethrowFromSystemServer();
14986         }
14987     }
14988 
14989     /**
14990      * Clears organization ID set by the DPC and resets the precomputed enrollment specific ID.
14991      * @hide
14992      */
14993     @TestApi
14994     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
clearOrganizationId()14995     public void clearOrganizationId() {
14996         if (mService == null) {
14997             return;
14998         }
14999         try {
15000             mService.clearOrganizationIdForUser(myUserId());
15001         } catch (RemoteException re) {
15002             throw re.rethrowFromSystemServer();
15003         }
15004     }
15005 
15006     /**
15007      * Creates and provisions a managed profile and sets the
15008      * {@link ManagedProfileProvisioningParams#getProfileAdminComponentName()} as the profile
15009      * owner.
15010      *
15011      * <p>The method {@link #checkProvisioningPrecondition} must be returning {@link #STATUS_OK}
15012      * before calling this method.
15013      *
15014      * @param provisioningParams Params required to provision a managed profile,
15015      * see {@link ManagedProfileProvisioningParams}.
15016      * @return The {@link UserHandle} of the created profile or {@code null} if the service is
15017      * not available.
15018      * @throws SecurityException if the caller does not hold
15019      * {@link android.Manifest.permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
15020      * @throws ProvisioningException if an error occurred during provisioning.
15021      * @hide
15022      */
15023     @Nullable
15024     @SystemApi
15025     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
createAndProvisionManagedProfile( @onNull ManagedProfileProvisioningParams provisioningParams)15026     public UserHandle createAndProvisionManagedProfile(
15027             @NonNull ManagedProfileProvisioningParams provisioningParams)
15028             throws ProvisioningException {
15029         if (mService == null) {
15030             return null;
15031         }
15032         try {
15033             return mService.createAndProvisionManagedProfile(
15034                     provisioningParams, mContext.getPackageName());
15035         } catch (ServiceSpecificException e) {
15036             throw new ProvisioningException(e, e.errorCode, getErrorMessage(e));
15037         } catch (RemoteException e) {
15038             throw e.rethrowFromSystemServer();
15039         }
15040     }
15041 
15042     /**
15043      * Called when a managed profile has been provisioned.
15044      *
15045      * @throws SecurityException if the caller does not hold
15046      * {@link android.Manifest.permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
15047      * @hide
15048      */
15049     @SystemApi
15050     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
finalizeWorkProfileProvisioning( @onNull UserHandle managedProfileUser, @Nullable Account migratedAccount)15051     public void finalizeWorkProfileProvisioning(
15052             @NonNull UserHandle managedProfileUser, @Nullable Account migratedAccount) {
15053         Objects.requireNonNull(managedProfileUser, "managedProfileUser can't be null");
15054         if (mService == null) {
15055             throw new IllegalStateException("Could not find DevicePolicyManagerService");
15056         }
15057         try {
15058             mService.finalizeWorkProfileProvisioning(managedProfileUser, migratedAccount);
15059         } catch (RemoteException e) {
15060             throw e.rethrowFromSystemServer();
15061         }
15062     }
15063 
15064     /**
15065      * The localized error message to show to the end-user. If {@code null}, a generic error
15066      * message will be shown.
15067      */
getErrorMessage(ServiceSpecificException e)15068     private String getErrorMessage(ServiceSpecificException e) {
15069         return null;
15070     }
15071 
15072 
15073     /**
15074      * Provisions a managed device and sets the {@code deviceAdminComponentName} as the device
15075      * owner.
15076      *
15077      * <p>The method {@link #checkProvisioningPrecondition} must be returning {@link #STATUS_OK}
15078      * before calling this method.
15079      *
15080      * <p>Holders of {@link android.Manifest.permission#PROVISION_DEMO_DEVICE} can call this API
15081      * only if {@link FullyManagedDeviceProvisioningParams#isDemoDevice()} is {@code true}.</p>
15082      *
15083      * @param provisioningParams Params required to provision a fully managed device,
15084      * see {@link FullyManagedDeviceProvisioningParams}.
15085      *
15086      * @throws ProvisioningException if an error occurred during provisioning.
15087      *
15088      * @hide
15089      */
15090     @SystemApi
15091     @RequiresPermission(anyOf = {
15092             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
15093             android.Manifest.permission.PROVISION_DEMO_DEVICE})
provisionFullyManagedDevice( @onNull FullyManagedDeviceProvisioningParams provisioningParams)15094     public void provisionFullyManagedDevice(
15095             @NonNull FullyManagedDeviceProvisioningParams provisioningParams)
15096             throws ProvisioningException {
15097         if (mService != null) {
15098             try {
15099                 mService.provisionFullyManagedDevice(provisioningParams, mContext.getPackageName());
15100             } catch (ServiceSpecificException e) {
15101                 throw new ProvisioningException(e, e.errorCode, getErrorMessage(e));
15102             } catch (RemoteException re) {
15103                 throw re.rethrowFromSystemServer();
15104             }
15105         }
15106     }
15107 
15108     /**
15109      * Resets the default cross profile intent filters that were set during
15110      * {@link #createAndProvisionManagedProfile} between {@code userId} and all it's managed
15111      * profiles if any.
15112      *
15113      * @hide
15114      */
15115     @TestApi
15116     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
resetDefaultCrossProfileIntentFilters(@serIdInt int userId)15117     public void resetDefaultCrossProfileIntentFilters(@UserIdInt int userId) {
15118         if (mService != null) {
15119             try {
15120                 mService.resetDefaultCrossProfileIntentFilters(userId);
15121             } catch (RemoteException re) {
15122                 throw re.rethrowFromSystemServer();
15123             }
15124         }
15125     }
15126 
15127     /**
15128      * Returns true if the caller is running on a device where the admin can grant
15129      * permissions related to device sensors.
15130      * This is a signal that the device is a fully-managed device where personal usage is
15131      * discouraged.
15132      * The list of permissions is listed in
15133      * {@link #setPermissionGrantState(ComponentName, String, String, int)}.
15134      *
15135      * May be called by any app.
15136      * @return true if the app can grant device sensors-related permissions, false otherwise.
15137      */
canAdminGrantSensorsPermissions()15138     public boolean canAdminGrantSensorsPermissions() {
15139         throwIfParentInstance("canAdminGrantSensorsPermissions");
15140         if (mService == null) {
15141             return false;
15142         }
15143         try {
15144             return mService.canAdminGrantSensorsPermissionsForUser(myUserId());
15145         } catch (RemoteException re) {
15146             throw re.rethrowFromSystemServer();
15147         }
15148     }
15149 
15150     /**
15151      * Sets the device owner type for a managed device (e.g. financed device).
15152      *
15153      * @param admin The {@link DeviceAdminReceiver} that is the device owner.
15154      * @param deviceOwnerType The device owner type is set to. Use
15155      * {@link #DEVICE_OWNER_TYPE_DEFAULT} for the default device owner type. Use
15156      * {@link #DEVICE_OWNER_TYPE_FINANCED} for the financed device owner type.
15157      *
15158      * @throws IllegalStateException When admin is not the device owner, or there is no device
15159      *     owner, or attempting to set the device owner type again for the same admin.
15160      * @throws SecurityException If the caller does not have the permission
15161      *     {@link permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
15162      *
15163      * @hide
15164      */
15165     @TestApi
setDeviceOwnerType(@onNull ComponentName admin, @DeviceOwnerType int deviceOwnerType)15166     public void setDeviceOwnerType(@NonNull ComponentName admin,
15167             @DeviceOwnerType int deviceOwnerType) {
15168         throwIfParentInstance("setDeviceOwnerType");
15169         if (mService != null) {
15170             try {
15171                 mService.setDeviceOwnerType(admin, deviceOwnerType);
15172             } catch (RemoteException re) {
15173                 throw re.rethrowFromSystemServer();
15174             }
15175         }
15176     }
15177 
15178     /**
15179      * Returns the device owner type for the admin used in
15180      * {@link #setDeviceOwnerType(ComponentName, int)}. {@link #DEVICE_OWNER_TYPE_DEFAULT}
15181      * would be returned when the device owner type is not set for the device owner admin.
15182      *
15183      * @param admin The {@link DeviceAdminReceiver} that is the device owner.
15184      *
15185      * @throws IllegalStateException When admin is not the device owner or there is no device owner.
15186      *
15187      * @hide
15188      */
15189     @TestApi
15190     @DeviceOwnerType
getDeviceOwnerType(@onNull ComponentName admin)15191     public int getDeviceOwnerType(@NonNull ComponentName admin) {
15192         throwIfParentInstance("getDeviceOwnerType");
15193         if (mService != null) {
15194             try {
15195                 return mService.getDeviceOwnerType(admin);
15196             } catch (RemoteException re) {
15197                 throw re.rethrowFromSystemServer();
15198             }
15199         }
15200         return DEVICE_OWNER_TYPE_DEFAULT;
15201     }
15202 
15203     /**
15204      * Called by device owner or profile owner of an organization-owned managed profile to
15205      * enable or disable USB data signaling for the device. When disabled, USB data connections
15206      * (except from charging functions) are prohibited.
15207      *
15208      * <p> This API is not supported on all devices, the caller should call
15209      * {@link #canUsbDataSignalingBeDisabled()} to check whether enabling or disabling USB data
15210      * signaling is supported on the device.
15211      *
15212      * @param enabled whether USB data signaling should be enabled or not.
15213      * @throws SecurityException if the caller is not a device owner or a profile owner on
15214      *         an organization-owned managed profile.
15215      * @throws IllegalStateException if disabling USB data signaling is not supported or
15216      *         if USB data signaling fails to be enabled/disabled.
15217      */
setUsbDataSignalingEnabled(boolean enabled)15218     public void setUsbDataSignalingEnabled(boolean enabled) {
15219         throwIfParentInstance("setUsbDataSignalingEnabled");
15220         if (mService != null) {
15221             try {
15222                 mService.setUsbDataSignalingEnabled(mContext.getPackageName(), enabled);
15223             } catch (RemoteException e) {
15224                 throw e.rethrowFromSystemServer();
15225             }
15226         }
15227     }
15228 
15229     /**
15230      * Returns whether USB data signaling is currently enabled.
15231      *
15232      * <p> When called by a device owner or profile owner of an organization-owned managed profile,
15233      * this API returns whether USB data signaling is currently enabled by that admin. When called
15234      * by any other app, returns whether USB data signaling is currently enabled on the device.
15235      *
15236      * @return {@code true} if USB data signaling is enabled, {@code false} otherwise.
15237      */
isUsbDataSignalingEnabled()15238     public boolean isUsbDataSignalingEnabled() {
15239         throwIfParentInstance("isUsbDataSignalingEnabled");
15240         if (mService != null) {
15241             try {
15242                 return mService.isUsbDataSignalingEnabled(mContext.getPackageName());
15243             } catch (RemoteException e) {
15244                 throw e.rethrowFromSystemServer();
15245             }
15246         }
15247         return true;
15248     }
15249 
15250     /**
15251      * Called by the system to check whether USB data signaling is currently enabled for this user.
15252      *
15253      * @param userId which user to check for.
15254      * @return {@code true} if USB data signaling is enabled, {@code false} otherwise.
15255      * @hide
15256      */
isUsbDataSignalingEnabledForUser(@serIdInt int userId)15257     public boolean isUsbDataSignalingEnabledForUser(@UserIdInt int userId) {
15258         throwIfParentInstance("isUsbDataSignalingEnabledForUser");
15259         if (mService != null) {
15260             try {
15261                 return mService.isUsbDataSignalingEnabledForUser(userId);
15262             } catch (RemoteException e) {
15263                 throw e.rethrowFromSystemServer();
15264             }
15265         }
15266         return true;
15267     }
15268 
15269     /**
15270      * Returns whether enabling or disabling USB data signaling is supported on the device.
15271      *
15272      * @return {@code true} if the device supports enabling and disabling USB data signaling.
15273      */
canUsbDataSignalingBeDisabled()15274     public boolean canUsbDataSignalingBeDisabled() {
15275         throwIfParentInstance("canUsbDataSignalingBeDisabled");
15276         if (mService != null) {
15277             try {
15278                 return mService.canUsbDataSignalingBeDisabled();
15279             } catch (RemoteException re) {
15280                 throw re.rethrowFromSystemServer();
15281             }
15282         }
15283         return false;
15284     }
15285 
15286     /**
15287      * Gets the list of {@link #isAffiliatedUser() affiliated} users running on foreground.
15288      *
15289      * @return list of {@link #isAffiliatedUser() affiliated} users running on foreground.
15290      *
15291      * @throws SecurityException if the calling application is not a device owner
15292      */
15293     @NonNull
listForegroundAffiliatedUsers()15294     public List<UserHandle> listForegroundAffiliatedUsers() {
15295         if (mService == null) return Collections.emptyList();
15296 
15297         try {
15298             return mService.listForegroundAffiliatedUsers();
15299         } catch (RemoteException re) {
15300             throw re.rethrowFromSystemServer();
15301         }
15302     }
15303 
15304     /**
15305      * Lists apps that are exempt from policies (such as
15306      * {@link #setPackagesSuspended(ComponentName, String[], boolean)}).
15307      *
15308      * @hide
15309      */
15310     @TestApi
15311     @RequiresPermission(value = android.Manifest.permission.MANAGE_DEVICE_ADMINS)
getPolicyExemptApps()15312     public @NonNull Set<String> getPolicyExemptApps() {
15313         if (mService == null) return Collections.emptySet();
15314 
15315         try {
15316             return new HashSet<>(mService.listPolicyExemptApps());
15317         } catch (RemoteException e) {
15318             throw e.rethrowFromSystemServer();
15319         }
15320     }
15321 
15322     /**
15323      * Creates a {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent
15324      * from the provided {@code nfcIntent}.
15325      *
15326      * <p>Prerequisites to create the provisioning intent:
15327      *
15328      * <ul>
15329      * <li>{@code nfcIntent}'s action is {@link NfcAdapter#ACTION_NDEF_DISCOVERED}</li>
15330      * <li>{@code nfcIntent}'s NFC properties contain either
15331      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} or
15332      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} </li>
15333      * </ul>
15334      *
15335      * This method returns {@code null} if the prerequisites are not met or if an error occurs
15336      * when reading the NFC properties.
15337      *
15338      * @param nfcIntent the nfc intent generated from scanning a NFC tag
15339      * @return a {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent with
15340      * intent extras as read by {@code nfcIntent}'s NFC properties or {@code null} if the
15341      * prerequisites are not met or if an error occurs when reading the NFC properties.
15342      *
15343      * @hide
15344      */
15345     @Nullable
15346     @SystemApi
createProvisioningIntentFromNfcIntent(@onNull Intent nfcIntent)15347     public Intent createProvisioningIntentFromNfcIntent(@NonNull Intent nfcIntent) {
15348         return ProvisioningIntentHelper.createProvisioningIntentFromNfcIntent(nfcIntent);
15349     }
15350 
15351     /**
15352      * Called by device owner or profile owner of an organization-owned managed profile to
15353      * specify the minimum security level required for Wi-Fi networks.
15354      * The device may not connect to networks that do not meet the minimum security level.
15355      * If the current network does not meet the minimum security level set, it will be disconnected.
15356      *
15357      * The following shows the Wi-Fi security levels from the lowest to the highest security level:
15358      * {@link #WIFI_SECURITY_OPEN}
15359      * {@link #WIFI_SECURITY_PERSONAL}
15360      * {@link #WIFI_SECURITY_ENTERPRISE_EAP}
15361      * {@link #WIFI_SECURITY_ENTERPRISE_192}
15362      *
15363      * @param level minimum security level
15364      * @throws SecurityException if the caller is not a device owner or a profile owner on
15365      *         an organization-owned managed profile.
15366      */
setMinimumRequiredWifiSecurityLevel(@ifiSecurity int level)15367     public void setMinimumRequiredWifiSecurityLevel(@WifiSecurity int level) {
15368         throwIfParentInstance("setMinimumRequiredWifiSecurityLevel");
15369         if (mService != null) {
15370             try {
15371                 mService.setMinimumRequiredWifiSecurityLevel(level);
15372             } catch (RemoteException e) {
15373                 throw e.rethrowFromSystemServer();
15374             }
15375         }
15376     }
15377 
15378     /**
15379      * Returns the current Wi-Fi minimum security level.
15380      *
15381      * @see #setMinimumRequiredWifiSecurityLevel(int)
15382      */
getMinimumRequiredWifiSecurityLevel()15383     public @WifiSecurity int getMinimumRequiredWifiSecurityLevel() {
15384         throwIfParentInstance("getMinimumRequiredWifiSecurityLevel");
15385         if (mService == null) {
15386             return WIFI_SECURITY_OPEN;
15387         }
15388         try {
15389             return mService.getMinimumRequiredWifiSecurityLevel();
15390         } catch (RemoteException e) {
15391             throw e.rethrowFromSystemServer();
15392         }
15393     }
15394 
15395     /**
15396      * Called by device owner or profile owner of an organization-owned managed profile to
15397      * specify the Wi-Fi SSID policy ({@link WifiSsidPolicy}).
15398      * Wi-Fi SSID policy specifies the SSID restriction the network must satisfy
15399      * in order to be eligible for a connection. Providing a null policy results in the
15400      * deactivation of the SSID restriction
15401      *
15402      * @param policy Wi-Fi SSID policy
15403      * @throws SecurityException if the caller is not a device owner or a profile owner on
15404      *         an organization-owned managed profile.
15405      */
setWifiSsidPolicy(@ullable WifiSsidPolicy policy)15406     public void setWifiSsidPolicy(@Nullable WifiSsidPolicy policy) {
15407         throwIfParentInstance("setWifiSsidPolicy");
15408         if (mService == null) {
15409             return;
15410         }
15411         try {
15412             mService.setWifiSsidPolicy(policy);
15413         } catch (RemoteException e) {
15414             throw e.rethrowFromSystemServer();
15415         }
15416 
15417     }
15418 
15419     /**
15420      * Returns the current Wi-Fi SSID policy.
15421      * If the policy has not been set, it will return NULL.
15422      *
15423      * @see #setWifiSsidPolicy(WifiSsidPolicy)
15424      * @throws SecurityException if the caller is not a device owner or a profile owner on
15425      * an organization-owned managed profile or a system app.
15426      */
15427     @Nullable
getWifiSsidPolicy()15428     public WifiSsidPolicy getWifiSsidPolicy() {
15429         throwIfParentInstance("getWifiSsidPolicy");
15430         if (mService == null) {
15431             return null;
15432         }
15433         try {
15434             return mService.getWifiSsidPolicy();
15435         } catch (RemoteException e) {
15436             throw e.rethrowFromSystemServer();
15437         }
15438     }
15439 
15440     /**
15441      * Returns a {@link DevicePolicyResourcesManager} containing the required APIs to set, reset,
15442      * and get device policy related resources.
15443      */
15444     @NonNull
getResources()15445     public DevicePolicyResourcesManager getResources() {
15446         return mResourcesManager;
15447     }
15448 
15449     /**
15450      * Returns a boolean for whether the DPC
15451      * (Device Policy Controller, the agent responsible for enforcing policy)
15452      * has been downloaded during provisioning.
15453      *
15454      * <p>If true is returned, then any attempts to begin setup again should result in factory reset
15455      *
15456      * @hide
15457      */
15458     @SystemApi
15459     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
isDpcDownloaded()15460     public boolean isDpcDownloaded() {
15461         throwIfParentInstance("isDpcDownloaded");
15462         if (mService != null) {
15463             try {
15464                 return mService.isDpcDownloaded();
15465             } catch (RemoteException e) {
15466                 throw e.rethrowFromSystemServer();
15467             }
15468         }
15469         return false;
15470     }
15471 
15472     /**
15473      * Indicates that the DPC (Device Policy Controller, the agent responsible for enforcing policy)
15474      * has or has not been downloaded during provisioning.
15475      *
15476      * @param downloaded {@code true} if the dpc has been downloaded during provisioning.
15477      *                               {@code false} otherwise.
15478      *
15479      * @hide
15480      */
15481     @SystemApi
15482     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setDpcDownloaded(boolean downloaded)15483     public void setDpcDownloaded(boolean downloaded) {
15484         throwIfParentInstance("setDpcDownloaded");
15485         if (mService != null) {
15486             try {
15487                 mService.setDpcDownloaded(downloaded);
15488             } catch (RemoteException e) {
15489                 throw e.rethrowFromSystemServer();
15490             }
15491         }
15492     }
15493 
15494     /**
15495      * Returns the package name of the device policy management role holder.
15496      *
15497      * <p>If the device policy management role holder is not configured for this device, returns
15498      * {@code null}.
15499      */
15500     @Nullable
getDevicePolicyManagementRoleHolderPackage()15501     public String getDevicePolicyManagementRoleHolderPackage() {
15502         String devicePolicyManagementConfig = mContext.getString(
15503                 com.android.internal.R.string.config_devicePolicyManagement);
15504         return extractPackageNameFromDeviceManagerConfig(devicePolicyManagementConfig);
15505     }
15506 
15507     /**
15508      * Returns the package name of the device policy management role holder updater.
15509      *
15510      * <p>If the device policy management role holder updater is not configured for this device,
15511      * returns {@code null}.
15512      *
15513      * @hide
15514      */
15515     @Nullable
15516     @TestApi
getDevicePolicyManagementRoleHolderUpdaterPackage()15517     public String getDevicePolicyManagementRoleHolderUpdaterPackage() {
15518         String devicePolicyManagementUpdaterConfig = mContext.getString(
15519                 com.android.internal.R.string.config_devicePolicyManagementUpdater);
15520         if (TextUtils.isEmpty(devicePolicyManagementUpdaterConfig)) {
15521             return null;
15522         }
15523         return devicePolicyManagementUpdaterConfig;
15524     }
15525 
15526     /**
15527      * Returns a {@link List} of managed profiles managed by some profile owner within the profile
15528      * group of the given user, or an empty {@link List} if there is not one.
15529      *
15530      * @param user the user whose profile group to look within to return managed profiles
15531      *
15532      * @hide
15533      */
15534     @SystemApi
15535     @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
15536     @NonNull
getPolicyManagedProfiles(@onNull UserHandle user)15537     public List<UserHandle> getPolicyManagedProfiles(@NonNull UserHandle user) {
15538         Objects.requireNonNull(user);
15539         if (mService != null) {
15540             try {
15541                 return mService.getPolicyManagedProfiles(user);
15542             } catch (RemoteException e) {
15543                 throw e.rethrowFromSystemServer();
15544             }
15545         }
15546         return Collections.emptyList();
15547     }
15548 
15549     /**
15550      * Retrieves the package name for a given {@code deviceManagerConfig}.
15551      *
15552      * <p>Valid configs look like:
15553      * <ul>
15554      *     <li>{@code com.package.name}</li>
15555      *     <li>{@code com.package.name:<SHA256 checksum>}</li>
15556      * </ul>
15557      *
15558      * <p>If the supplied {@code deviceManagerConfig} is {@code null} or empty, returns
15559      * {@code null}.
15560      */
15561     @Nullable
extractPackageNameFromDeviceManagerConfig( @ullable String deviceManagerConfig)15562     private String extractPackageNameFromDeviceManagerConfig(
15563             @Nullable String deviceManagerConfig) {
15564         if (TextUtils.isEmpty(deviceManagerConfig)) {
15565             return null;
15566         }
15567         if (deviceManagerConfig.contains(":")) {
15568             return deviceManagerConfig.split(":")[0];
15569         }
15570         return deviceManagerConfig;
15571     }
15572 
15573     /**
15574      * @return {@code true} if bypassing the device policy management role qualification is allowed
15575      * with the current state of the device.
15576      *
15577      * @hide
15578      */
15579     @SystemApi
15580     @RequiresPermission(android.Manifest.permission.MANAGE_ROLE_HOLDERS)
shouldAllowBypassingDevicePolicyManagementRoleQualification()15581     public boolean shouldAllowBypassingDevicePolicyManagementRoleQualification() {
15582         if (mService != null) {
15583             try {
15584                 return mService.shouldAllowBypassingDevicePolicyManagementRoleQualification();
15585             } catch (RemoteException e) {
15586                 throw e.rethrowFromSystemServer();
15587             }
15588         }
15589         return false;
15590     }
15591 }
15592