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.Manifest.permission.INTERACT_ACROSS_USERS;
20 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
21 import static android.Manifest.permission.MANAGE_DEVICE_ADMINS;
22 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT;
23 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_APPS_CONTROL;
24 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CAMERA;
25 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CERTIFICATES;
26 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE;
27 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_DEFAULT_SMS;
28 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_FACTORY_RESET;
29 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_INPUT_METHODS;
30 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_KEYGUARD;
31 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK;
32 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS;
33 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK_TASK;
34 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MTE;
35 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY;
36 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PACKAGE_STATE;
37 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PROFILE_INTERACTION;
38 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RESET_PASSWORD;
39 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS;
40 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SCREEN_CAPTURE;
41 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SECURITY_LOGGING;
42 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_STATUS_BAR;
43 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE;
44 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SYSTEM_UPDATES;
45 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING;
46 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WIFI;
47 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WIPE_DATA;
48 import static android.Manifest.permission.QUERY_ADMIN_POLICY;
49 import static android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY;
50 import static android.Manifest.permission.SET_TIME;
51 import static android.Manifest.permission.SET_TIME_ZONE;
52 import static android.content.Intent.LOCAL_FLAG_FROM_SYSTEM;
53 import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
54 import static android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE;
55 
56 import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
57 
58 import android.Manifest.permission;
59 import android.accounts.Account;
60 import android.annotation.BroadcastBehavior;
61 import android.annotation.CallbackExecutor;
62 import android.annotation.ColorInt;
63 import android.annotation.IntDef;
64 import android.annotation.NonNull;
65 import android.annotation.Nullable;
66 import android.annotation.RequiresFeature;
67 import android.annotation.RequiresPermission;
68 import android.annotation.SdkConstant;
69 import android.annotation.SdkConstant.SdkConstantType;
70 import android.annotation.StringDef;
71 import android.annotation.SupportsCoexistence;
72 import android.annotation.SuppressLint;
73 import android.annotation.SystemApi;
74 import android.annotation.SystemService;
75 import android.annotation.TestApi;
76 import android.annotation.UserHandleAware;
77 import android.annotation.UserIdInt;
78 import android.annotation.WorkerThread;
79 import android.app.Activity;
80 import android.app.IServiceConnection;
81 import android.app.KeyguardManager;
82 import android.app.admin.SecurityLog.SecurityEvent;
83 import android.compat.annotation.UnsupportedAppUsage;
84 import android.content.ComponentName;
85 import android.content.Context;
86 import android.content.Intent;
87 import android.content.IntentFilter;
88 import android.content.ServiceConnection;
89 import android.content.pm.ApplicationInfo;
90 import android.content.pm.IPackageDataObserver;
91 import android.content.pm.PackageManager;
92 import android.content.pm.PackageManager.NameNotFoundException;
93 import android.content.pm.ParceledListSlice;
94 import android.content.pm.UserInfo;
95 import android.graphics.Bitmap;
96 import android.graphics.drawable.Drawable;
97 import android.net.PrivateDnsConnectivityChecker;
98 import android.net.ProxyInfo;
99 import android.net.Uri;
100 import android.nfc.NfcAdapter;
101 import android.os.Binder;
102 import android.os.Build;
103 import android.os.Bundle;
104 import android.os.IpcDataCache;
105 import android.os.ParcelFileDescriptor;
106 import android.os.Parcelable;
107 import android.os.PersistableBundle;
108 import android.os.Process;
109 import android.os.RemoteCallback;
110 import android.os.RemoteException;
111 import android.os.ServiceSpecificException;
112 import android.os.UserHandle;
113 import android.os.UserManager;
114 import android.os.UserManager.UserOperationException;
115 import android.os.UserManager.UserOperationResult;
116 import android.provider.CalendarContract;
117 import android.provider.ContactsContract.Directory;
118 import android.provider.Settings;
119 import android.security.AttestedKeyPair;
120 import android.security.Credentials;
121 import android.security.KeyChain;
122 import android.security.KeyChainException;
123 import android.security.keymaster.KeymasterCertificateChain;
124 import android.security.keystore.AttestationUtils;
125 import android.security.keystore.KeyAttestationException;
126 import android.security.keystore.KeyGenParameterSpec;
127 import android.security.keystore.ParcelableKeyGenParameterSpec;
128 import android.security.keystore.StrongBoxUnavailableException;
129 import android.service.restrictions.RestrictionsReceiver;
130 import android.telephony.TelephonyManager;
131 import android.telephony.data.ApnSetting;
132 import android.text.TextUtils;
133 import android.util.ArraySet;
134 import android.util.DebugUtils;
135 import android.util.Log;
136 import android.util.Pair;
137 
138 import com.android.internal.annotations.VisibleForTesting;
139 import com.android.internal.infra.AndroidFuture;
140 import com.android.internal.net.NetworkUtilsInternal;
141 import com.android.internal.os.BackgroundThread;
142 import com.android.internal.util.ArrayUtils;
143 import com.android.internal.util.Preconditions;
144 import com.android.org.conscrypt.TrustedCertificateStore;
145 
146 import java.io.ByteArrayInputStream;
147 import java.io.FileNotFoundException;
148 import java.io.IOException;
149 import java.lang.annotation.Retention;
150 import java.lang.annotation.RetentionPolicy;
151 import java.net.InetSocketAddress;
152 import java.net.Proxy;
153 import java.security.KeyFactory;
154 import java.security.KeyPair;
155 import java.security.NoSuchAlgorithmException;
156 import java.security.PrivateKey;
157 import java.security.cert.Certificate;
158 import java.security.cert.CertificateException;
159 import java.security.cert.CertificateFactory;
160 import java.security.cert.X509Certificate;
161 import java.security.spec.InvalidKeySpecException;
162 import java.security.spec.PKCS8EncodedKeySpec;
163 import java.util.ArrayList;
164 import java.util.Arrays;
165 import java.util.Collections;
166 import java.util.HashSet;
167 import java.util.List;
168 import java.util.Map;
169 import java.util.Objects;
170 import java.util.Set;
171 import java.util.concurrent.CompletableFuture;
172 import java.util.concurrent.ExecutionException;
173 import java.util.concurrent.Executor;
174 import java.util.function.Consumer;
175 
176 // TODO(b/172376923) - add CarDevicePolicyManager examples below (or remove reference to it).
177 /**
178  * Public interface for managing policies enforced on a device. Most clients of this class must be
179  * registered with the system as a <a href="{@docRoot}guide/topics/admin/device-admin.html">device
180  * administrator</a>. Additionally, a device administrator may be registered as either a profile or
181  * device owner. A given method is accessible to all device administrators unless the documentation
182  * for that method specifies that it is restricted to either device or profile owners. Any
183  * application calling an api may only pass as an argument a device administrator component it
184  * owns. Otherwise, a {@link SecurityException} will be thrown.
185  *
186  * <p><b>Note: </b>on
187  * {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, some methods can
188  * throw an {@link UnsafeStateException} exception (for example, if the vehicle is moving), so
189  * callers running on automotive builds should always check for that exception, otherwise they
190  * might crash.
191  *
192  * <div class="special reference">
193  * <h3>Developer Guides</h3>
194  * <p>
195  * For more information about managing policies for device administration, read the <a href=
196  * "{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a> developer
197  * guide. </div>
198  */
199 @SystemService(Context.DEVICE_POLICY_SERVICE)
200 @RequiresFeature(PackageManager.FEATURE_DEVICE_ADMIN)
201 @SuppressLint("UseIcu")
202 public class DevicePolicyManager {
203 
204     /** @hide */
205     public static final String DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_FLAG =
206             "deprecate_usermanagerinternal_devicepolicy";
207     /** @hide */
208     public static final boolean DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_DEFAULT = true;
209     /** @hide */
210     public static final String ADD_ISFINANCED_DEVICE_FLAG =
211             "add-isfinanced-device";
212     /** @hide */
213     public static final boolean ADD_ISFINANCED_FEVICE_DEFAULT = true;
214 
215     private static String TAG = "DevicePolicyManager";
216 
217     private final Context mContext;
218     private final IDevicePolicyManager mService;
219     private final boolean mParentInstance;
220     private final DevicePolicyResourcesManager mResourcesManager;
221 
222 
223     /** @hide */
DevicePolicyManager(Context context, IDevicePolicyManager service)224     public DevicePolicyManager(Context context, IDevicePolicyManager service) {
225         this(context, service, false);
226     }
227 
228     /** @hide */
229     @VisibleForTesting
DevicePolicyManager(Context context, IDevicePolicyManager service, boolean parentInstance)230     protected DevicePolicyManager(Context context, IDevicePolicyManager service,
231             boolean parentInstance) {
232         mContext = context;
233         mService = service;
234         mParentInstance = parentInstance;
235         mResourcesManager = new DevicePolicyResourcesManager(context, service);
236     }
237 
238     /**
239      * Fetch the current value of mService.  This is used in the binder cache lambda
240      * expressions.
241      */
getService()242     private final IDevicePolicyManager getService() {
243         return mService;
244     }
245 
246     /**
247      * Fetch the current value of mParentInstance.  This is used in the binder cache
248      * lambda expressions.
249      */
isParentInstance()250     private final boolean isParentInstance() {
251         return mParentInstance;
252     }
253 
254     /**
255      * Fetch the current value of mContext.  This is used in the binder cache lambda
256      * expressions.
257      */
getContext()258     private final Context getContext() {
259         return mContext;
260     }
261 
262     /** @hide test will override it. */
263     @VisibleForTesting
myUserId()264     protected int myUserId() {
265         return mContext.getUserId();
266     }
267 
268     /**
269      * Activity action: Starts the provisioning flow which sets up a managed profile.
270      *
271      * <p>A managed profile allows data separation for example for the usage of a
272      * device as a personal and corporate device. The user which provisioning is started from and
273      * the managed profile share a launcher.
274      *
275      * <p>This intent will typically be sent by a mobile device management application (MDM).
276      * Provisioning adds a managed profile and sets the MDM as the profile owner who has full
277      * control over the profile.
278      *
279      * <p>It is possible to check if provisioning is allowed or not by querying the method
280      * {@link #isProvisioningAllowed(String)}.
281      *
282      * <p>In version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this intent must contain the
283      * extra {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}.
284      * As of {@link android.os.Build.VERSION_CODES#M}, it should contain the extra
285      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead, although specifying only
286      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported.
287      *
288      * <p>The intent may also contain the following extras:
289      * <ul>
290      * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, optional </li>
291      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional, supported from
292      * {@link android.os.Build.VERSION_CODES#N}</li>
293      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
294      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
295      * <li>{@link #EXTRA_PROVISIONING_SKIP_USER_CONSENT}, optional</li>
296      * <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION}, optional</li>
297      * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
298      * </ul>
299      *
300      * <p>When managed provisioning has completed, broadcasts are sent to the application specified
301      * in the provisioning intent. The
302      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the
303      * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in
304      * the primary profile.
305      *
306      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when managed provisioning has
307      * completed, along with the above broadcast, activity intent
308      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the profile owner.
309      *
310      * <p>If provisioning fails, the managedProfile is removed so the device returns to its
311      * previous state.
312      *
313      * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
314      * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
315      * the provisioning flow was successful, although this doesn't guarantee the full flow will
316      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
317      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
318      *
319      * <p>If a device policy management role holder (DPMRH) updater is present on the device, an
320      * internet connection attempt must be made prior to launching this intent. If internet
321      * connection could not be established, provisioning will fail unless {@link
322      * #EXTRA_PROVISIONING_ALLOW_OFFLINE} is explicitly set to {@code true}, in which case
323      * provisioning will continue without using the DPMRH. If an internet connection has been
324      * established, the DPMRH updater will be launched, which will update the DPMRH if it's not
325      * present on the device, or if it's present and not valid.
326      *
327      * <p>If a DPMRH is present on the device and valid, the provisioning flow will be deferred to
328      * it.
329      */
330     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
331     public static final String ACTION_PROVISION_MANAGED_PROFILE
332         = "android.app.action.PROVISION_MANAGED_PROFILE";
333 
334     /**
335      * Activity action: Starts the provisioning flow which sets up a managed user.
336      *
337      * <p>This intent will typically be sent by a mobile device management application (MDM).
338      * Provisioning configures the user as managed user and sets the MDM as the profile
339      * owner who has full control over the user. Provisioning can only happen before user setup has
340      * been completed. Use {@link #isProvisioningAllowed(String)} to check if provisioning is
341      * allowed.
342      *
343      * <p>The intent contains the following extras:
344      * <ul>
345      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
346      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
347      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
348      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
349      * </ul>
350      *
351      * <p>If provisioning fails, the device returns to its previous state.
352      *
353      * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
354      * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
355      * the provisioning flow was successful, although this doesn't guarantee the full flow will
356      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
357      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
358      *
359      * @hide
360      */
361     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
362     public static final String ACTION_PROVISION_MANAGED_USER
363         = "android.app.action.PROVISION_MANAGED_USER";
364 
365     /**
366      * Activity action: Starts the provisioning flow which sets up a managed device.
367      * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
368      *
369      * <p> During device owner provisioning a device admin app is set as the owner of the device.
370      * A device owner has full control over the device. The device owner can not be modified by the
371      * user.
372      *
373      * <p> A typical use case would be a device that is owned by a company, but used by either an
374      * employee or client.
375      *
376      * <p> An intent with this action can be sent only on an unprovisioned device.
377      * It is possible to check if provisioning is allowed or not by querying the method
378      * {@link #isProvisioningAllowed(String)}.
379      *
380      * <p>The intent contains the following extras:
381      * <ul>
382      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
383      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
384      * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
385      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
386      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
387      * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
388      * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional</li>
389      * </ul>
390      *
391      * <p>When device owner provisioning has completed, an intent of the type
392      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
393      * device owner.
394      *
395      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
396      * completed, along with the above broadcast, activity intent
397      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
398      *
399      * <p>If provisioning fails, the device is factory reset.
400      *
401      * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
402      * of the provisioning flow was successful, although this doesn't guarantee the full flow will
403      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
404      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
405      *
406      * @deprecated to support {@link android.os.Build.VERSION_CODES#S} and later, admin apps must
407      * implement activities with intent filters for the {@link #ACTION_GET_PROVISIONING_MODE} and
408      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} intent actions; using {@link
409      * #ACTION_PROVISION_MANAGED_DEVICE} to start provisioning will cause the provisioning to fail;
410      * to additionally support pre-{@link android.os.Build.VERSION_CODES#S}, admin apps must also
411      * continue to use this constant.
412      */
413     @Deprecated
414     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
415     public static final String ACTION_PROVISION_MANAGED_DEVICE
416         = "android.app.action.PROVISION_MANAGED_DEVICE";
417 
418     /**
419      * Activity action: launch when user provisioning completed, i.e.
420      * {@link #getUserProvisioningState()} returns one of the complete state.
421      *
422      * <p> Please note that the API behavior is not necessarily consistent across various releases,
423      * and devices, as it's contract between SetupWizard and ManagedProvisioning. The default
424      * implementation is that ManagedProvisioning launches SetupWizard in NFC provisioning only.
425      *
426      * <p> The activity must be protected by permission
427      * {@link android.Manifest.permission#BIND_DEVICE_ADMIN}, and the process must hold
428      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE} to be launched.
429      * Only one {@link ComponentName} in the entire system should be enabled, and the rest of the
430      * components are not started by this intent.
431      *
432      * @deprecated Starting from Android 13, the system no longer launches an intent with this
433      * action when user provisioning completes.
434      * @hide
435      */
436     @Deprecated
437     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
438     @SystemApi
439     public static final String ACTION_STATE_USER_SETUP_COMPLETE =
440             "android.app.action.STATE_USER_SETUP_COMPLETE";
441 
442     /**
443      * Activity action: Starts the provisioning flow which sets up a managed device.
444      *
445      * <p>During device owner provisioning, a device admin app is downloaded and set as the owner of
446      * the device. A device owner has full control over the device. The device owner can not be
447      * modified by the user and the only way of resetting the device is via factory reset.
448      *
449      * <p>From version {@link android.os.Build.VERSION_CODES#Q}, the admin app can choose
450      * whether to set up a fully managed device or a managed profile. For the admin app to support
451      * this, it must have an activity with intent filter {@link #ACTION_GET_PROVISIONING_MODE} and
452      * another one with intent filter {@link #ACTION_ADMIN_POLICY_COMPLIANCE}. For example:
453      * <pre>
454      * &lt;activity
455      *     android:name=".GetProvisioningModeActivity"
456      *     android:label="@string/app_name"
457      *     android:permission="android.permission.BIND_DEVICE_ADMIN"&gt;
458      *     &lt;intent-filter&gt;
459      *         &lt;action
460      *             android:name="android.app.action.GET_PROVISIONING_MODE" /&gt;
461      *         &lt;category android:name="android.intent.category.DEFAULT" /&gt;
462      *     &lt;/intent-filter&gt;
463      * &lt;/activity&gt;
464      *
465      * &lt;activity
466      *     android:name=".PolicyComplianceActivity"
467      *     android:label="@string/app_name"
468      *     android:permission="android.permission.BIND_DEVICE_ADMIN"&gt;
469      *     &lt;intent-filter&gt;
470      *         &lt;action
471      *             android:name="android.app.action.ADMIN_POLICY_COMPLIANCE" /&gt;
472      *         &lt;category android:name="android.intent.category.DEFAULT" /&gt;
473      *     &lt;/intent-filter&gt;
474      * &lt;/activity&gt;</pre>
475      *
476      * <p>A typical use case would be a device that is owned by a company, but used by either an
477      * employee or client.
478      *
479      * <p>The provisioning message should be sent to an unprovisioned device.
480      *
481      * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
482      * by a privileged app with the permission
483      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
484      *
485      * <p>If a device policy management role holder (DPMRH) updater is present on the device, an
486      * internet connection attempt must be made prior to launching this intent. If internet
487      * connection could not be established, provisioning will fail unless {@link
488      * #EXTRA_PROVISIONING_ALLOW_OFFLINE} is explicitly set to {@code true}, in which case
489      * provisioning will continue without using the DPMRH. If an internet connection has been
490      * established, the DPMRH updater will be launched via {@link
491      * #ACTION_UPDATE_DEVICE_MANAGEMENT_ROLE_HOLDER}, which will update the DPMRH if it's not
492      * present on the device, or if it's present and not valid.
493      *
494      * <p>A DPMRH is considered valid if it has intent filters for {@link
495      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}, {@link
496      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} and {@link
497      * #ACTION_ROLE_HOLDER_PROVISION_FINALIZATION}.
498      *
499      * <p>If a DPMRH is present on the device and valid, the provisioning flow will be deferred to
500      * it via the {@link #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent.
501      *
502      * <p>The provisioning intent contains the following properties:
503      * <ul>
504      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
505      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
506      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
507      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
508      * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
509      * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
510      * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
511      * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
512      * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
513      * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
514      * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
515      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
516      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
517      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
518      * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
519      * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
520      * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
521      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
522      * <li>{@link #EXTRA_PROVISIONING_USE_MOBILE_DATA}, optional </li>
523      * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional - when not used for
524      * cloud enrollment, NFC or QR provisioning</li>
525      * </ul>
526      *
527      * @hide
528      */
529     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
530     @SystemApi
531     public static final String ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
532             "android.app.action.PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
533 
534     /**
535      * Activity action: Starts the provisioning flow which sets up a financed device.
536      *
537      * <p>During financed device provisioning, a device admin app is downloaded and set as the owner
538      * of the device. A device owner has full control over the device. The device owner can not be
539      * modified by the user.
540      *
541      * <p>A typical use case would be a device that is bought from the reseller through financing
542      * program.
543      *
544      * <p>An intent with this action can be sent only on an unprovisioned device.
545      *
546      * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
547      * by a privileged app with the permission
548      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
549      *
550      * <p>The provisioning intent contains the following properties:
551      * <ul>
552      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
553      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
554      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
555      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
556      * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
557      * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
558      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
559      * </ul>
560      *
561      * <p>Once the device admin app is set as the device owner, the following APIs are available for
562      * managing polices on the device:
563      * <ul>
564      * <li>{@link #isDeviceManaged()}</li>
565      * <li>{@link #isUninstallBlocked(ComponentName, String)}</li>
566      * <li>{@link #setUninstallBlocked(ComponentName, String, boolean)}</li>
567      * <li>{@link #setUserControlDisabledPackages(ComponentName, List)}</li>
568      * <li>{@link #getUserControlDisabledPackages(ComponentName)}</li>
569      * <li>{@link #setOrganizationName(ComponentName, CharSequence)}</li>
570      * <li>{@link #getOrganizationName(ComponentName)} </li>
571      * <li>{@link #setShortSupportMessage(ComponentName, CharSequence)}</li>
572      * <li>{@link #getShortSupportMessage(ComponentName)}</li>
573      * <li>{@link #isBackupServiceEnabled(ComponentName)}</li>
574      * <li>{@link #setBackupServiceEnabled(ComponentName, boolean)}</li>
575      * <li>{@link #isLockTaskPermitted(String)}</li>
576      * <li>{@link #setLockTaskFeatures(ComponentName, int)}, where the following lock task features
577      * can be set (otherwise a {@link SecurityException} will be thrown):</li>
578      * <ul>
579      *     <li>{@link #LOCK_TASK_FEATURE_SYSTEM_INFO}</li>
580      *     <li>{@link #LOCK_TASK_FEATURE_KEYGUARD}</li>
581      *     <li>{@link #LOCK_TASK_FEATURE_HOME}</li>
582      *     <li>{@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}</li>
583      *     <li>{@link #LOCK_TASK_FEATURE_NOTIFICATIONS}</li>
584      *     <li>{@link #LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK}</li>
585      * </ul>
586      * <li>{@link #getLockTaskFeatures(ComponentName)}</li>
587      * <li>{@link #setLockTaskPackages(ComponentName, String[])}</li>
588      * <li>{@link #getLockTaskPackages(ComponentName)}</li>
589      * <li>{@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}</li>
590      * <li>{@link #clearPackagePersistentPreferredActivities(ComponentName, String)} </li>
591      * <li>{@link #wipeData(int)}</li>
592      * <li>{@link #isDeviceOwnerApp(String)}</li>
593      * <li>{@link #clearDeviceOwnerApp(String)}</li>
594      * <li>{@link #setPermissionGrantState(ComponentName, String, String, int)}, where
595      * {@link permission#READ_PHONE_STATE} is the <b>only</b> permission that can be
596      * {@link #PERMISSION_GRANT_STATE_GRANTED}, {@link #PERMISSION_GRANT_STATE_DENIED}, or
597      * {@link #PERMISSION_GRANT_STATE_DEFAULT} and can <b>only</b> be applied to the device admin
598      * app (otherwise a {@link SecurityException} will be thrown)</li>
599      * <li>{@link #getPermissionGrantState(ComponentName, String, String)}, where
600      * {@link permission#READ_PHONE_STATE} is the <b>only</b> permission that can be
601      * used and device admin app is the only package that can be used to retrieve the permission
602      * permission grant state for (otherwise a {@link SecurityException} will be thrown)</li>
603      * <li>{@link #addUserRestriction(ComponentName, String)}, where the following user restrictions
604      * are permitted (otherwise a {@link SecurityException} will be thrown):</li>
605      * <ul>
606      *     <li>{@link UserManager#DISALLOW_ADD_USER}</li>
607      *     <li>{@link UserManager#DISALLOW_DEBUGGING_FEATURES}</li>
608      *     <li>{@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}</li>
609      *     <li>{@link UserManager#DISALLOW_SAFE_BOOT}</li>
610      *     <li>{@link UserManager#DISALLOW_CONFIG_DATE_TIME}</li>
611      *     <li>{@link UserManager#DISALLOW_OUTGOING_CALLS}</li>
612      * </ul>
613      * <li>{@link #getUserRestrictions(ComponentName)}</li>
614      * <li>{@link #clearUserRestriction(ComponentName, String)}, where the following user
615      * restrictions are permitted (otherwise a {@link SecurityException} will be thrown):</li>
616      * <ul>
617      *     <li>{@link UserManager#DISALLOW_ADD_USER}</li>
618      *     <li>{@link UserManager#DISALLOW_DEBUGGING_FEATURES}</li>
619      *     <li>{@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}</li>
620      *     <li>{@link UserManager#DISALLOW_SAFE_BOOT}</li>
621      *     <li>{@link UserManager#DISALLOW_CONFIG_DATE_TIME}</li>
622      *     <li>{@link UserManager#DISALLOW_OUTGOING_CALLS}</li>
623      * </ul>
624      * </ul>
625      *
626      * @hide
627      */
628     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
629     @SystemApi
630     public static final String ACTION_PROVISION_FINANCED_DEVICE =
631             "android.app.action.PROVISION_FINANCED_DEVICE";
632 
633     /**
634      * Activity action: Finalizes management provisioning, should be used after user-setup
635      * has been completed and {@link #getUserProvisioningState()} returns one of:
636      * <ul>
637      * <li>{@link #STATE_USER_SETUP_INCOMPLETE}</li>
638      * <li>{@link #STATE_USER_SETUP_COMPLETE}</li>
639      * <li>{@link #STATE_USER_PROFILE_COMPLETE}</li>
640      * </ul>
641      *
642      * <p>If a device policy management role holder (DPMRH) is present on the device and
643      * valid, the provisioning flow will be deferred to it via the {@link
644      * #ACTION_ROLE_HOLDER_PROVISION_FINALIZATION} intent.
645      *
646      * @hide
647      */
648     @SystemApi
649     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
650     public static final String ACTION_PROVISION_FINALIZATION
651             = "android.app.action.PROVISION_FINALIZATION";
652 
653     /**
654      * Activity action: starts the managed profile provisioning flow inside the device policy
655      * management role holder.
656      *
657      * <p>During the managed profile provisioning flow, the platform-provided provisioning handler
658      * will delegate provisioning to the device policy management role holder, by firing this
659      * intent. Third-party mobile device management applications attempting to fire this intent will
660      * receive a {@link SecurityException}.
661      *
662      * <p>Device policy management role holders are required to have a handler for this intent
663      * action.
664      *
665      * <p>If {@link #EXTRA_ROLE_HOLDER_STATE} is supplied to this intent, it is the responsibility
666      * of the role holder to restore its state from this extra. This is the same {@link Bundle}
667      * which the role holder returns alongside {@link #RESULT_UPDATE_ROLE_HOLDER}.
668      *
669      * <p>A result code of {@link Activity#RESULT_OK} implies that managed profile provisioning
670      * finished successfully. If it did not, a result code of {@link Activity#RESULT_CANCELED}
671      * is used instead.
672      *
673      * @see #ACTION_PROVISION_MANAGED_PROFILE
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_PROFILE =
681             "android.app.action.ROLE_HOLDER_PROVISION_MANAGED_PROFILE";
682 
683     /**
684      * Result code that can be returned by the {@link
685      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link
686      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent handlers if a work
687      * profile has been created.
688      *
689      * @hide
690      */
691     @SystemApi
692     public static final int RESULT_WORK_PROFILE_CREATED = 122;
693 
694     /**
695      * Result code that can be returned by the {@link
696      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link
697      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent handlers if the
698      * device owner was set.
699      *
700      * @hide
701      */
702     @SystemApi
703     public static final int RESULT_DEVICE_OWNER_SET = 123;
704 
705     /**
706      * Activity action: starts the trusted source provisioning flow inside the device policy
707      * management role holder.
708      *
709      * <p>During the trusted source provisioning flow, the platform-provided provisioning handler
710      * will delegate provisioning to the device policy management role holder, by firing this
711      * intent. Third-party mobile device management applications attempting to fire this intent will
712      * receive a {@link SecurityException}.
713      *
714      * <p>Device policy management role holders are required to have a handler for this intent
715      * action.
716      *
717      * <p>If {@link #EXTRA_ROLE_HOLDER_STATE} is supplied to this intent, it is the responsibility
718      * of the role holder to restore its state from this extra. This is the same {@link Bundle}
719      * which the role holder returns alongside {@link #RESULT_UPDATE_ROLE_HOLDER}.
720      *
721      * <p>The result codes can be either {@link #RESULT_WORK_PROFILE_CREATED}, {@link
722      * #RESULT_DEVICE_OWNER_SET} or {@link Activity#RESULT_CANCELED} if provisioning failed.
723      *
724      * @see #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE
725      *
726      * @hide
727      */
728     @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP)
729     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
730     @SystemApi
731     public static final String ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
732             "android.app.action.ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
733 
734     /**
735      * Activity action: starts the provisioning finalization flow inside the device policy
736      * management role holder.
737      *
738      * <p>During the provisioning finalization flow, the platform-provided provisioning handler
739      * will delegate provisioning to the device policy management role holder, by firing this
740      * intent. Third-party mobile device management applications attempting to fire this intent will
741      * receive a {@link SecurityException}.
742      *
743      * <p>Device policy management role holders are required to have a handler for this intent
744      * action.
745      *
746      * <p>This handler forwards the result from the admin app's {@link
747      * #ACTION_ADMIN_POLICY_COMPLIANCE} handler. Result code {@link Activity#RESULT_CANCELED}
748      * implies the provisioning finalization flow has failed.
749      *
750      * @see #ACTION_PROVISION_FINALIZATION
751      *
752      * @hide
753      */
754     @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP)
755     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
756     @SystemApi
757     public static final String ACTION_ROLE_HOLDER_PROVISION_FINALIZATION =
758             "android.app.action.ROLE_HOLDER_PROVISION_FINALIZATION";
759 
760     /**
761      * {@link Activity} result code which can be returned by {@link
762      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} and {@link
763      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} to signal that an update
764      * to the role holder is required.
765      *
766      * <p>This result code can be accompanied by {@link #EXTRA_ROLE_HOLDER_STATE}.
767      *
768      * @hide
769      */
770     @SystemApi
771     public static final int RESULT_UPDATE_ROLE_HOLDER = 2;
772 
773     /**
774      * A {@link PersistableBundle} extra which the role holder can use to describe its own state
775      * when it returns {@link #RESULT_UPDATE_ROLE_HOLDER}.
776      *
777      * <p>If {@link #RESULT_UPDATE_ROLE_HOLDER} was accompanied by this extra, after the update
778      * completes, the role holder's {@link #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} or {@link
779      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent will be relaunched,
780      * which will contain this extra. It is the role holder's responsibility to restore its
781      * state from this extra.
782      *
783      * <p>The content of this {@link PersistableBundle} is entirely up to the role holder. It
784      * should contain anything the role holder needs to restore its original state when it gets
785      * restarted.
786      *
787      * @hide
788      */
789     @SystemApi
790     public static final String EXTRA_ROLE_HOLDER_STATE = "android.app.extra.ROLE_HOLDER_STATE";
791 
792     /**
793      * A {@code boolean} extra which determines whether to force a role holder update, regardless
794      * of any internal conditions {@link #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} might
795      * have.
796      *
797      * <p>This extra can be provided to intents with action {@link
798      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER}.
799      *
800      * @hide
801      */
802     @SystemApi
803     public static final String EXTRA_FORCE_UPDATE_ROLE_HOLDER =
804             "android.app.extra.FORCE_UPDATE_ROLE_HOLDER";
805 
806     /**
807      * A boolean extra indicating whether offline provisioning is allowed.
808      *
809      * <p>For the online provisioning flow, there will be an attempt to download and install
810      * the latest version of the device policy management role holder. The platform will then
811      * delegate provisioning to the device policy management role holder via role holder-specific
812      * provisioning actions.
813      *
814      * <p>For the offline provisioning flow, the provisioning flow will always be handled by
815      * the platform.
816      *
817      * <p>If this extra is set to {@code false}, the provisioning flow will enforce that an
818      * internet connection is established, which will start the online provisioning flow. If an
819      * internet connection cannot be established, provisioning will fail.
820      *
821      * <p>If this extra is set to {@code true}, the provisioning flow will still try to connect to
822      * the internet, but if it fails it will start the offline provisioning flow.
823      *
824      * <p>For T if this extra is set to {@code true}, the provisioning flow will be forced through
825      * the platform and there will be no attempt to download and install the device policy
826      * management role holder.
827      *
828      * <p>The default value is {@code false}.
829      *
830      * <p>This extra is respected when provided via the provisioning intent actions such as {@link
831      * #ACTION_PROVISION_MANAGED_PROFILE}.
832      */
833     public static final String EXTRA_PROVISIONING_ALLOW_OFFLINE =
834             "android.app.extra.PROVISIONING_ALLOW_OFFLINE";
835 
836     /**
837      * A String extra holding a url that specifies the download location of the device policy
838      * management role holder package.
839      *
840      * <p>This is only meant to be used in cases when a specific variant of the role holder package
841      * is needed (such as a debug variant). If not provided, the default variant of the device
842      * manager role holder package is downloaded.
843      *
844      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
845      * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
846      * provisioning via an NFC bump.
847      *
848      * @hide
849      */
850     @SystemApi
851     public static final String EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION =
852             "android.app.extra.PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION";
853 
854     /**
855      * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
856      * android package archive at the download location specified in {@link
857      * #EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION}.
858      *
859      * <p>The signatures of an android package archive can be obtained using
860      * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
861      * {@link android.content.pm.PackageManager#GET_SIGNING_CERTIFICATES}.
862      *
863      * <p>If {@link #EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION} is provided, it must
864      * be accompanied by this extra. The provided checksum must match the checksum of any signature
865      * of the file at the download location. If the checksum does not match an error will be shown
866      * to the user and the user will be asked to factory reset the device.
867      *
868      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
869      * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
870      * provisioning via an NFC bump.
871      *
872      * @hide
873      */
874     @SystemApi
875     public static final String EXTRA_PROVISIONING_ROLE_HOLDER_SIGNATURE_CHECKSUM =
876             "android.app.extra.PROVISIONING_ROLE_HOLDER_SIGNATURE_CHECKSUM";
877 
878     /**
879      * A String extra holding a http cookie header which should be used in the http request to the
880      * url specified in {@link #EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION}.
881      *
882      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
883      * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
884      * provisioning via an NFC bump.
885      *
886      * @hide
887      */
888     @SystemApi
889     public static final String EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_COOKIE_HEADER =
890             "android.app.extra.PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_COOKIE_HEADER";
891 
892     /**
893      * An extra of type {@link android.os.PersistableBundle} that allows the provisioning initiator
894      * to pass data to the device policy management role holder.
895      *
896      * <p>The device policy management role holder will receive this extra via the {@link
897      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent.
898      *
899      * <p>The contents of this extra are up to the contract between the provisioning initiator
900      * and the device policy management role holder.
901      *
902      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
903      * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
904      * provisioning via an NFC bump.
905      *
906      * @hide
907      */
908     @SystemApi
909     public static final String EXTRA_PROVISIONING_ROLE_HOLDER_EXTRAS_BUNDLE =
910             "android.app.extra.PROVISIONING_ROLE_HOLDER_EXTRAS_BUNDLE";
911 
912     /**
913      * A String extra containing the package name of the provisioning initiator.
914      *
915      * <p>Use in an intent with action {@link
916      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}.
917      *
918      * @hide
919      */
920     @SystemApi
921     public static final String EXTRA_ROLE_HOLDER_PROVISIONING_INITIATOR_PACKAGE =
922             "android.app.extra.ROLE_HOLDER_PROVISIONING_INITIATOR_PACKAGE";
923 
924     /**
925      * An {@link Intent} result extra specifying the {@link Intent} to be launched after
926      * provisioning is finalized.
927      *
928      * <p>If {@link #EXTRA_PROVISIONING_SHOULD_LAUNCH_RESULT_INTENT} is set to {@code false},
929      * this result will be supplied as part of the result {@link Intent} for provisioning actions
930      * such as {@link #ACTION_PROVISION_MANAGED_PROFILE}. This result will also be supplied as
931      * part of the result {@link Intent} for the device policy management role holder provisioning
932      * actions.
933      */
934     public static final String EXTRA_RESULT_LAUNCH_INTENT =
935             "android.app.extra.RESULT_LAUNCH_INTENT";
936 
937     /**
938      * A boolean extra that determines whether the provisioning flow should launch the resulting
939      * launch intent, if one is supplied by the device policy management role holder via {@link
940      * #EXTRA_RESULT_LAUNCH_INTENT}. Default value is {@code false}.
941      *
942      * <p>If {@code true}, the resulting intent will be launched by the provisioning flow, if one
943      * is supplied by the device policy management role holder.
944      *
945      * <p>If {@code false}, the resulting intent will be returned as {@link
946      * #EXTRA_RESULT_LAUNCH_INTENT} to the provisioning initiator, if one is supplied by the device
947      * manager role holder. It will be the responsibility of the provisioning initiator to launch
948      * this {@link Intent} after provisioning completes.
949      *
950      * <p>This extra is respected when provided via the provisioning intent actions such as {@link
951      * #ACTION_PROVISION_MANAGED_PROFILE}.
952      */
953     public static final String EXTRA_PROVISIONING_SHOULD_LAUNCH_RESULT_INTENT =
954             "android.app.extra.PROVISIONING_SHOULD_LAUNCH_RESULT_INTENT";
955 
956     /**
957      * Action: Bugreport sharing with device owner has been accepted by the user.
958      *
959      * @hide
960      */
961     public static final String ACTION_BUGREPORT_SHARING_ACCEPTED =
962             "com.android.server.action.REMOTE_BUGREPORT_SHARING_ACCEPTED";
963 
964     /**
965      * Action: Bugreport sharing with device owner has been declined by the user.
966      *
967      * @hide
968      */
969     public static final String ACTION_BUGREPORT_SHARING_DECLINED =
970             "com.android.server.action.REMOTE_BUGREPORT_SHARING_DECLINED";
971 
972     /**
973      * Action: Bugreport has been collected and is dispatched to {@code DevicePolicyManagerService}.
974      *
975      * @hide
976      */
977     public static final String ACTION_REMOTE_BUGREPORT_DISPATCH =
978             "android.intent.action.REMOTE_BUGREPORT_DISPATCH";
979 
980     /**
981      * Extra for shared bugreport's SHA-256 hash.
982      *
983      * @hide
984      */
985     public static final String EXTRA_REMOTE_BUGREPORT_HASH =
986             "android.intent.extra.REMOTE_BUGREPORT_HASH";
987 
988     /**
989      * Extra for shared bugreport's nonce in long integer type.
990      *
991      * @hide
992      */
993     public static final String EXTRA_REMOTE_BUGREPORT_NONCE =
994             "android.intent.extra.REMOTE_BUGREPORT_NONCE";
995 
996     /**
997      * Extra for remote bugreport notification shown type.
998      *
999      * @hide
1000      */
1001     public static final String EXTRA_BUGREPORT_NOTIFICATION_TYPE =
1002             "android.app.extra.bugreport_notification_type";
1003 
1004     /**
1005      * Default value for preferential network service enabling.
1006      *
1007      * @hide
1008      */
1009     public static final boolean PREFERENTIAL_NETWORK_SERVICE_ENABLED_DEFAULT = false;
1010 
1011     /**
1012      * Notification type for a started remote bugreport flow.
1013      *
1014      * @hide
1015      */
1016     public static final int NOTIFICATION_BUGREPORT_STARTED = 1;
1017 
1018     /**
1019      * Notification type for a bugreport that has already been accepted to be shared, but is still
1020      * being taken.
1021      *
1022      * @hide
1023      */
1024     public static final int NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED = 2;
1025 
1026     /**
1027      * Notification type for a bugreport that has been taken and can be shared or declined.
1028      *
1029      * @hide
1030      */
1031     public static final int NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED = 3;
1032 
1033     /**
1034      * Default and maximum timeout in milliseconds after which unlocking with weak auth times out,
1035      * i.e. the user has to use a strong authentication method like password, PIN or pattern.
1036      *
1037      * @hide
1038      */
1039     public static final long DEFAULT_STRONG_AUTH_TIMEOUT_MS = 72 * 60 * 60 * 1000; // 72h
1040 
1041     /**
1042      * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that
1043      * allows a mobile device management application or NFC programmer application which starts
1044      * managed provisioning to pass data to the management application instance after provisioning.
1045      * <p>
1046      * If used with {@link #ACTION_PROVISION_MANAGED_PROFILE} it can be used by the application that
1047      * sends the intent to pass data to itself on the newly created profile.
1048      * If used with {@link #ACTION_PROVISION_MANAGED_DEVICE} it allows passing data to the same
1049      * instance of the app on the primary user.
1050      * Starting from {@link android.os.Build.VERSION_CODES#M}, if used with
1051      * {@link #MIME_TYPE_PROVISIONING_NFC} as part of NFC managed device provisioning, the NFC
1052      * message should contain a stringified {@link java.util.Properties} instance, whose string
1053      * properties will be converted into a {@link android.os.PersistableBundle} and passed to the
1054      * management application after provisioning.
1055      *
1056      * <p>Admin apps will receive this extra in their {@link #ACTION_GET_PROVISIONING_MODE} and
1057      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} intent handlers. Additionally, {@link
1058      * #ACTION_GET_PROVISIONING_MODE} may also return this extra which will then be sent over to
1059      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE}, alongside the original values that were passed to
1060      * {@link #ACTION_GET_PROVISIONING_MODE}.
1061      *
1062      * <p>
1063      * In both cases the application receives the data in
1064      * {@link DeviceAdminReceiver#onProfileProvisioningComplete} via an intent with the action
1065      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}. The bundle is not changed
1066      * during the managed provisioning.
1067      */
1068     public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE =
1069             "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE";
1070 
1071     /**
1072      * A String extra holding the package name of the mobile device management application that
1073      * will be set as the profile owner or device owner.
1074      *
1075      * <p>If an application starts provisioning directly via an intent with action
1076      * {@link #ACTION_PROVISION_MANAGED_PROFILE} this package has to match the package name of the
1077      * application that started provisioning. The package will be set as profile owner in that case.
1078      *
1079      * <p>This package is set as device owner when device owner provisioning is started by an NFC
1080      * message containing an NFC record with MIME type {@link #MIME_TYPE_PROVISIONING_NFC}.
1081      *
1082      * <p> When this extra is set, the application must have exactly one device admin receiver.
1083      * This receiver will be set as the profile or device owner and active admin.
1084      *
1085      * @see DeviceAdminReceiver
1086      * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}. This extra is still
1087      * supported, but only if there is only one device admin receiver in the package that requires
1088      * the permission {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
1089      */
1090     @Deprecated
1091     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME
1092         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME";
1093 
1094     /**
1095      * A ComponentName extra indicating the device admin receiver of the mobile device management
1096      * application that will be set as the profile owner or device owner and active admin.
1097      *
1098      * <p>If an application starts provisioning directly via an intent with action
1099      * {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1100      * {@link #ACTION_PROVISION_MANAGED_DEVICE} the package name of this
1101      * component has to match the package name of the application that started provisioning.
1102      *
1103      * <p>This component is set as device owner and active admin when device owner provisioning is
1104      * started by an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or by an NFC
1105      * message containing an NFC record with MIME type
1106      * {@link #MIME_TYPE_PROVISIONING_NFC}. For the NFC record, the component name must be
1107      * flattened to a string, via {@link ComponentName#flattenToShortString()}.
1108      *
1109      * @see DeviceAdminReceiver
1110      */
1111     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME
1112         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME";
1113 
1114     /**
1115      * An {@link android.accounts.Account} extra holding the account to migrate during managed
1116      * profile provisioning. If the account supplied is present in the primary user, it will be
1117      * copied, along with its credentials to the managed profile and removed from the primary user.
1118      *
1119      * Use with {@link #ACTION_PROVISION_MANAGED_PROFILE}, with managed account provisioning, or
1120      * return as an extra to the intent result from the {@link #ACTION_GET_PROVISIONING_MODE}
1121      * activity.
1122      */
1123 
1124     public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
1125         = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE";
1126 
1127     /**
1128      * Boolean extra to indicate that the migrated account should be kept. This is used in
1129      * conjunction with {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}. If it's set to {@code true},
1130      * the account will not be removed from the primary user after it is migrated to the newly
1131      * created user or profile.
1132      *
1133      * <p> Defaults to {@code false}
1134      *
1135      * <p> Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or set as an extra to the
1136      * intent result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
1137      *
1138      * @see #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
1139      */
1140     public static final String EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION
1141             = "android.app.extra.PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION";
1142 
1143     /**
1144      * @deprecated From {@link android.os.Build.VERSION_CODES#O}, never used while provisioning the
1145      * device.
1146      */
1147     @Deprecated
1148     public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
1149         = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
1150 
1151     /**
1152      * A integer extra indicating the predominant color to show during the provisioning.
1153      * Refer to {@link android.graphics.Color} for how the color is represented.
1154      *
1155      * <p>Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1156      * {@link #ACTION_PROVISION_MANAGED_DEVICE}.
1157      *
1158      * @deprecated Color customization is no longer supported in the provisioning flow.
1159      */
1160     @Deprecated
1161     public static final String EXTRA_PROVISIONING_MAIN_COLOR =
1162              "android.app.extra.PROVISIONING_MAIN_COLOR";
1163 
1164     /**
1165      * A Boolean extra that can be used by the mobile device management application to skip the
1166      * disabling of system apps during provisioning when set to {@code true}.
1167      *
1168      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC}, an intent with action
1169      * {@link #ACTION_PROVISION_MANAGED_PROFILE} that starts profile owner provisioning or
1170      * set as an extra to the intent result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
1171      */
1172     public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED =
1173             "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED";
1174 
1175     /**
1176      * A String extra holding the time zone {@link android.app.AlarmManager} that the device
1177      * will be set to.
1178      *
1179      * <p>Use only for device owner provisioning. This extra can be returned by the admin app when
1180      * performing the admin-integrated provisioning flow as a result of the {@link
1181      * #ACTION_GET_PROVISIONING_MODE} activity.
1182      *
1183      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1184      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1185      */
1186     public static final String EXTRA_PROVISIONING_TIME_ZONE
1187         = "android.app.extra.PROVISIONING_TIME_ZONE";
1188 
1189     /**
1190      * A Long extra holding the wall clock time (in milliseconds) to be set on the device's
1191      * {@link android.app.AlarmManager}.
1192      *
1193      * <p>Use only for device owner provisioning. This extra can be returned by the admin app when
1194      * performing the admin-integrated provisioning flow as a result of the {@link
1195      * #ACTION_GET_PROVISIONING_MODE} activity.
1196      *
1197      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1198      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1199      */
1200     public static final String EXTRA_PROVISIONING_LOCAL_TIME
1201         = "android.app.extra.PROVISIONING_LOCAL_TIME";
1202 
1203     /**
1204      * A String extra holding the {@link java.util.Locale} that the device will be set to.
1205      * Format: xx_yy, where xx is the language code, and yy the country code.
1206      *
1207      * <p>Use only for device owner provisioning. This extra can be returned by the admin app when
1208      * performing the admin-integrated provisioning flow as a result of the {@link
1209      * #ACTION_GET_PROVISIONING_MODE} activity.
1210      *
1211      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1212      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1213      */
1214     public static final String EXTRA_PROVISIONING_LOCALE
1215         = "android.app.extra.PROVISIONING_LOCALE";
1216 
1217     /**
1218      * A String extra holding the ssid of the wifi network that should be used during nfc device
1219      * owner provisioning for downloading the mobile device management application.
1220      *
1221      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1222      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1223      */
1224     public static final String EXTRA_PROVISIONING_WIFI_SSID
1225         = "android.app.extra.PROVISIONING_WIFI_SSID";
1226 
1227     /**
1228      * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
1229      * is hidden or not.
1230      *
1231      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1232      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1233      */
1234     public static final String EXTRA_PROVISIONING_WIFI_HIDDEN
1235         = "android.app.extra.PROVISIONING_WIFI_HIDDEN";
1236 
1237     /**
1238      * A String extra indicating the security type of the wifi network in
1239      * {@link #EXTRA_PROVISIONING_WIFI_SSID} and could be one of {@code NONE}, {@code WPA},
1240      * {@code WEP} or {@code EAP}.
1241      *
1242      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1243      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1244      */
1245     public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE
1246         = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE";
1247 
1248     /**
1249      * A String extra holding the password of the wifi network in
1250      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
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_PASSWORD =
1256             "android.app.extra.PROVISIONING_WIFI_PASSWORD";
1257 
1258     /**
1259      * The EAP method of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
1260      * and could be one of {@code PEAP}, {@code TLS}, {@code TTLS}, {@code PWD}, {@code SIM},
1261      * {@code AKA} or {@code AKA_PRIME}. This is only used if the
1262      * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1263      *
1264      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1265      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1266      */
1267     public static final String EXTRA_PROVISIONING_WIFI_EAP_METHOD =
1268             "android.app.extra.PROVISIONING_WIFI_EAP_METHOD";
1269 
1270     /**
1271      * The phase 2 authentication of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
1272      * and could be one of {@code NONE}, {@code PAP}, {@code MSCHAP}, {@code MSCHAPV2}, {@code GTC},
1273      * {@code SIM}, {@code AKA} or {@code AKA_PRIME}. This is only used if the
1274      * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1275      *
1276      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1277      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1278      */
1279     public static final String EXTRA_PROVISIONING_WIFI_PHASE2_AUTH =
1280             "android.app.extra.PROVISIONING_WIFI_PHASE2_AUTH";
1281 
1282     /**
1283      * The CA certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This should
1284      * be an X.509 certificate Base64 encoded DER format, ie. PEM representation of a certificate
1285      * without header, footer and line breaks. <a href=
1286      * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only
1287      * used if the {@link
1288      * #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1289      *
1290      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1291      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1292      */
1293     public static final String EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE =
1294             "android.app.extra.PROVISIONING_WIFI_CA_CERTIFICATE";
1295 
1296     /**
1297      * The user certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This
1298      * should be an X.509 certificate and private key Base64 encoded DER format, ie. PEM
1299      * representation of a certificate and key without header, footer and line breaks. <a href=
1300      * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only
1301      * used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1302      *
1303      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1304      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1305      */
1306     public static final String EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE =
1307             "android.app.extra.PROVISIONING_WIFI_USER_CERTIFICATE";
1308 
1309     /**
1310      * The identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used
1311      * if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1312      *
1313      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1314      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1315      */
1316     public static final String EXTRA_PROVISIONING_WIFI_IDENTITY =
1317             "android.app.extra.PROVISIONING_WIFI_IDENTITY";
1318 
1319     /**
1320      * The anonymous identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is
1321      * only used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1322      *
1323      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1324      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1325      */
1326 
1327     public static final String EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY =
1328             "android.app.extra.PROVISIONING_WIFI_ANONYMOUS_IDENTITY";
1329     /**
1330      * The domain of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used if
1331      * the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1332      *
1333      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1334      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1335      */
1336     public static final String EXTRA_PROVISIONING_WIFI_DOMAIN =
1337             "android.app.extra.PROVISIONING_WIFI_DOMAIN";
1338 
1339     /**
1340      * A String extra holding the proxy host for the wifi network in
1341      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1342      *
1343      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1344      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1345      */
1346     public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST
1347         = "android.app.extra.PROVISIONING_WIFI_PROXY_HOST";
1348 
1349     /**
1350      * An int extra holding the proxy port for the wifi network in
1351      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1352      *
1353      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1354      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1355      */
1356     public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT
1357         = "android.app.extra.PROVISIONING_WIFI_PROXY_PORT";
1358 
1359     /**
1360      * A String extra holding the proxy bypass for the wifi network in
1361      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1362      *
1363      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1364      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1365      */
1366     public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS
1367         = "android.app.extra.PROVISIONING_WIFI_PROXY_BYPASS";
1368 
1369     /**
1370      * A String extra holding the proxy auto-config (PAC) URL for the wifi network in
1371      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1372      *
1373      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1374      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1375      */
1376     public static final String EXTRA_PROVISIONING_WIFI_PAC_URL
1377         = "android.app.extra.PROVISIONING_WIFI_PAC_URL";
1378 
1379     /**
1380      * A String extra holding a url that specifies the download location of the device admin
1381      * package. When not provided it is assumed that the device admin package is already installed.
1382      *
1383      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1384      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1385      */
1386     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION
1387         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION";
1388 
1389     /**
1390      * A String extra holding the localized name of the organization under management.
1391      *
1392      * The name is displayed only during provisioning.
1393      *
1394      * <p>Use in an intent with action {@link #ACTION_PROVISION_FINANCED_DEVICE}
1395      *
1396      * @hide
1397      */
1398     @SystemApi
1399     public static final String EXTRA_PROVISIONING_ORGANIZATION_NAME =
1400             "android.app.extra.PROVISIONING_ORGANIZATION_NAME";
1401 
1402     /**
1403      * A String extra holding a url to the website of the device provider so the user can open it
1404      * during provisioning. If the url is not HTTPS, an error will be shown.
1405      *
1406      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
1407      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
1408      *
1409      * @hide
1410      */
1411     @SystemApi
1412     public static final String EXTRA_PROVISIONING_SUPPORT_URL =
1413             "android.app.extra.PROVISIONING_SUPPORT_URL";
1414 
1415     /**
1416      * A String extra holding the localized name of the device admin package. It should be the same
1417      * as the app label of the package.
1418      *
1419      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
1420      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
1421      *
1422      * @deprecated This extra is no longer respected in the provisioning flow.
1423      * @hide
1424      */
1425     @Deprecated
1426     @SystemApi
1427     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL =
1428             "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL";
1429 
1430     /**
1431      * A {@link Uri} extra pointing to the app icon of device admin package. This image will be
1432      * shown during the provisioning.
1433      * <h5>The following URI schemes are accepted:</h5>
1434      * <ul>
1435      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1436      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1437      * </ul>
1438      *
1439      * <p> It is the responsibility of the caller to provide an image with a reasonable
1440      * pixel density for the device.
1441      *
1442      * <p> If a content: URI is passed, the intent should have the flag
1443      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1444      * {@link android.content.ClipData} of the intent too.
1445      *
1446      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
1447      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
1448      *
1449      * @deprecated This extra is no longer respected in the provisioning flow.
1450      * @hide
1451      */
1452     @SystemApi
1453     @Deprecated
1454     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI =
1455             "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI";
1456 
1457     /**
1458      * An int extra holding a minimum required version code for the device admin package. If the
1459      * device admin is already installed on the device, it will only be re-downloaded from
1460      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION} if the version of the
1461      * installed package is less than this version code.
1462      *
1463      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1464      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1465      */
1466     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE
1467         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE";
1468 
1469     /**
1470      * A String extra holding a http cookie header which should be used in the http request to the
1471      * url specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
1472      *
1473      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1474      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1475      */
1476     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER
1477         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER";
1478 
1479     /**
1480      * A String extra holding the URL-safe base64 encoded SHA-256 hash of the file at download
1481      * location specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
1482      *
1483      * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM} must be
1484      * present. The provided checksum must match the checksum of the file at the download
1485      * location. If the checksum doesn't match an error will be shown to the user and the user will
1486      * be asked to factory reset the device.
1487      *
1488      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1489      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1490      *
1491      * <p><strong>Note:</strong> for devices running {@link android.os.Build.VERSION_CODES#LOLLIPOP}
1492      * and {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} only SHA-1 hash is supported.
1493      * Starting from {@link android.os.Build.VERSION_CODES#M}, this parameter accepts SHA-256 in
1494      * addition to SHA-1. From {@link android.os.Build.VERSION_CODES#Q}, only SHA-256 hash is
1495      * supported.
1496      */
1497     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM
1498         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM";
1499 
1500     /**
1501      * A boolean extra indicating the admin of a fully-managed device opts out of controlling
1502      * permission grants for sensor-related permissions,
1503      * see {@link #setPermissionGrantState(ComponentName, String, String, int)}.
1504      *
1505      * The default for this extra is {@code false} - by default, the admin of a fully-managed
1506      * device has the ability to grant sensors-related permissions.
1507      *
1508      * <p>Use only for device owner provisioning. This extra can be returned by the
1509      * admin app when performing the admin-integrated provisioning flow as a result of the
1510      * {@link #ACTION_GET_PROVISIONING_MODE} activity.
1511      *
1512      * <p>This extra may also be provided to the admin app via an intent extra for {@link
1513      * #ACTION_GET_PROVISIONING_MODE}.
1514      *
1515      * @see #ACTION_GET_PROVISIONING_MODE
1516      */
1517     public static final String EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT =
1518             "android.app.extra.PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT";
1519 
1520     /**
1521      * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
1522      * android package archive at the download location specified in {@link
1523      * #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
1524      *
1525      * <p>The signatures of an android package archive can be obtained using
1526      * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
1527      * {@link android.content.pm.PackageManager#GET_SIGNATURES}.
1528      *
1529      * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM} must be
1530      * present. The provided checksum must match the checksum of any signature of the file at
1531      * the download location. If the checksum does not match an error will be shown to the user and
1532      * the user will be asked to factory reset the device.
1533      *
1534      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1535      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1536      */
1537     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM
1538         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM";
1539 
1540     /**
1541      * Broadcast Action: This broadcast is sent to indicate that provisioning of a managed profile
1542      * has completed successfully.
1543      *
1544      * <p>The broadcast is limited to the primary profile, to the app specified in the provisioning
1545      * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
1546      *
1547      * <p>This intent will contain the following extras
1548      * <ul>
1549      * <li>{@link Intent#EXTRA_USER}, corresponds to the {@link UserHandle} of the managed
1550      * profile.</li>
1551      * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, corresponds to the account requested to
1552      * be migrated at provisioning time, if any.</li>
1553      * </ul>
1554      */
1555     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1556     public static final String ACTION_MANAGED_PROFILE_PROVISIONED
1557         = "android.app.action.MANAGED_PROFILE_PROVISIONED";
1558 
1559     /**
1560      * Activity action: This activity action is sent to indicate that provisioning of a managed
1561      * profile or managed device has completed successfully. It'll be sent at the same time as
1562      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast but this will be
1563      * delivered faster as it's an activity intent.
1564      *
1565      * <p>The intent is only sent to the new device or profile owner.
1566      *
1567      * @see #ACTION_PROVISION_MANAGED_PROFILE
1568      * @see #ACTION_PROVISION_MANAGED_DEVICE
1569      */
1570     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1571     public static final String ACTION_PROVISIONING_SUCCESSFUL =
1572             "android.app.action.PROVISIONING_SUCCESSFUL";
1573 
1574     /**
1575      * A boolean extra indicating whether device encryption can be skipped as part of device owner
1576      * or managed profile provisioning.
1577      *
1578      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
1579      * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
1580      *
1581      * <p>From {@link android.os.Build.VERSION_CODES#N} onwards, this is also supported for an
1582      * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
1583      *
1584      * <p>This extra can also be returned by the admin app when performing the admin-integrated
1585      * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
1586      */
1587     public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION =
1588              "android.app.extra.PROVISIONING_SKIP_ENCRYPTION";
1589 
1590     /**
1591      * A {@link Uri} extra pointing to a logo image. This image will be shown during the
1592      * provisioning. If this extra is not passed, a default image will be shown.
1593      * <h5>The following URI schemes are accepted:</h5>
1594      * <ul>
1595      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1596      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1597      * </ul>
1598      *
1599      * <p> It is the responsibility of the caller to provide an image with a reasonable
1600      * pixel density for the device.
1601      *
1602      * <p> If a content: URI is passed, the intent should have the flag
1603      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1604      * {@link android.content.ClipData} of the intent too.
1605      *
1606      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1607      * {@link #ACTION_PROVISION_MANAGED_DEVICE}
1608      *
1609      * @deprecated Logo customization is no longer supported in the provisioning flow.
1610      */
1611     @Deprecated
1612     public static final String EXTRA_PROVISIONING_LOGO_URI =
1613             "android.app.extra.PROVISIONING_LOGO_URI";
1614 
1615     /**
1616      * A {@link Bundle}[] extra consisting of list of disclaimer headers and disclaimer contents.
1617      * Each {@link Bundle} must have both {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}
1618      * as disclaimer header, and {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} as disclaimer
1619      * content.
1620      *
1621      * <p> The extra typically contains one disclaimer from the company of mobile device
1622      * management application (MDM), and one disclaimer from the organization.
1623      *
1624      * <p> Call {@link Bundle#putParcelableArray(String, Parcelable[])} to put the {@link Bundle}[]
1625      *
1626      * <p> Maximum 3 key-value pairs can be specified. The rest will be ignored.
1627      *
1628      * <p> Can be used in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}. This
1629      * extra can also be returned by the admin app when performing the admin-integrated
1630      * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
1631      */
1632     public static final String EXTRA_PROVISIONING_DISCLAIMERS =
1633             "android.app.extra.PROVISIONING_DISCLAIMERS";
1634 
1635     /**
1636      * A String extra of localized disclaimer header.
1637      *
1638      * <p> The extra is typically the company name of mobile device management application (MDM)
1639      * or the organization name.
1640      *
1641      * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
1642      *
1643      * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
1644      * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
1645      * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT}. Here is the example:
1646      *
1647      * <pre>
1648      *  &lt;meta-data
1649      *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_HEADER"
1650      *      android:resource="@string/disclaimer_header"
1651      * /&gt;</pre>
1652      */
1653     public static final String EXTRA_PROVISIONING_DISCLAIMER_HEADER =
1654             "android.app.extra.PROVISIONING_DISCLAIMER_HEADER";
1655 
1656     /**
1657      * A {@link Uri} extra pointing to disclaimer content.
1658      *
1659      * <h5>The following URI schemes are accepted:</h5>
1660      * <ul>
1661      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1662      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1663      * </ul>
1664      *
1665      * <p> Styled text is supported in the disclaimer content. The content is parsed by
1666      * {@link android.text.Html#fromHtml(String)} and displayed in a
1667      * {@link android.widget.TextView}.
1668      *
1669      * <p> If a <code>content:</code> URI is passed, URI is passed, the intent should have the flag
1670      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1671      * {@link android.content.ClipData} of the intent too.
1672      *
1673      * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
1674      *
1675      * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
1676      * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
1677      * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}. Here is the example:
1678      *
1679      * <pre>
1680      *  &lt;meta-data
1681      *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_CONTENT"
1682      *      android:resource="@string/disclaimer_content"
1683      * /&gt;</pre>
1684      */
1685     public static final String EXTRA_PROVISIONING_DISCLAIMER_CONTENT =
1686             "android.app.extra.PROVISIONING_DISCLAIMER_CONTENT";
1687 
1688     /**
1689      * A boolean extra indicating if the user consent steps from the provisioning flow should be
1690      * skipped. If unspecified, defaults to {@code false}.
1691      *
1692      * It can only be used by an existing device owner trying to create a managed profile via
1693      * {@link #ACTION_PROVISION_MANAGED_PROFILE}. Otherwise it is ignored.
1694      *
1695      * @deprecated this extra is no longer relevant as device owners cannot create managed profiles
1696      */
1697     @Deprecated
1698     public static final String EXTRA_PROVISIONING_SKIP_USER_CONSENT =
1699             "android.app.extra.PROVISIONING_SKIP_USER_CONSENT";
1700 
1701     /**
1702      * A boolean extra indicating if the education screens from the provisioning flow should be
1703      * skipped. If unspecified, defaults to {@code false}.
1704      *
1705      * <p>This extra can be set in the following ways:
1706      * <ul>
1707      * <li>By the admin app when performing the admin-integrated
1708      * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity</li>
1709      * <li>For managed account enrollment</li>
1710      * </ul>
1711      *
1712      * <p>If the education screens are skipped, it is the admin application's responsibility
1713      * to display its own user education screens.
1714      */
1715     public static final String EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS =
1716             "android.app.extra.PROVISIONING_SKIP_EDUCATION_SCREENS";
1717 
1718     /**
1719      * A boolean extra indicating if mobile data should be used during the provisioning flow
1720      * for downloading the admin app. If {@link #EXTRA_PROVISIONING_WIFI_SSID} is also specified,
1721      * wifi network will be used instead.
1722      *
1723      * <p>Default value is {@code false}.
1724      *
1725      * <p>If this extra is set to {@code true} and {@link #EXTRA_PROVISIONING_WIFI_SSID} is not
1726      * specified, this extra has different behaviour depending on the way provisioning is triggered:
1727      * <ul>
1728      * <li>
1729      *     For provisioning started via a QR code or an NFC tag, mobile data is always used for
1730      *     downloading the admin app.
1731      * </li>
1732      * <li>
1733      *     For all other provisioning methods, a mobile data connection check is made at the start
1734      *     of provisioning. If mobile data is connected at that point, the admin app download will
1735      *     happen using mobile data. If mobile data is not connected at that point, the end-user
1736      *     will be asked to pick a wifi network and the admin app download will proceed over wifi.
1737      * </li>
1738      * </ul>
1739      */
1740     public static final String EXTRA_PROVISIONING_USE_MOBILE_DATA =
1741             "android.app.extra.PROVISIONING_USE_MOBILE_DATA";
1742 
1743     /**
1744      * Possible values for {@link #EXTRA_PROVISIONING_TRIGGER}.
1745      *
1746      * @hide
1747      */
1748     @IntDef(prefix = { "PROVISIONING_TRIGGER_" }, value = {
1749             PROVISIONING_TRIGGER_UNSPECIFIED,
1750             PROVISIONING_TRIGGER_CLOUD_ENROLLMENT,
1751             PROVISIONING_TRIGGER_QR_CODE,
1752             PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER,
1753             PROVISIONING_TRIGGER_MANAGED_ACCOUNT,
1754             PROVISIONING_TRIGGER_NFC
1755     })
1756     @Retention(RetentionPolicy.SOURCE)
1757     public @interface ProvisioningTrigger {}
1758 
1759     /**
1760      * Flags for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES}.
1761      *
1762      * @hide
1763      */
1764     @IntDef(flag = true, prefix = { "FLAG_SUPPORTED_MODES_" }, value = {
1765             FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED,
1766             FLAG_SUPPORTED_MODES_PERSONALLY_OWNED,
1767             FLAG_SUPPORTED_MODES_DEVICE_OWNER
1768     })
1769     @Retention(RetentionPolicy.SOURCE)
1770     public @interface ProvisioningConfiguration {}
1771 
1772     /**
1773      * An int extra holding the provisioning trigger. It could be one of
1774      * {@link #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT}, {@link #PROVISIONING_TRIGGER_QR_CODE},
1775      * {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} or {@link
1776      * #PROVISIONING_TRIGGER_UNSPECIFIED}.
1777      *
1778      * <p>Use in an intent with action {@link
1779      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}.
1780      * @hide
1781      */
1782     @SystemApi
1783     public static final String EXTRA_PROVISIONING_TRIGGER =
1784             "android.app.extra.PROVISIONING_TRIGGER";
1785 
1786     /**
1787      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1788      * trigger has not been specified.
1789      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1790      * @see #PROVISIONING_TRIGGER_QR_CODE
1791      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1792      * @see #PROVISIONING_TRIGGER_NFC
1793      * @hide
1794      */
1795     @SystemApi
1796     public static final int PROVISIONING_TRIGGER_UNSPECIFIED = 0;
1797 
1798     /**
1799      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1800      * trigger is cloud enrollment.
1801      * @see #PROVISIONING_TRIGGER_QR_CODE
1802      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1803      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1804      * @see #PROVISIONING_TRIGGER_NFC
1805      * @hide
1806      */
1807     @SystemApi
1808     public static final int PROVISIONING_TRIGGER_CLOUD_ENROLLMENT = 1;
1809 
1810     /**
1811      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1812      * trigger is the QR code scanner.
1813      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1814      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1815      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1816      * @see #PROVISIONING_TRIGGER_NFC
1817      * @hide
1818      */
1819     @SystemApi
1820     public static final int PROVISIONING_TRIGGER_QR_CODE = 2;
1821 
1822     /**
1823      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1824      * trigger is persistent device owner enrollment.
1825      * <p>This constant is meant to represent a specific type of managed account provisioning which
1826      * provisions a device to a device owner by invoking the standard provisioning flow (where
1827      * the ManagedProvisioning component downloads and installs the admin app), as opposed to
1828      * relying on the provisioning trigger to handle download and install of the admin app.
1829      * <p>As of {@link android.os.Build.VERSION_CODES#S}, this constant is no longer used in favor
1830      * of the more general {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} which handles all managed
1831      * account provisioning types.
1832      * @deprecated Use the broader {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} instead
1833      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1834      * @see #PROVISIONING_TRIGGER_QR_CODE
1835      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1836      * @see #PROVISIONING_TRIGGER_NFC
1837      * @hide
1838      */
1839     @SystemApi
1840     @Deprecated
1841     public static final int PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER = 3;
1842 
1843     /**
1844      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1845      * trigger is managed account enrollment.
1846      * <p>
1847      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1848      * @see #PROVISIONING_TRIGGER_QR_CODE
1849      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1850      * @see #PROVISIONING_TRIGGER_NFC
1851      * @hide
1852      */
1853     @SystemApi
1854     public static final int PROVISIONING_TRIGGER_MANAGED_ACCOUNT = 4;
1855 
1856     /**
1857      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning is
1858      * triggered by tapping an NFC tag.
1859      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1860      * @see #PROVISIONING_TRIGGER_QR_CODE
1861      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1862      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1863      * @hide
1864      */
1865     @SystemApi
1866     public static final int PROVISIONING_TRIGGER_NFC = 5;
1867 
1868     /**
1869      * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that provisioning is
1870      * organization-owned.
1871      *
1872      * <p>Using this value indicates the admin app can only be provisioned in either a
1873      * fully-managed device or a corporate-owned work profile. This will cause the admin app's
1874      * {@link #ACTION_GET_PROVISIONING_MODE} activity to have the {@link
1875      * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
1876      * #PROVISIONING_MODE_MANAGED_PROFILE} and {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}.
1877      *
1878      * <p>This flag can be combined with {@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}. In
1879      * that case, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity will have
1880      * the {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
1881      * #PROVISIONING_MODE_MANAGED_PROFILE}, {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE} and
1882      * {@link #PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE}.
1883      *
1884      * @hide
1885      */
1886     @SystemApi
1887     public static final int FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED = 1;
1888 
1889     /**
1890      * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that provisioning
1891      * is personally-owned.
1892      *
1893      * <p>Using this flag will cause the admin app's {@link #ACTION_GET_PROVISIONING_MODE}
1894      * activity to have the {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra
1895      * contain only {@link #PROVISIONING_MODE_MANAGED_PROFILE}.
1896      *
1897      * <p>Also, if this flag is set, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity
1898      * will not receive the {@link #EXTRA_PROVISIONING_IMEI} and {@link
1899      * #EXTRA_PROVISIONING_SERIAL_NUMBER} extras.
1900      *
1901      * <p>This flag can be combined with {@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}. In
1902      * that case, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity will have the
1903      * {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
1904      * #PROVISIONING_MODE_MANAGED_PROFILE}, {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE} and
1905      * {@link #PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE}.
1906      *
1907      * @hide
1908      */
1909     @SystemApi
1910     public static final int FLAG_SUPPORTED_MODES_PERSONALLY_OWNED = 1 << 1;
1911 
1912     /**
1913      * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that the only
1914      * supported provisioning mode is device owner.
1915      *
1916      * @hide
1917      */
1918     @SystemApi
1919     public static final int FLAG_SUPPORTED_MODES_DEVICE_OWNER = 1 << 2;
1920 
1921     /**
1922      * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and
1923      * {@link #setMinimumRequiredWifiSecurityLevel(int)}: no minimum security level.
1924      *
1925      * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant
1926      * represents the current minimum security level required.
1927      * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the
1928      * minimum security level a Wi-Fi network must meet.
1929      *
1930      * @see #WIFI_SECURITY_PERSONAL
1931      * @see #WIFI_SECURITY_ENTERPRISE_EAP
1932      * @see #WIFI_SECURITY_ENTERPRISE_192
1933      */
1934     public static final int WIFI_SECURITY_OPEN = 0;
1935 
1936     /**
1937      * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and
1938      * {@link #setMinimumRequiredWifiSecurityLevel(int)}: personal network such as WEP, WPA2-PSK.
1939      *
1940      * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant
1941      * represents the current minimum security level required.
1942      * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the
1943      * minimum security level a Wi-Fi network must meet.
1944      *
1945      * @see #WIFI_SECURITY_OPEN
1946      * @see #WIFI_SECURITY_ENTERPRISE_EAP
1947      * @see #WIFI_SECURITY_ENTERPRISE_192
1948      */
1949     public static final int WIFI_SECURITY_PERSONAL = 1;
1950 
1951     /**
1952      * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and
1953      * {@link #setMinimumRequiredWifiSecurityLevel(int)}: enterprise EAP network.
1954      *
1955      * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant
1956      * represents the current minimum security level required.
1957      * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the
1958      * minimum security level a Wi-Fi network must meet.
1959      *
1960      * @see #WIFI_SECURITY_OPEN
1961      * @see #WIFI_SECURITY_PERSONAL
1962      * @see #WIFI_SECURITY_ENTERPRISE_192
1963      */
1964     public static final int WIFI_SECURITY_ENTERPRISE_EAP = 2;
1965 
1966     /**
1967      * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and
1968      * {@link #setMinimumRequiredWifiSecurityLevel(int)}: enterprise 192 bit network.
1969      *
1970      * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant
1971      * represents the current minimum security level required.
1972      * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the
1973      * minimum security level a Wi-Fi network must meet.
1974      *
1975      * @see #WIFI_SECURITY_OPEN
1976      * @see #WIFI_SECURITY_PERSONAL
1977      * @see #WIFI_SECURITY_ENTERPRISE_EAP
1978      */
1979     public static final int WIFI_SECURITY_ENTERPRISE_192 = 3;
1980 
1981     /**
1982      * Possible Wi-Fi minimum security levels
1983      *
1984      * @hide */
1985     @Retention(RetentionPolicy.SOURCE)
1986     @IntDef(prefix = {"WIFI_SECURITY_"}, value = {
1987             WIFI_SECURITY_OPEN,
1988             WIFI_SECURITY_PERSONAL,
1989             WIFI_SECURITY_ENTERPRISE_EAP,
1990             WIFI_SECURITY_ENTERPRISE_192})
1991     public @interface WifiSecurity {}
1992 
1993     /**
1994      * This MIME type is used for starting the device owner provisioning.
1995      *
1996      * <p>During device owner provisioning a device admin app is set as the owner of the device.
1997      * A device owner has full control over the device. The device owner can not be modified by the
1998      * user and the only way of resetting the device is if the device owner app calls a factory
1999      * reset.
2000      *
2001      * <p> A typical use case would be a device that is owned by a company, but used by either an
2002      * employee or client.
2003      *
2004      * <p> The NFC message must be sent to an unprovisioned device.
2005      *
2006      * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
2007      * contains the following properties:
2008      * <ul>
2009      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
2010      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
2011      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
2012      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
2013      * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
2014      * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
2015      * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
2016      * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
2017      * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
2018      * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
2019      * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
2020      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
2021      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
2022      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
2023      * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
2024      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional, supported from {@link
2025      * android.os.Build.VERSION_CODES#M} </li>
2026      * <li>{@link #EXTRA_PROVISIONING_WIFI_EAP_METHOD}, optional, supported from {@link
2027      * android.os.Build.VERSION_CODES#Q}</li>
2028      * <li>{@link #EXTRA_PROVISIONING_WIFI_PHASE2_AUTH}, optional, supported from {@link
2029      * android.os.Build.VERSION_CODES#Q}</li>
2030      * <li>{@link #EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE}, optional, supported from {@link
2031      * android.os.Build.VERSION_CODES#Q}</li>
2032      * <li>{@link #EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE}, optional, supported from {@link
2033      * android.os.Build.VERSION_CODES#Q}</li>
2034      * <li>{@link #EXTRA_PROVISIONING_WIFI_IDENTITY}, optional, supported from {@link
2035      * android.os.Build.VERSION_CODES#Q}</li>
2036      * <li>{@link #EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY}, optional, supported from {@link
2037      * android.os.Build.VERSION_CODES#Q}</li>
2038      * <li>{@link #EXTRA_PROVISIONING_WIFI_DOMAIN}, optional, supported from {@link
2039      * android.os.Build.VERSION_CODES#Q}</li></ul>
2040      *
2041      * <p>
2042      * As of {@link android.os.Build.VERSION_CODES#M}, the properties should contain
2043      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of
2044      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only
2045      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported).
2046      */
2047     public static final String MIME_TYPE_PROVISIONING_NFC
2048         = "application/com.android.managedprovisioning";
2049 
2050     /**
2051      * Activity action: ask the user to add a new device administrator to the system.
2052      * The desired policy is the ComponentName of the policy in the
2053      * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
2054      * bring the user through adding the device administrator to the system (or
2055      * allowing them to reject it).
2056      *
2057      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
2058      * field to provide the user with additional explanation (in addition
2059      * to your component's description) about what is being added.
2060      *
2061      * <p>If your administrator is already active, this will ordinarily return immediately (without
2062      * user intervention).  However, if your administrator has been updated and is requesting
2063      * additional uses-policy flags, the user will be presented with the new list.  New policies
2064      * will not be available to the updated administrator until the user has accepted the new list.
2065      */
2066     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
2067     public static final String ACTION_ADD_DEVICE_ADMIN
2068             = "android.app.action.ADD_DEVICE_ADMIN";
2069 
2070     /**
2071      * @hide
2072      * Activity action: ask the user to add a new device administrator as the profile owner
2073      * for this user. Only system apps can launch this intent.
2074      *
2075      * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN}
2076      * extra field. This will invoke a UI to bring the user through adding the profile owner admin
2077      * to remotely control restrictions on the user.
2078      *
2079      * <p>The intent must be invoked via {@link Activity#startActivityForResult} to receive the
2080      * result of whether or not the user approved the action. If approved, the result will
2081      * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well
2082      * as a profile owner.
2083      *
2084      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
2085      * field to provide the user with additional explanation (in addition
2086      * to your component's description) about what is being added.
2087      *
2088      * <p>If there is already a profile owner active or the caller is not a system app, the
2089      * operation will return a failure result.
2090      */
2091     @SystemApi
2092     public static final String ACTION_SET_PROFILE_OWNER
2093             = "android.app.action.SET_PROFILE_OWNER";
2094 
2095     /**
2096      * @hide
2097      * Name of the profile owner admin that controls the user.
2098      */
2099     @SystemApi
2100     public static final String EXTRA_PROFILE_OWNER_NAME
2101             = "android.app.extra.PROFILE_OWNER_NAME";
2102 
2103     /**
2104      * Broadcast action: send when any policy admin changes a policy.
2105      * This is generally used to find out when a new policy is in effect.
2106      *
2107      * If the profile owner of an organization-owned managed profile changes some user
2108      * restriction explicitly on the parent user, this broadcast will <em>not</em> be
2109      * sent to the parent user.
2110      * @hide
2111      */
2112     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2113     public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
2114             = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
2115 
2116     /**
2117      * Broadcast action: sent when the device owner is set, changed or cleared.
2118      *
2119      * This broadcast is sent only to the primary user.
2120      * @see #ACTION_PROVISION_MANAGED_DEVICE
2121      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
2122      */
2123     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2124     public static final String ACTION_DEVICE_OWNER_CHANGED
2125             = "android.app.action.DEVICE_OWNER_CHANGED";
2126 
2127     /**
2128      * Broadcast action: sent when the factory reset protection (FRP) policy is changed.
2129      *
2130      * @see #setFactoryResetProtectionPolicy
2131      * @hide
2132      */
2133     @RequiresPermission(android.Manifest.permission.MANAGE_FACTORY_RESET_PROTECTION)
2134     @SystemApi
2135     public static final String ACTION_RESET_PROTECTION_POLICY_CHANGED =
2136             "android.app.action.RESET_PROTECTION_POLICY_CHANGED";
2137 
2138     /**
2139      * Broadcast action: sent when there is a location update on a device in lost mode. This
2140      * broadcast is explicitly sent to the device policy controller app only.
2141      *
2142      * @see DevicePolicyManager#sendLostModeLocationUpdate
2143      * @hide
2144      */
2145     @SystemApi
2146     public static final String ACTION_LOST_MODE_LOCATION_UPDATE =
2147             "android.app.action.LOST_MODE_LOCATION_UPDATE";
2148 
2149     /**
2150      * Extra used with {@link #ACTION_LOST_MODE_LOCATION_UPDATE} to send the location of a device
2151      * in lost mode. Value is {@code Location}.
2152      *
2153      * @see DevicePolicyManager#sendLostModeLocationUpdate
2154      * @hide
2155      */
2156     @SystemApi
2157     public static final String EXTRA_LOST_MODE_LOCATION =
2158             "android.app.extra.LOST_MODE_LOCATION";
2159 
2160     /**
2161      * The ComponentName of the administrator component.
2162      *
2163      * @see #ACTION_ADD_DEVICE_ADMIN
2164      */
2165     public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
2166 
2167     /**
2168      * An optional CharSequence providing additional explanation for why the
2169      * admin is being added.
2170      *
2171      * @see #ACTION_ADD_DEVICE_ADMIN
2172      */
2173     public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
2174 
2175     /**
2176      * Constant to indicate the feature of disabling the camera. Used as argument to
2177      * {@link #createAdminSupportIntent(String)}.
2178      * @see #setCameraDisabled(ComponentName, boolean)
2179      */
2180     public static final String POLICY_DISABLE_CAMERA = "policy_disable_camera";
2181 
2182     /**
2183      * Constant to indicate the feature of disabling screen captures. Used as argument to
2184      * {@link #createAdminSupportIntent(String)}.
2185      * @see #setScreenCaptureDisabled(ComponentName, boolean)
2186      */
2187     public static final String POLICY_DISABLE_SCREEN_CAPTURE = "policy_disable_screen_capture";
2188 
2189     /**
2190      * Constant to indicate the feature of suspending app. Use it as the value of
2191      * {@link #EXTRA_RESTRICTION}.
2192      * @hide
2193      */
2194     public static final String POLICY_SUSPEND_PACKAGES = "policy_suspend_packages";
2195 
2196     /**
2197      * A String indicating a specific restricted feature. Can be a user restriction from the
2198      * {@link UserManager}, e.g. {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the values
2199      * {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
2200      * @see #createAdminSupportIntent(String)
2201      * @hide
2202      */
2203     @SystemApi
2204     public static final String EXTRA_RESTRICTION = "android.app.extra.RESTRICTION";
2205 
2206     /**
2207      * Activity action: have the user enter a new password.
2208      *
2209      * <p>For admin apps, this activity should be launched after using {@link
2210      * #setPasswordQuality(ComponentName, int)}, or {@link
2211      * #setPasswordMinimumLength(ComponentName, int)} to have the user enter a new password that
2212      * meets the current requirements. You can use {@link #isActivePasswordSufficient()} to
2213      * determine whether you need to have the user select a new password in order to meet the
2214      * current constraints. Upon being resumed from this activity, you can check the new
2215      * password characteristics to see if they are sufficient.
2216      *
2217      * <p>Non-admin apps can use {@link #getPasswordComplexity()} to check the current screen lock
2218      * complexity, and use this activity with extra {@link #EXTRA_PASSWORD_COMPLEXITY} to suggest
2219      * to users how complex the app wants the new screen lock to be. Note that both {@link
2220      * #getPasswordComplexity()} and the extra {@link #EXTRA_PASSWORD_COMPLEXITY} require the
2221      * calling app to have the permission {@link permission#REQUEST_PASSWORD_COMPLEXITY}.
2222      *
2223      * <p>If the intent is launched from within a managed profile with a profile
2224      * owner built against {@link android.os.Build.VERSION_CODES#M} or before,
2225      * this will trigger entering a new password for the parent of the profile.
2226      * For all other cases it will trigger entering a new password for the user
2227      * or profile it is launched from.
2228      *
2229      * @see #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
2230      */
2231     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
2232     public static final String ACTION_SET_NEW_PASSWORD
2233             = "android.app.action.SET_NEW_PASSWORD";
2234 
2235     /**
2236      * An integer indicating the complexity level of the new password an app would like the user to
2237      * set when launching the action {@link #ACTION_SET_NEW_PASSWORD}.
2238      *
2239      * <p>Must be one of
2240      * <ul>
2241      *     <li>{@link #PASSWORD_COMPLEXITY_HIGH}
2242      *     <li>{@link #PASSWORD_COMPLEXITY_MEDIUM}
2243      *     <li>{@link #PASSWORD_COMPLEXITY_LOW}
2244      *     <li>{@link #PASSWORD_COMPLEXITY_NONE}
2245      * </ul>
2246      *
2247      * <p>If an invalid value is used, it will be treated as {@link #PASSWORD_COMPLEXITY_NONE}.
2248      */
2249     @RequiresPermission(REQUEST_PASSWORD_COMPLEXITY)
2250     public static final String EXTRA_PASSWORD_COMPLEXITY =
2251             "android.app.extra.PASSWORD_COMPLEXITY";
2252 
2253     /**
2254      * Constant for {@link #getPasswordComplexity()} and
2255      * {@link #setRequiredPasswordComplexity(int)}: no password.
2256      *
2257      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
2258      * the exact complexity band the password is in.
2259      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
2260      * band which the password must meet.
2261      */
2262     public static final int PASSWORD_COMPLEXITY_NONE = 0;
2263 
2264     /**
2265      * Constant for {@link #getPasswordComplexity()} and
2266      * {@link #setRequiredPasswordComplexity(int)}.
2267      * Define the low password complexity band as:
2268      * <ul>
2269      * <li>pattern
2270      * <li>PIN with repeating (4444) or ordered (1234, 4321, 2468) sequences
2271      * </ul>
2272      *
2273      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
2274      * the exact complexity band the password is in.
2275      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
2276      * band which the password must meet.
2277      *
2278      * @see #PASSWORD_QUALITY_SOMETHING
2279      * @see #PASSWORD_QUALITY_NUMERIC
2280      */
2281     public static final int PASSWORD_COMPLEXITY_LOW = 0x10000;
2282 
2283     /**
2284      * Constant for {@link #getPasswordComplexity()} and
2285      * {@link #setRequiredPasswordComplexity(int)}.
2286      * Define the medium password complexity band as:
2287      * <ul>
2288      * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
2289      * least 4
2290      * <li>alphabetic, length at least 4
2291      * <li>alphanumeric, length at least 4
2292      * </ul>
2293      *
2294      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
2295      * the exact complexity band the password is in.
2296      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
2297      * band which the password must meet.
2298      *
2299      * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX
2300      * @see #PASSWORD_QUALITY_ALPHABETIC
2301      * @see #PASSWORD_QUALITY_ALPHANUMERIC
2302      */
2303     public static final int PASSWORD_COMPLEXITY_MEDIUM = 0x30000;
2304 
2305     /**
2306      * Constant for {@link #getPasswordComplexity()} and
2307      * {@link #setRequiredPasswordComplexity(int)}.
2308      * Define the high password complexity band as:
2309      * <ul>
2310      * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
2311      * least 8
2312      * <li>alphabetic, length at least 6
2313      * <li>alphanumeric, length at least 6
2314      * </ul>
2315      *
2316      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
2317      * the exact complexity band the password is in.
2318      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
2319      * band which the password must meet.
2320      *
2321      * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX
2322      * @see #PASSWORD_QUALITY_ALPHABETIC
2323      * @see #PASSWORD_QUALITY_ALPHANUMERIC
2324      */
2325     public static final int PASSWORD_COMPLEXITY_HIGH = 0x50000;
2326 
2327     /**
2328      * A boolean extra for {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} requesting that only
2329      * device password requirement is enforced during the parent profile password enrolment flow.
2330      * <p> Normally when enrolling password for the parent profile, both the device-wide password
2331      * requirement (requirement set via {@link #getParentProfileInstance(ComponentName)} instance)
2332      * and the profile password requirement are enforced, if the profile currently does not have a
2333      * separate work challenge. By setting this to {@code true}, profile password requirement is
2334      * explicitly disregarded.
2335      *
2336      * @see #isActivePasswordSufficientForDeviceRequirement()
2337      */
2338     public static final String EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY =
2339             "android.app.extra.DEVICE_PASSWORD_REQUIREMENT_ONLY";
2340 
2341     /**
2342      * @hide
2343      */
2344     @Retention(RetentionPolicy.SOURCE)
2345     @IntDef(prefix = {"PASSWORD_COMPLEXITY_"}, value = {
2346             PASSWORD_COMPLEXITY_NONE,
2347             PASSWORD_COMPLEXITY_LOW,
2348             PASSWORD_COMPLEXITY_MEDIUM,
2349             PASSWORD_COMPLEXITY_HIGH,
2350     })
2351     public @interface PasswordComplexity {}
2352 
2353     /**
2354      * Indicates that nearby streaming is not controlled by policy, which means nearby streaming is
2355      * allowed.
2356      */
2357     public static final int NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY = 0;
2358 
2359     /** Indicates that nearby streaming is disabled. */
2360     public static final int NEARBY_STREAMING_DISABLED = 1;
2361 
2362     /** Indicates that nearby streaming is enabled. */
2363     public static final int NEARBY_STREAMING_ENABLED = 2;
2364 
2365     /**
2366      * Indicates that nearby streaming is enabled only to devices offering a comparable level of
2367      * security, with the same authenticated managed account.
2368      */
2369     public static final int NEARBY_STREAMING_SAME_MANAGED_ACCOUNT_ONLY = 3;
2370 
2371     /**
2372      * @hide
2373      */
2374     @Retention(RetentionPolicy.SOURCE)
2375     @IntDef(prefix = {"NEARBY_STREAMING_"}, value = {
2376         NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY,
2377         NEARBY_STREAMING_DISABLED,
2378         NEARBY_STREAMING_ENABLED,
2379         NEARBY_STREAMING_SAME_MANAGED_ACCOUNT_ONLY,
2380     })
2381     public @interface NearbyStreamingPolicy {}
2382 
2383     /**
2384      * Activity action: have the user enter a new password for the parent profile.
2385      * If the intent is launched from within a managed profile, this will trigger
2386      * entering a new password for the parent of the profile. The caller can optionally
2387      * set {@link #EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY} to only enforce device-wide
2388      * password requirement. In all other cases the behaviour is identical to
2389      * {@link #ACTION_SET_NEW_PASSWORD}.
2390      */
2391     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
2392     public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
2393             = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD";
2394 
2395     /**
2396      * Broadcast action: Tell the status bar to open the device monitoring dialog, e.g. when
2397      * Network logging was enabled and the user tapped the notification.
2398      * <p class="note">This is a protected intent that can only be sent by the system.</p>
2399      * @hide
2400      */
2401     public static final String ACTION_SHOW_DEVICE_MONITORING_DIALOG
2402             = "android.app.action.SHOW_DEVICE_MONITORING_DIALOG";
2403 
2404     /**
2405      * Broadcast Action: Sent after application delegation scopes are changed. The new delegation
2406      * scopes will be sent in an {@code ArrayList<String>} extra identified by the
2407      * {@link #EXTRA_DELEGATION_SCOPES} key.
2408      *
2409      * <p class="note"><b>Note:</b> This is a protected intent that can only be sent by the
2410      * system.</p>
2411      */
2412     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2413     public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED =
2414             "android.app.action.APPLICATION_DELEGATION_SCOPES_CHANGED";
2415 
2416     /**
2417      * An {@code ArrayList<String>} corresponding to the delegation scopes given to an app in the
2418      * {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} broadcast.
2419      */
2420     public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES";
2421 
2422     /**
2423      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
2424      * the parent profile to access intents sent from the managed profile.
2425      * That is, when an app in the managed profile calls
2426      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
2427      * matching activity in the parent profile.
2428      */
2429     public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
2430 
2431     /**
2432      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
2433      * the managed profile to access intents sent from the parent profile.
2434      * That is, when an app in the parent profile calls
2435      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
2436      * matching activity in the managed profile.
2437      */
2438     public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
2439 
2440     /**
2441      * Broadcast action: notify that a new local system update policy has been set by the device
2442      * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
2443      */
2444     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2445     public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
2446             = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
2447 
2448     /**
2449      * Broadcast action from ManagedProvisioning to notify that the latest change to
2450      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has been successfully
2451      * applied (cross profile intent filters updated). Only usesd for CTS tests.
2452      * @hide
2453      */
2454     @SuppressLint("ActionValue")
2455     @TestApi
2456     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2457     public static final String ACTION_DATA_SHARING_RESTRICTION_APPLIED =
2458             "android.app.action.DATA_SHARING_RESTRICTION_APPLIED";
2459 
2460     /**
2461      * Broadcast action: notify that a value of {@link Settings.Global#DEVICE_POLICY_CONSTANTS}
2462      * has been changed.
2463      * @hide
2464      */
2465     @SuppressLint("ActionValue")
2466     @TestApi
2467     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2468     public static final String ACTION_DEVICE_POLICY_CONSTANTS_CHANGED =
2469             "android.app.action.DEVICE_POLICY_CONSTANTS_CHANGED";
2470 
2471     /**
2472      * Permission policy to prompt user for new permission requests for runtime permissions.
2473      * Already granted or denied permissions are not affected by this.
2474      */
2475     public static final int PERMISSION_POLICY_PROMPT = 0;
2476 
2477     /**
2478      * Permission policy to always grant new permission requests for runtime permissions.
2479      * Already granted or denied permissions are not affected by this.
2480      */
2481     public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
2482 
2483     /**
2484      * Permission policy to always deny new permission requests for runtime permissions.
2485      * Already granted or denied permissions are not affected by this.
2486      */
2487     public static final int PERMISSION_POLICY_AUTO_DENY = 2;
2488 
2489     /**
2490      * Possible policy values for permissions.
2491      *
2492      * @hide
2493      */
2494     @IntDef(prefix = { "PERMISSION_GRANT_STATE_" }, value = {
2495             PERMISSION_GRANT_STATE_DEFAULT,
2496             PERMISSION_GRANT_STATE_GRANTED,
2497             PERMISSION_GRANT_STATE_DENIED
2498     })
2499     @Retention(RetentionPolicy.SOURCE)
2500     public @interface PermissionGrantState {}
2501 
2502     /**
2503      * Runtime permission state: The user can manage the permission
2504      * through the UI.
2505      */
2506     public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
2507 
2508     /**
2509      * Runtime permission state: The permission is granted to the app
2510      * and the user cannot manage the permission through the UI.
2511      */
2512     public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
2513 
2514     /**
2515      * Runtime permission state: The permission is denied to the app
2516      * and the user cannot manage the permission through the UI.
2517      */
2518     public static final int PERMISSION_GRANT_STATE_DENIED = 2;
2519 
2520     /**
2521      * Delegation of certificate installation and management. This scope grants access to the
2522      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
2523      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair} APIs.
2524      * This scope also grants the ability to read identifiers that the delegating device owner or
2525      * profile owner can obtain. See {@link #getEnrollmentSpecificId()}.
2526      */
2527     public static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
2528 
2529     /**
2530      * Delegation of application restrictions management. This scope grants access to the
2531      * {@link #setApplicationRestrictions} and {@link #getApplicationRestrictions} APIs.
2532      */
2533     public static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions";
2534 
2535     /**
2536      * Delegation of application uninstall block. This scope grants access to the
2537      * {@link #setUninstallBlocked} API.
2538      */
2539     public static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall";
2540 
2541     /**
2542      * Delegation of permission policy and permission grant state. This scope grants access to the
2543      * {@link #setPermissionPolicy}, {@link #getPermissionGrantState},
2544      * and {@link #setPermissionGrantState} APIs.
2545      */
2546     public static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant";
2547 
2548     /**
2549      * Delegation of package access state. This scope grants access to the
2550      * {@link #isApplicationHidden}, {@link #setApplicationHidden}, {@link #isPackageSuspended}, and
2551      * {@link #setPackagesSuspended} APIs.
2552      */
2553     public static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
2554 
2555     /**
2556      * Delegation for enabling system apps. This scope grants access to the {@link #enableSystemApp}
2557      * API.
2558      */
2559     public static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app";
2560 
2561     /**
2562      * Delegation for installing existing packages. This scope grants access to the
2563      * {@link #installExistingPackage} API.
2564      */
2565     public static final String DELEGATION_INSTALL_EXISTING_PACKAGE =
2566             "delegation-install-existing-package";
2567 
2568     /**
2569      * Delegation of management of uninstalled packages. This scope grants access to the
2570      * {@link #setKeepUninstalledPackages} and {@link #getKeepUninstalledPackages} APIs.
2571      */
2572     public static final String DELEGATION_KEEP_UNINSTALLED_PACKAGES =
2573             "delegation-keep-uninstalled-packages";
2574 
2575     /**
2576      * Grants access to {@link #setNetworkLoggingEnabled}, {@link #isNetworkLoggingEnabled} and
2577      * {@link #retrieveNetworkLogs}. Once granted the delegated app will start receiving
2578      * DelegatedAdminReceiver.onNetworkLogsAvailable() callback, and Device owner or Profile Owner
2579      * will no longer receive the DeviceAdminReceiver.onNetworkLogsAvailable() callback.
2580      * There can be at most one app that has this delegation.
2581      * If another app already had delegated network logging access,
2582      * it will lose the delegation when a new app is delegated.
2583      *
2584      * <p> Device Owner can grant this access since Android 10. Profile Owner of a managed profile
2585      * can grant this access since Android 12.
2586      */
2587     public static final String DELEGATION_NETWORK_LOGGING = "delegation-network-logging";
2588 
2589     /**
2590      * Grants access to selection of KeyChain certificates on behalf of requesting apps.
2591      * Once granted the app will start receiving
2592      * {@link DelegatedAdminReceiver#onChoosePrivateKeyAlias}. The caller (PO/DO) will
2593      * no longer receive {@link DeviceAdminReceiver#onChoosePrivateKeyAlias}.
2594      * There can be at most one app that has this delegation.
2595      * If another app already had delegated certificate selection access,
2596      * it will lose the delegation when a new app is delegated.
2597      * <p> The delegaetd app can also call {@link #grantKeyPairToApp} and
2598      * {@link #revokeKeyPairFromApp} to directly grant KeyCain keys to other apps.
2599      * <p> Can be granted by Device Owner or Profile Owner.
2600      */
2601     public static final String DELEGATION_CERT_SELECTION = "delegation-cert-selection";
2602 
2603     /**
2604      * Grants access to {@link #setSecurityLoggingEnabled}, {@link #isSecurityLoggingEnabled},
2605      * {@link #retrieveSecurityLogs}, and {@link #retrievePreRebootSecurityLogs}. Once granted the
2606      * delegated app will start receiving {@link DelegatedAdminReceiver#onSecurityLogsAvailable}
2607      * callback, and Device owner or Profile Owner will no longer receive the
2608      * {@link DeviceAdminReceiver#onSecurityLogsAvailable} callback. There can be at most one app
2609      * that has this delegation. If another app already had delegated security logging access, it
2610      * will lose the delegation when a new app is delegated.
2611      *
2612      * <p> Can only be granted by Device Owner or Profile Owner of an organization-owned
2613      * managed profile.
2614      */
2615     public static final String DELEGATION_SECURITY_LOGGING = "delegation-security-logging";
2616 
2617     /**
2618      * No management for current user in-effect. This is the default.
2619      * @hide
2620      */
2621     @SystemApi
2622     public static final int STATE_USER_UNMANAGED = 0;
2623 
2624     /**
2625      * Management partially setup, user setup needs to be completed.
2626      * @hide
2627      */
2628     @SystemApi
2629     public static final int STATE_USER_SETUP_INCOMPLETE = 1;
2630 
2631     /**
2632      * Management partially setup, user setup completed.
2633      * @hide
2634      */
2635     @SystemApi
2636     public static final int STATE_USER_SETUP_COMPLETE = 2;
2637 
2638     /**
2639      * Management setup and active on current user.
2640      * @hide
2641      */
2642     @SystemApi
2643     public static final int STATE_USER_SETUP_FINALIZED = 3;
2644 
2645     /**
2646      * Management partially setup on a managed profile.
2647      * @hide
2648      */
2649     @SystemApi
2650     public static final int STATE_USER_PROFILE_COMPLETE = 4;
2651 
2652     /**
2653      * Management setup on a managed profile.
2654      * <p>This is used as an intermediate state after {@link #STATE_USER_PROFILE_COMPLETE} once the
2655      * work profile has been created.
2656      * @hide
2657      */
2658     @SystemApi
2659     public static final int STATE_USER_PROFILE_FINALIZED = 5;
2660 
2661     /**
2662      * @hide
2663      */
2664     @IntDef(prefix = { "STATE_USER_" }, value = {
2665             STATE_USER_UNMANAGED,
2666             STATE_USER_SETUP_INCOMPLETE,
2667             STATE_USER_SETUP_COMPLETE,
2668             STATE_USER_SETUP_FINALIZED,
2669             STATE_USER_PROFILE_COMPLETE,
2670             STATE_USER_PROFILE_FINALIZED
2671     })
2672     @Retention(RetentionPolicy.SOURCE)
2673     public @interface UserProvisioningState {}
2674 
2675     /**
2676      * Result code for {@link #checkProvisioningPrecondition}.
2677      *
2678      * <p>Unknown error code returned  for {@link #ACTION_PROVISION_MANAGED_DEVICE},
2679      * {@link #ACTION_PROVISION_MANAGED_PROFILE} and {@link #ACTION_PROVISION_MANAGED_USER}.
2680      *
2681      * @hide
2682      */
2683     @SystemApi
2684     public static final int STATUS_UNKNOWN_ERROR = -1;
2685 
2686     /**
2687      * Result code for {@link #checkProvisioningPrecondition}.
2688      *
2689      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
2690      * {@link #ACTION_PROVISION_MANAGED_PROFILE} and {@link #ACTION_PROVISION_MANAGED_USER}
2691      * when provisioning is allowed.
2692      *
2693      * @hide
2694      */
2695     @SystemApi
2696     public static final int STATUS_OK = 0;
2697 
2698     /**
2699      * Result code for {@link #checkProvisioningPrecondition}.
2700      *
2701      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the device already has a
2702      * device owner.
2703      *
2704      * @hide
2705      */
2706     @SystemApi
2707     public static final int STATUS_HAS_DEVICE_OWNER = 1;
2708 
2709     /**
2710      * Result code for {@link #checkProvisioningPrecondition}.
2711      *
2712      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the user has a profile owner
2713      *  and for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the profile owner is already set.
2714      *
2715      * @hide
2716      */
2717     @SystemApi
2718     public static final int STATUS_USER_HAS_PROFILE_OWNER = 2;
2719 
2720     /**
2721      * Result code for {@link #checkProvisioningPrecondition}.
2722      *
2723      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the user isn't running.
2724      *
2725      * @hide
2726      */
2727     @SystemApi
2728     public static final int STATUS_USER_NOT_RUNNING = 3;
2729 
2730     /**
2731      * Result code for {@link #checkProvisioningPrecondition}.
2732      *
2733      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} if the device has already been
2734      * setup and for {@link #ACTION_PROVISION_MANAGED_USER} if the user has already been setup.
2735      *
2736      * @hide
2737      */
2738     @SystemApi
2739     public static final int STATUS_USER_SETUP_COMPLETED = 4;
2740 
2741     /**
2742      * Code used to indicate that the device also has a user other than the system user.
2743      *
2744      * @hide
2745      */
2746     @SystemApi
2747     public static final int STATUS_NONSYSTEM_USER_EXISTS = 5;
2748 
2749     /**
2750      * Code used to indicate that device has an account that prevents provisioning.
2751      *
2752      * @hide
2753      */
2754     @SystemApi
2755     public static final int STATUS_ACCOUNTS_NOT_EMPTY = 6;
2756 
2757     /**
2758      * Result code for {@link #checkProvisioningPrecondition}.
2759      *
2760      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} if the user is not a system user.
2761      *
2762      * @hide
2763      */
2764     @SystemApi
2765     public static final int STATUS_NOT_SYSTEM_USER = 7;
2766 
2767     /**
2768      * Result code for {@link #checkProvisioningPrecondition}.
2769      *
2770      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
2771      * {@link #ACTION_PROVISION_MANAGED_USER} when the device is a watch and is already paired.
2772      *
2773      * @hide
2774      */
2775     @SystemApi
2776     public static final int STATUS_HAS_PAIRED = 8;
2777 
2778     /**
2779      * Result code for {@link #checkProvisioningPrecondition}.
2780      *
2781      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} and
2782      * {@link #ACTION_PROVISION_MANAGED_USER} on devices which do not support managed users.
2783      *
2784      * @see {@link PackageManager#FEATURE_MANAGED_USERS}
2785      * @hide
2786      */
2787     @SystemApi
2788     public static final int STATUS_MANAGED_USERS_NOT_SUPPORTED = 9;
2789 
2790     /**
2791      * Result code for {@link #checkProvisioningPrecondition}.
2792      *
2793      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} if the user is a system user and
2794      * for {@link #ACTION_PROVISION_MANAGED_DEVICE} on devices running headless system user mode
2795      * and the user is a system user.
2796      *
2797      * @hide
2798      */
2799     @SystemApi
2800     public static final int STATUS_SYSTEM_USER = 10;
2801 
2802     /**
2803      * Result code for {@link #checkProvisioningPrecondition}.
2804      *
2805      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the user cannot have more
2806      * managed profiles.
2807      *
2808      * @hide
2809      */
2810     @SystemApi
2811     public static final int STATUS_CANNOT_ADD_MANAGED_PROFILE = 11;
2812 
2813     /**
2814      * Result code for {@link #checkProvisioningPrecondition}.
2815      *
2816      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
2817      * {@link #ACTION_PROVISION_MANAGED_PROFILE} on devices which do not support device
2818      * admins.
2819      *
2820      * @hide
2821      */
2822     @SystemApi
2823     public static final int STATUS_DEVICE_ADMIN_NOT_SUPPORTED = 13;
2824 
2825     /**
2826      * TODO (b/137101239): clean up split system user codes
2827      * Result code for {@link #checkProvisioningPrecondition}.
2828      *
2829      * @hide
2830      * @deprecated not used anymore but can't be removed since it's a @TestApi.
2831      */
2832     @Deprecated
2833     @TestApi
2834     public static final int STATUS_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER = 14;
2835 
2836     /**
2837      * Result code for {@link #checkProvisioningPrecondition}.
2838      *
2839      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
2840      * {@link #ACTION_PROVISION_MANAGED_PROFILE} on devices which do not support provisioning.
2841      *
2842      * @hide
2843      */
2844     @SystemApi
2845     public static final int STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS = 15;
2846 
2847     /**
2848      * Result code for {@link #checkProvisioningPrecondition}.
2849      *
2850      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when provisioning a DPC which does
2851      * not support headless system user mode on a headless system user mode device.
2852      *
2853      * @hide
2854      */
2855     @SystemApi
2856     public static final int STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED = 16;
2857 
2858     /**
2859      * Result codes for {@link #checkProvisioningPrecondition} indicating all the provisioning pre
2860      * conditions.
2861      *
2862      * @hide
2863      */
2864     @Retention(RetentionPolicy.SOURCE)
2865     @IntDef(prefix = { "STATUS_" }, value = {
2866             STATUS_UNKNOWN_ERROR, STATUS_OK, STATUS_HAS_DEVICE_OWNER, STATUS_USER_HAS_PROFILE_OWNER,
2867             STATUS_USER_NOT_RUNNING, STATUS_USER_SETUP_COMPLETED, STATUS_NOT_SYSTEM_USER,
2868             STATUS_HAS_PAIRED, STATUS_MANAGED_USERS_NOT_SUPPORTED, STATUS_SYSTEM_USER,
2869             STATUS_CANNOT_ADD_MANAGED_PROFILE, STATUS_DEVICE_ADMIN_NOT_SUPPORTED,
2870             STATUS_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER,
2871             STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS,
2872             STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED
2873     })
2874     public @interface ProvisioningPrecondition {}
2875 
2876     /**
2877      * Disable all configurable SystemUI features during LockTask mode. This includes,
2878      * <ul>
2879      *     <li>system info area in the status bar (connectivity icons, clock, etc.)
2880      *     <li>notifications (including alerts, icons, and the notification shade)
2881      *     <li>Home button
2882      *     <li>Recents button and UI
2883      *     <li>global actions menu (i.e. power button menu)
2884      *     <li>keyguard
2885      * </ul>
2886      *
2887      * @see #setLockTaskFeatures(ComponentName, int)
2888      */
2889     public static final int LOCK_TASK_FEATURE_NONE = 0;
2890 
2891     /**
2892      * Enable the system info area in the status bar during LockTask mode. The system info area
2893      * usually occupies the right side of the status bar (although this can differ across OEMs). It
2894      * includes all system information indicators, such as date and time, connectivity, battery,
2895      * vibration mode, etc.
2896      *
2897      * @see #setLockTaskFeatures(ComponentName, int)
2898      */
2899     public static final int LOCK_TASK_FEATURE_SYSTEM_INFO = 1;
2900 
2901     /**
2902      * Enable notifications during LockTask mode. This includes notification icons on the status
2903      * bar, heads-up notifications, and the expandable notification shade. Note that the Quick
2904      * Settings panel remains disabled. This feature flag can only be used in combination with
2905      * {@link #LOCK_TASK_FEATURE_HOME}. {@link #setLockTaskFeatures(ComponentName, int)}
2906      * throws an {@link IllegalArgumentException} if this feature flag is defined without
2907      * {@link #LOCK_TASK_FEATURE_HOME}.
2908      *
2909      * @see #setLockTaskFeatures(ComponentName, int)
2910      */
2911     public static final int LOCK_TASK_FEATURE_NOTIFICATIONS = 1 << 1;
2912 
2913     /**
2914      * Enable the Home button during LockTask mode. Note that if a custom launcher is used, it has
2915      * to be registered as the default launcher with
2916      * {@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}, and its
2917      * package needs to be allowlisted for LockTask with
2918      * {@link #setLockTaskPackages(ComponentName, String[])}.
2919      *
2920      * @see #setLockTaskFeatures(ComponentName, int)
2921      */
2922     public static final int LOCK_TASK_FEATURE_HOME = 1 << 2;
2923 
2924     /**
2925      * Enable the Overview button and the Overview screen during LockTask mode. This feature flag
2926      * can only be used in combination with {@link #LOCK_TASK_FEATURE_HOME}, and
2927      * {@link #setLockTaskFeatures(ComponentName, int)} will throw an
2928      * {@link IllegalArgumentException} if this feature flag is defined without
2929      * {@link #LOCK_TASK_FEATURE_HOME}.
2930      *
2931      * @see #setLockTaskFeatures(ComponentName, int)
2932      */
2933     public static final int LOCK_TASK_FEATURE_OVERVIEW = 1 << 3;
2934 
2935     /**
2936      * Enable the global actions dialog during LockTask mode. This is the dialog that shows up when
2937      * the user long-presses the power button, for example. Note that the user may not be able to
2938      * power off the device if this flag is not set.
2939      *
2940      * <p>This flag is enabled by default until {@link #setLockTaskFeatures(ComponentName, int)} is
2941      * called for the first time.
2942      *
2943      * @see #setLockTaskFeatures(ComponentName, int)
2944      */
2945     public static final int LOCK_TASK_FEATURE_GLOBAL_ACTIONS = 1 << 4;
2946 
2947     /**
2948      * Enable the keyguard during LockTask mode. Note that if the keyguard is already disabled with
2949      * {@link #setKeyguardDisabled(ComponentName, boolean)}, setting this flag will have no effect.
2950      * If this flag is not set, the keyguard will not be shown even if the user has a lock screen
2951      * credential.
2952      *
2953      * @see #setLockTaskFeatures(ComponentName, int)
2954      */
2955     public static final int LOCK_TASK_FEATURE_KEYGUARD = 1 << 5;
2956 
2957     /**
2958      * Enable blocking of non-allowlisted activities from being started into a locked task.
2959      *
2960      * @see #setLockTaskFeatures(ComponentName, int)
2961      */
2962     public static final int LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK = 1 << 6;
2963 
2964     /**
2965      * Flags supplied to {@link #setLockTaskFeatures(ComponentName, int)}.
2966      *
2967      * @hide
2968      */
2969     @Retention(RetentionPolicy.SOURCE)
2970     @IntDef(flag = true, prefix = { "LOCK_TASK_FEATURE_" }, value = {
2971             LOCK_TASK_FEATURE_NONE,
2972             LOCK_TASK_FEATURE_SYSTEM_INFO,
2973             LOCK_TASK_FEATURE_NOTIFICATIONS,
2974             LOCK_TASK_FEATURE_HOME,
2975             LOCK_TASK_FEATURE_OVERVIEW,
2976             LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
2977             LOCK_TASK_FEATURE_KEYGUARD,
2978             LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK
2979     })
2980     public @interface LockTaskFeature {}
2981 
2982     /**
2983      * Service action: Action for a service that device owner and profile owner can optionally
2984      * own.  If a device owner or a profile owner has such a service, the system tries to keep
2985      * a bound connection to it, in order to keep their process always running.
2986      * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN}
2987      * permission.
2988      */
2989     @SdkConstant(SdkConstantType.SERVICE_ACTION)
2990     public static final String ACTION_DEVICE_ADMIN_SERVICE
2991             = "android.app.action.DEVICE_ADMIN_SERVICE";
2992 
2993     /** @hide */
2994     @Retention(RetentionPolicy.SOURCE)
2995     @IntDef(flag = true, prefix = {"ID_TYPE_"}, value = {
2996         ID_TYPE_BASE_INFO,
2997         ID_TYPE_SERIAL,
2998         ID_TYPE_IMEI,
2999         ID_TYPE_MEID,
3000         ID_TYPE_INDIVIDUAL_ATTESTATION
3001     })
3002     public @interface AttestationIdType {}
3003 
3004     /**
3005      * Specifies that the device should attest its manufacturer details. For use with
3006      * {@link #generateKeyPair}.
3007      *
3008      * @see #generateKeyPair
3009      */
3010     public static final int ID_TYPE_BASE_INFO = 1;
3011 
3012     /**
3013      * Specifies that the device should attest its serial number. For use with
3014      * {@link #generateKeyPair}.
3015      *
3016      * @see #generateKeyPair
3017      */
3018     public static final int ID_TYPE_SERIAL = 2;
3019 
3020     /**
3021      * Specifies that the device should attest its IMEI. For use with {@link #generateKeyPair}.
3022      *
3023      * @see #generateKeyPair
3024      */
3025     public static final int ID_TYPE_IMEI = 4;
3026 
3027     /**
3028      * Specifies that the device should attest its MEID. For use with {@link #generateKeyPair}.
3029      *
3030      * @see #generateKeyPair
3031      */
3032     public static final int ID_TYPE_MEID = 8;
3033 
3034     /**
3035      * Specifies that the device should attest using an individual attestation certificate.
3036      * For use with {@link #generateKeyPair}.
3037      *
3038      * @see #generateKeyPair
3039      */
3040     public static final int ID_TYPE_INDIVIDUAL_ATTESTATION = 16;
3041 
3042     /**
3043      * Service-specific error code for {@link #generateKeyPair}:
3044      * Indicates the call has failed due to StrongBox unavailability.
3045      * @hide
3046      */
3047     public static final int KEY_GEN_STRONGBOX_UNAVAILABLE = 1;
3048 
3049     /**
3050      * Specifies that the calling app should be granted access to the installed credentials
3051      * immediately. Otherwise, access to the credentials will be gated by user approval.
3052      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
3053      *
3054      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
3055      */
3056     public static final int INSTALLKEY_REQUEST_CREDENTIALS_ACCESS = 1;
3057 
3058     /**
3059      * Specifies that a user can select the key via the Certificate Selection prompt.
3060      * If this flag is not set when calling {@link #installKeyPair}, the key can only be granted
3061      * access by implementing {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
3062      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
3063      *
3064      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
3065      */
3066     public static final int INSTALLKEY_SET_USER_SELECTABLE = 2;
3067 
3068     /**
3069      * Broadcast action: sent when the profile owner is set, changed or cleared.
3070      *
3071      * This broadcast is sent only to the user managed by the new profile owner.
3072      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
3073      */
3074     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3075     public static final String ACTION_PROFILE_OWNER_CHANGED =
3076             "android.app.action.PROFILE_OWNER_CHANGED";
3077 
3078     /** @hide */
3079     @Retention(RetentionPolicy.SOURCE)
3080     @IntDef(prefix = {"PRIVATE_DNS_MODE_"}, value = {
3081             PRIVATE_DNS_MODE_UNKNOWN,
3082             PRIVATE_DNS_MODE_OFF,
3083             PRIVATE_DNS_MODE_OPPORTUNISTIC,
3084             PRIVATE_DNS_MODE_PROVIDER_HOSTNAME
3085     })
3086     public @interface PrivateDnsMode {}
3087 
3088     /**
3089      * Specifies that the Private DNS setting is in an unknown state.
3090      */
3091     public static final int PRIVATE_DNS_MODE_UNKNOWN = 0;
3092 
3093     /**
3094      * Specifies that Private DNS was turned off completely.
3095      */
3096     public static final int PRIVATE_DNS_MODE_OFF = 1;
3097 
3098     /**
3099      * Specifies that the device owner requested opportunistic DNS over TLS
3100      */
3101     public static final int PRIVATE_DNS_MODE_OPPORTUNISTIC = 2;
3102 
3103     /**
3104      * Specifies that the device owner configured a specific host to use for Private DNS.
3105      */
3106     public static final int PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = 3;
3107 
3108     /**
3109      * Callback used in {@link #installSystemUpdate} to indicate that there was an error while
3110      * trying to install an update.
3111      */
3112     public abstract static class InstallSystemUpdateCallback {
3113         /** Represents an unknown error while trying to install an update. */
3114         public static final int UPDATE_ERROR_UNKNOWN = 1;
3115 
3116         /** Represents the update file being intended for different OS version. */
3117         public static final int UPDATE_ERROR_INCORRECT_OS_VERSION = 2;
3118 
3119         /**
3120          * Represents the update file being wrong; e.g. payloads are mismatched, or the wrong
3121          * compression method is used.
3122          */
3123         public static final int UPDATE_ERROR_UPDATE_FILE_INVALID = 3;
3124 
3125         /** Represents that the file could not be found. */
3126         public static final int UPDATE_ERROR_FILE_NOT_FOUND = 4;
3127 
3128         /** Represents the battery being too low to apply an update. */
3129         public static final int UPDATE_ERROR_BATTERY_LOW = 5;
3130 
3131         /**
3132          * Method invoked when there was an error while installing an update.
3133          *
3134          * <p>The given error message is not intended to be user-facing. It is intended to be
3135          * reported back to the IT admin to be read.
3136          */
onInstallUpdateError( @nstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage)3137         public void onInstallUpdateError(
3138                 @InstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage) {
3139         }
3140     }
3141 
3142     /**
3143      * @hide
3144      */
3145     @IntDef(prefix = { "UPDATE_ERROR_" }, value = {
3146             InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN,
3147             InstallSystemUpdateCallback.UPDATE_ERROR_INCORRECT_OS_VERSION,
3148             InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
3149             InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
3150             InstallSystemUpdateCallback.UPDATE_ERROR_BATTERY_LOW
3151     })
3152     @Retention(RetentionPolicy.SOURCE)
3153     public @interface InstallUpdateCallbackErrorConstants {}
3154 
3155     /**
3156      * The selected mode has been set successfully. If the mode is
3157      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} then it implies the supplied host is valid
3158      * and reachable.
3159      */
3160     public static final int PRIVATE_DNS_SET_NO_ERROR = 0;
3161 
3162     /**
3163      * If the {@code privateDnsHost} provided was of a valid hostname but that host was found
3164      * to not support DNS-over-TLS.
3165      */
3166     public static final int PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING = 1;
3167 
3168     /**
3169      * General failure to set the Private DNS mode, not due to one of the reasons listed above.
3170      */
3171     public static final int PRIVATE_DNS_SET_ERROR_FAILURE_SETTING = 2;
3172 
3173     /**
3174      * @hide
3175      */
3176     @IntDef(prefix = {"PRIVATE_DNS_SET_"}, value = {
3177             PRIVATE_DNS_SET_NO_ERROR,
3178             PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING,
3179             PRIVATE_DNS_SET_ERROR_FAILURE_SETTING
3180     })
3181     @Retention(RetentionPolicy.SOURCE)
3182     public @interface PrivateDnsModeErrorCodes {}
3183 
3184     /**
3185      * Activity action: Starts the administrator to get the mode for the provisioning.
3186      * This intent may contain the following extras:
3187      * <ul>
3188      *     <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}</li>
3189      *     <li>{@link #EXTRA_PROVISIONING_IMEI}</li>
3190      *     <li>{@link #EXTRA_PROVISIONING_SERIAL_NUMBER}</li>
3191      *     <li>{@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES}</li>
3192      *     <li>{@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT}</li>
3193      * </ul>
3194      *
3195      * <p>The target activity should return one of the following values in
3196      * {@link #EXTRA_PROVISIONING_MODE} as result:
3197      * <ul>
3198      *     <li>{@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}</li>
3199      *     <li>{@link #PROVISIONING_MODE_MANAGED_PROFILE}</li>
3200      * </ul>
3201      *
3202      * <p>If performing fully-managed device provisioning and the admin app desires to show its
3203      * own education screens, the target activity can additionally return
3204      * {@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS} set to <code>true</code>.
3205      *
3206      * <p>The target activity may also return the account that needs to be migrated from primary
3207      * user to managed profile in case of a profile owner provisioning in
3208      * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE} as result.
3209      *
3210      * <p>The target activity may also include the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}
3211      * extra in the intent result. The values of this {@link android.os.PersistableBundle} will be
3212      * sent as an intent extra of the same name to the {@link #ACTION_ADMIN_POLICY_COMPLIANCE}
3213      * activity, along with the values of the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE} extra
3214      * that are already supplied to this activity.
3215      *
3216      * <p>Other extras the target activity may include in the intent result:
3217      * <ul>
3218      *     <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}</li>
3219      *     <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}</li>
3220      *     <li>{@link #EXTRA_PROVISIONING_KEEP_SCREEN_ON}</li>
3221      *     <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION} for work profile
3222      *     provisioning</li>
3223      *     <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED} for work profile
3224      *     provisioning</li>
3225      *     <li>{@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT} for fully-managed
3226      *     device provisioning</li>
3227      *     <li>{@link #EXTRA_PROVISIONING_LOCALE} for fully-managed device provisioning</li>
3228      *     <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} for fully-managed device provisioning</li>
3229      *     <li>{@link #EXTRA_PROVISIONING_TIME_ZONE} for fully-managed device provisioning</li>
3230      * </ul>
3231      *
3232      * @see #ACTION_ADMIN_POLICY_COMPLIANCE
3233      */
3234     public static final String ACTION_GET_PROVISIONING_MODE =
3235             "android.app.action.GET_PROVISIONING_MODE";
3236 
3237     /**
3238      * A string extra holding the IMEI (International Mobile Equipment Identity) of the device.
3239      */
3240     public static final String EXTRA_PROVISIONING_IMEI = "android.app.extra.PROVISIONING_IMEI";
3241 
3242     /**
3243      * A string extra holding the serial number of the device.
3244      */
3245     public static final String EXTRA_PROVISIONING_SERIAL_NUMBER =
3246             "android.app.extra.PROVISIONING_SERIAL_NUMBER";
3247 
3248     /**
3249      * An intent extra holding the provisioning mode returned by the administrator.
3250      * The value of this extra must be one of the values provided in {@link
3251      * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES}, which is provided as an intent extra to
3252      * the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity.
3253      *
3254      * @see #PROVISIONING_MODE_FULLY_MANAGED_DEVICE
3255      * @see #PROVISIONING_MODE_MANAGED_PROFILE
3256      */
3257     public static final String EXTRA_PROVISIONING_MODE =
3258             "android.app.extra.PROVISIONING_MODE";
3259 
3260     /**
3261      * An integer extra indication what provisioning modes should be available for the admin app
3262      * to pick.
3263      *
3264      * <p>The default value is {@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}.
3265      *
3266      * <p>The value of this extra will determine the contents of the {@link
3267      * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array that is passed to the admin app as an
3268      * extra to its {@link #ACTION_GET_PROVISIONING_MODE} activity.
3269      *
3270      * <p>If one of the possible admin app choices is a personally-owned work profile, then the
3271      * IMEI and serial number will not be passed to the admin app's {@link
3272      * #ACTION_GET_PROVISIONING_MODE} activity via the {@link #EXTRA_PROVISIONING_IMEI} and {@link
3273      * #EXTRA_PROVISIONING_SERIAL_NUMBER} respectively.
3274      *
3275      * <p>The allowed flag combinations are:
3276      * <ul>
3277      *     <li>{@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}</li>
3278      *     <li>{@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}</li>
3279      *     <li>{@link #FLAG_SUPPORTED_MODES_DEVICE_OWNER}</li>
3280      *     <li>{@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}
3281      *             | {@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}</li>
3282      * </ul>
3283      *
3284      * <p>This extra is only respected when provided alongside the {@link
3285      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
3286      *
3287      * @see #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED
3288      * @see #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED
3289      * @see #FLAG_SUPPORTED_MODES_DEVICE_OWNER
3290      * @hide
3291      */
3292     @SystemApi
3293     public static final String EXTRA_PROVISIONING_SUPPORTED_MODES =
3294             "android.app.extra.PROVISIONING_SUPPORTED_MODES";
3295 
3296     /**
3297      * A boolean extra which determines whether to skip the ownership disclaimer screen during the
3298      * provisioning flow. The default value is {@code false}.
3299      *
3300      * If the value is {@code true}, the provisioning initiator must display a device ownership
3301      * disclaimer screen similar to that provided in AOSP.
3302      *
3303      * <p>This extra is only respected when provided alongside the {@link
3304      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
3305      *
3306      * @hide
3307      */
3308     @SystemApi
3309     public static final String EXTRA_PROVISIONING_SKIP_OWNERSHIP_DISCLAIMER =
3310             "android.app.extra.PROVISIONING_SKIP_OWNERSHIP_DISCLAIMER";
3311 
3312     /**
3313      * An {@link ArrayList} of {@link Integer} extra specifying the allowed provisioning modes.
3314      * <p>This extra will be passed to the admin app's {@link #ACTION_GET_PROVISIONING_MODE}
3315      * activity, whose result intent must contain {@link #EXTRA_PROVISIONING_MODE} set to one of
3316      * the values in this array.
3317      * <p>If the value set to {@link #EXTRA_PROVISIONING_MODE} is not in the array,
3318      * provisioning will fail.
3319      * @see #PROVISIONING_MODE_MANAGED_PROFILE
3320      * @see #PROVISIONING_MODE_FULLY_MANAGED_DEVICE
3321      */
3322     public static final String EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES =
3323             "android.app.extra.PROVISIONING_ALLOWED_PROVISIONING_MODES";
3324 
3325     /**
3326      * The provisioning mode for fully managed device.
3327      */
3328     public static final int PROVISIONING_MODE_FULLY_MANAGED_DEVICE = 1;
3329 
3330     /**
3331      * The provisioning mode for managed profile.
3332      */
3333     public static final int PROVISIONING_MODE_MANAGED_PROFILE = 2;
3334 
3335     /**
3336      * The provisioning mode for a managed profile on a personal device.
3337      * <p>This mode is only available when the provisioning initiator has explicitly instructed the
3338      * provisioning flow to support managed profile on a personal device provisioning. In that case,
3339      * {@link #PROVISIONING_MODE_MANAGED_PROFILE} corresponds to an organization-owned managed
3340      * profile, whereas this constant corresponds to a personally-owned managed profile.
3341      *
3342      * @see #EXTRA_PROVISIONING_MODE
3343      */
3344     public static final int PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE = 3;
3345 
3346     /**
3347      * A {@code boolean} flag that indicates whether the provisioning flow should return before
3348      * starting the admin app's {@link #ACTION_ADMIN_POLICY_COMPLIANCE} handler. The default value
3349      * is {@code true}.
3350      *
3351      * <p>If this extra is set to {@code true}, then when the provisioning flow returns back to the
3352      * provisioning initiator, provisioning will not be complete. The provisioning initiator can
3353      * use this opportunity to do its own preparatory steps prior to the launch of the admin app's
3354      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} handler. It is the responsibility of the
3355      * provisioning initiator to ensure that the provisioning flow is then resumed and completed.
3356      *
3357      * <p>If this extra is set to {@code false}, then when the provisioning flow returns back to
3358      * the provisioning initiator, provisioning will be complete. Note that device owner
3359      * provisioning is not currently supported for the this scenario.
3360      *
3361      * <p>This extra is only respected when provided alongside the {@link
3362      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
3363      *
3364      * @hide
3365      */
3366     @SystemApi
3367     public static final String EXTRA_PROVISIONING_RETURN_BEFORE_POLICY_COMPLIANCE =
3368             "android.app.extra.PROVISIONING_RETURN_BEFORE_POLICY_COMPLIANCE";
3369 
3370     /**
3371      * A {@code boolean} flag that indicates whether the screen should be on throughout the
3372      * provisioning flow.
3373      *
3374      * <p>This extra can either be passed as an extra to the {@link
3375      * #ACTION_PROVISION_MANAGED_PROFILE} intent, or it can be returned by the
3376      * admin app when performing the admin-integrated provisioning flow as a result of the
3377      * {@link #ACTION_GET_PROVISIONING_MODE} activity.
3378      *
3379      * @deprecated from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the flag wouldn't
3380      * be functional. The screen is kept on throughout the provisioning flow.
3381      */
3382 
3383     @Deprecated
3384     public static final String EXTRA_PROVISIONING_KEEP_SCREEN_ON =
3385             "android.app.extra.PROVISIONING_KEEP_SCREEN_ON";
3386 
3387     /**
3388      * Activity action: Starts the administrator to show policy compliance for the provisioning.
3389      * This action is used any time that the administrator has an opportunity to show policy
3390      * compliance before the end of setup wizard. This could happen as part of the admin-integrated
3391      * provisioning flow (in which case this gets sent after {@link #ACTION_GET_PROVISIONING_MODE}),
3392      * or it could happen during provisioning finalization if the administrator supports
3393      * finalization during setup wizard.
3394      *
3395      * <p>Intents with this action may also be supplied with the {@link
3396      * #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE} extra.
3397      *
3398      * @see #ACTION_GET_PROVISIONING_MODE
3399      */
3400     public static final String ACTION_ADMIN_POLICY_COMPLIANCE =
3401             "android.app.action.ADMIN_POLICY_COMPLIANCE";
3402 
3403     /**
3404      * Activity action: Starts the device policy management role holder updater.
3405      *
3406      * <p>The activity must handle the device policy management role holder update and set the
3407      * intent result. This can include {@link Activity#RESULT_OK} if the update was successful,
3408      * {@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_RECOVERABLE_ERROR} if
3409      * it encounters a problem that may be solved by relaunching it again, {@link
3410      * #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_PROVISIONING_DISABLED} if role holder
3411      * provisioning is disabled, or {@link
3412      * #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR} if it encounters
3413      * any other problem that will not be solved by relaunching it again.
3414      *
3415      * <p>If this activity has additional internal conditions which are not met, it should return
3416      * {@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR}.
3417      *
3418      * @hide
3419      */
3420     @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP)
3421     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3422     @SystemApi
3423     public static final String ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER =
3424             "android.app.action.UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER";
3425 
3426     /**
3427      * Result code that can be returned by the {@link
3428      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} handler if it encounters a problem
3429      * that may be solved by relaunching it again.
3430      *
3431      * @hide
3432      */
3433     @SystemApi
3434     public static final int RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_RECOVERABLE_ERROR =
3435             1;
3436 
3437     /**
3438      * Result code that can be returned by the {@link
3439      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} handler if it encounters a problem that
3440      * will not be solved by relaunching it again.
3441      *
3442      * @hide
3443      */
3444     @SystemApi
3445     public static final int RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR =
3446             2;
3447 
3448     /**
3449      * Result code that can be returned by the {@link
3450      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} handler if role holder provisioning
3451      * is disabled.
3452      *
3453      * @hide
3454      */
3455     @SystemApi
3456     public static final int
3457             RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_PROVISIONING_DISABLED = 3;
3458 
3459     /**
3460      * An {@code int} extra that specifies one of {@link
3461      * #ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING} or {@link
3462      * #ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FALLBACK_TO_PLATFORM_PROVISIONING}.
3463      *
3464      * <p>The failure strategy specifies how the platform should handle a failed device policy
3465      * management role holder update via {@link
3466      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} when {@link
3467      * #EXTRA_PROVISIONING_ALLOW_OFFLINE} is not set or set to {@code false}.
3468      *
3469      * <p>This extra may be supplied as part of the {@link
3470      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} result intent.
3471      *
3472      * <p>Default value is {@link #ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING}.
3473      *
3474      * @hide
3475      */
3476     public static final String EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY =
3477             "android.app.extra.ROLE_HOLDER_UPDATE_FAILURE_STRATEGY";
3478 
3479     /**
3480      * Possible values for {@link #EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY}.
3481      *
3482      * @hide
3483      */
3484     @IntDef(prefix = { "ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_" }, value = {
3485             ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING,
3486             ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FALLBACK_TO_PLATFORM_PROVISIONING
3487     })
3488     @Retention(RetentionPolicy.SOURCE)
3489     public @interface RoleHolderUpdateFailureStrategy {}
3490 
3491     /**
3492      * A value for {@link #EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY} indicating that upon
3493      * failure to update the role holder, provisioning should fail.
3494      *
3495      * @hide
3496      */
3497     public static final int ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING = 1;
3498 
3499     /**
3500      * A value for {@link #EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY} indicating that upon
3501      * failure to update the role holder, provisioning should fallback to be platform-driven.
3502      *
3503      * @hide
3504      */
3505     public static final int ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FALLBACK_TO_PLATFORM_PROVISIONING =
3506             2;
3507 
3508     /**
3509      * An {@code int} extra which contains the result code of the last attempt to update
3510      * the device policy management role holder via {@link
3511      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER}.
3512      *
3513      * <p>This extra is provided to the device policy management role holder via either {@link
3514      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link
3515      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} when started after the role holder
3516      * had previously returned {@link #RESULT_UPDATE_ROLE_HOLDER}.
3517      *
3518      * <p>If the role holder update had failed, the role holder can use the value of this extra to
3519      * make a decision whether to fail the provisioning flow or to carry on with the older version
3520      * of the role holder.
3521      *
3522      * <p>Possible values can be:
3523      * <ul>
3524      *    <li>{@link Activity#RESULT_OK} if the update was successful
3525      *    <li>{@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_RECOVERABLE_ERROR} if it
3526      *    encounters a problem that may be solved by relaunching it again.
3527      *    <li>{@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR} if
3528      *    it encounters a problem that will not be solved by relaunching it again.
3529      *    <li>Any other value returned by {@link
3530      *    #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER}
3531      * </ul>
3532      *
3533      * @hide
3534      */
3535     @SystemApi
3536     public static final String EXTRA_ROLE_HOLDER_UPDATE_RESULT_CODE =
3537             "android.app.extra.ROLE_HOLDER_UPDATE_RESULT_CODE";
3538 
3539     /**
3540      * An {@link Intent} extra which resolves to a custom user consent screen.
3541      *
3542      * <p>If this extra is provided to the device policy management role holder via either {@link
3543      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link
3544      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE}, the device policy management role holder must
3545      * launch this intent which shows the custom user consent screen, replacing its own standard
3546      * consent screen.
3547      *
3548      * <p>If this extra is provided, it is the responsibility of the intent handler to show the
3549      * list of disclaimers which are normally shown by the standard consent screen:
3550      * <ul>
3551      *     <li>Disclaimers set by the IT admin via the {@link #EXTRA_PROVISIONING_DISCLAIMERS}
3552      *     provisioning extra</li>
3553      *     <li>For fully-managed device provisioning, disclaimers defined in system apps via the
3554      *     {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER} and {@link
3555      *     #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} metadata in their manifests</li>
3556      *     <li>General disclaimer relevant to the provisioning mode</li>
3557      * </ul>
3558      *
3559      * <p>When this {@link Intent} is started, the following intent extras will be supplied:
3560      * <ul>
3561      *     <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}</li>
3562      *     <li>{@link #EXTRA_PROVISIONING_MODE}</li>
3563      *     <li>{@link #EXTRA_PROVISIONING_LOCALE}</li>
3564      *     <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME}</li>
3565      *     <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}</li>
3566      *     <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}</li>
3567      * </ul>
3568      *
3569      * <p>If the custom consent screens are granted by the user {@link Activity#RESULT_OK} is
3570      * returned, otherwise {@link Activity#RESULT_CANCELED} is returned. The device policy
3571      * management role holder should ensure that the provisioning flow terminates immediately if
3572      * consent is not granted by the user.
3573      *
3574      * @hide
3575      */
3576     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3577     @SystemApi
3578     public static final String EXTRA_PROVISIONING_ROLE_HOLDER_CUSTOM_USER_CONSENT_INTENT =
3579             "android.app.extra.PROVISIONING_ROLE_HOLDER_CUSTOM_USER_CONSENT_INTENT";
3580 
3581     /**
3582      * Activity action: attempts to establish network connection
3583      *
3584      * <p>This intent can be accompanied by any of the relevant provisioning extras related to
3585      * network connectivity, such as:
3586      * <ul>
3587      *     <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}</li>
3588      *     <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN}</li>
3589      *     <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}</li>
3590      *     <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}</li>
3591      *     <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}</li>
3592      *     <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT}</li>
3593      *     <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}</li>
3594      *     <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}</li>
3595      *     <li>{@code #EXTRA_PROVISIONING_WIFI_EAP_METHOD}</li>
3596      *     <li>{@code #EXTRA_PROVISIONING_WIFI_PHASE2_AUTH}</li>
3597      *     <li>{@code #EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE}</li>
3598      *     <li>{@code #EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE}</li>
3599      *     <li>{@code #EXTRA_PROVISIONING_WIFI_IDENTITY}</li>
3600      *     <li>{@code #EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY}</li>
3601      *     <li>{@code #EXTRA_PROVISIONING_WIFI_DOMAIN}</li>
3602      * </ul>
3603      *
3604      * <p>If there are provisioning extras related to network connectivity, this activity
3605      * attempts to connect to the specified network. Otherwise it prompts the end-user to connect.
3606      *
3607      * <p>This activity is meant to be started by the provisioning initiator prior to starting
3608      * {@link #ACTION_PROVISION_MANAGED_PROFILE} or {@link
3609      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}.
3610      *
3611      * <p>Note that network connectivity is still also handled when provisioning via {@link
3612      * #ACTION_PROVISION_MANAGED_PROFILE} or {@link
3613      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}. {@link
3614      * #ACTION_ESTABLISH_NETWORK_CONNECTION} should only be used in cases when the provisioning
3615      * initiator would like to do some additional logic after the network connectivity step and
3616      * before the start of provisioning.
3617      *
3618      * If network connection is established, {@link Activity#RESULT_OK} will be returned. Otherwise
3619      * the result will be {@link Activity#RESULT_CANCELED}.
3620      *
3621      * @hide
3622      */
3623     @RequiresPermission(android.Manifest.permission.DISPATCH_PROVISIONING_MESSAGE)
3624     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3625     @SystemApi
3626     public static final String ACTION_ESTABLISH_NETWORK_CONNECTION =
3627             "android.app.action.ESTABLISH_NETWORK_CONNECTION";
3628 
3629     /**
3630      * Maximum supported password length. Kind-of arbitrary.
3631      * @hide
3632      */
3633     public static final int MAX_PASSWORD_LENGTH = 16;
3634 
3635     /**
3636      * Service Action: Service implemented by a device owner or profile owner supervision app to
3637      * provide a secondary lockscreen.
3638      * @hide
3639      */
3640     @SystemApi
3641     public static final String ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE =
3642             "android.app.action.BIND_SECONDARY_LOCKSCREEN_SERVICE";
3643 
3644     /**
3645      * Return value for {@link #getPersonalAppsSuspendedReasons} when personal apps are not
3646      * suspended.
3647      */
3648     public static final int PERSONAL_APPS_NOT_SUSPENDED = 0;
3649 
3650     /**
3651      * Flag for {@link #getPersonalAppsSuspendedReasons} return value. Set when personal
3652      * apps are suspended by an admin explicitly via {@link #setPersonalAppsSuspended}.
3653      */
3654     public static final int PERSONAL_APPS_SUSPENDED_EXPLICITLY = 1 << 0;
3655 
3656     /**
3657      * Flag for {@link #getPersonalAppsSuspendedReasons} return value. Set when personal apps are
3658      * suspended by framework because managed profile was off for longer than allowed by policy.
3659      * @see #setManagedProfileMaximumTimeOff
3660      */
3661     public static final int PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT = 1 << 1;
3662 
3663     /**
3664      * @hide
3665      */
3666     @IntDef(flag = true, prefix = { "PERSONAL_APPS_" }, value = {
3667             PERSONAL_APPS_NOT_SUSPENDED,
3668             PERSONAL_APPS_SUSPENDED_EXPLICITLY,
3669             PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT
3670     })
3671     @Retention(RetentionPolicy.SOURCE)
3672     public @interface PersonalAppsSuspensionReason {}
3673 
3674     /**
3675      * The default device owner type for a managed device.
3676      *
3677      * @hide
3678      */
3679     @TestApi
3680     public static final int DEVICE_OWNER_TYPE_DEFAULT = 0;
3681 
3682     /**
3683      * The device owner type for a financed device.
3684      *
3685      * @hide
3686      */
3687     @TestApi
3688     public static final int DEVICE_OWNER_TYPE_FINANCED = 1;
3689 
3690     /**
3691      * Different device owner types for a managed device.
3692      *
3693      * @hide
3694      */
3695     @Retention(RetentionPolicy.SOURCE)
3696     @IntDef(prefix = { "DEVICE_OWNER_TYPE_" }, value = {
3697             DEVICE_OWNER_TYPE_DEFAULT,
3698             DEVICE_OWNER_TYPE_FINANCED
3699     })
3700     public @interface DeviceOwnerType {}
3701 
3702     /** @hide */
3703     @TestApi
3704     public static final int OPERATION_LOCK_NOW = 1;
3705     /** @hide */
3706     @TestApi
3707     public static final int OPERATION_SWITCH_USER = 2;
3708     /** @hide */
3709     @TestApi
3710     public static final int OPERATION_START_USER_IN_BACKGROUND = 3;
3711     /** @hide */
3712     @TestApi
3713     public static final int OPERATION_STOP_USER = 4;
3714     /** @hide */
3715     @TestApi
3716     public static final int OPERATION_CREATE_AND_MANAGE_USER = 5;
3717     /** @hide */
3718     @TestApi
3719     public static final int OPERATION_REMOVE_USER = 6;
3720     /** @hide */
3721     @TestApi
3722     public static final int OPERATION_REBOOT = 7;
3723     /** @hide */
3724     @TestApi
3725     public static final int OPERATION_WIPE_DATA = 8;
3726     /** @hide */
3727     @TestApi
3728     public static final int OPERATION_LOGOUT_USER = 9;
3729     /** @hide */
3730     @TestApi
3731     public static final int OPERATION_SET_USER_RESTRICTION = 10;
3732     /** @hide */
3733     @TestApi
3734     public static final int OPERATION_SET_SYSTEM_SETTING = 11;
3735     /** @hide */
3736     @TestApi
3737     public static final int OPERATION_SET_KEYGUARD_DISABLED = 12;
3738     /** @hide */
3739     @TestApi
3740     public static final int OPERATION_SET_STATUS_BAR_DISABLED = 13;
3741     /** @hide */
3742     @TestApi
3743     public static final int OPERATION_SET_SYSTEM_UPDATE_POLICY = 14;
3744     /** @hide */
3745     @TestApi
3746     public static final int OPERATION_SET_APPLICATION_HIDDEN = 15;
3747     /** @hide */
3748     @TestApi
3749     public static final int OPERATION_SET_APPLICATION_RESTRICTIONS = 16;
3750     /** @hide */
3751     @TestApi
3752     public static final int OPERATION_SET_KEEP_UNINSTALLED_PACKAGES = 17;
3753     /** @hide */
3754     @TestApi
3755     public static final int OPERATION_SET_LOCK_TASK_FEATURES = 18;
3756     /** @hide */
3757     @TestApi
3758     public static final int OPERATION_SET_LOCK_TASK_PACKAGES = 19;
3759     /** @hide */
3760     @TestApi
3761     public static final int OPERATION_SET_PACKAGES_SUSPENDED = 20;
3762     /** @hide */
3763     @TestApi
3764     public static final int OPERATION_SET_TRUST_AGENT_CONFIGURATION = 21;
3765     /** @hide */
3766     @TestApi
3767     public static final int OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES = 22;
3768     /** @hide */
3769     @TestApi
3770     public static final int OPERATION_CLEAR_APPLICATION_USER_DATA = 23;
3771     /** @hide */
3772     @TestApi
3773     public static final int OPERATION_INSTALL_CA_CERT = 24;
3774     /** @hide */
3775     @TestApi
3776     public static final int OPERATION_INSTALL_KEY_PAIR = 25;
3777     /** @hide */
3778     @TestApi
3779     public static final int OPERATION_INSTALL_SYSTEM_UPDATE = 26;
3780     /** @hide */
3781     @TestApi
3782     public static final int OPERATION_REMOVE_ACTIVE_ADMIN = 27;
3783     /** @hide */
3784     @TestApi
3785     public static final int OPERATION_REMOVE_KEY_PAIR = 28;
3786     /** @hide */
3787     @TestApi
3788     public static final int OPERATION_REQUEST_BUGREPORT = 29;
3789     /** @hide */
3790     @TestApi
3791     public static final int OPERATION_SET_ALWAYS_ON_VPN_PACKAGE = 30;
3792     /** @hide */
3793     @TestApi
3794     public static final int OPERATION_SET_CAMERA_DISABLED = 31;
3795     /** @hide */
3796     @TestApi
3797     public static final int OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY = 32;
3798     /** @hide */
3799     @TestApi
3800     public static final int OPERATION_SET_GLOBAL_PRIVATE_DNS = 33;
3801     /** @hide */
3802     @TestApi
3803     public static final int OPERATION_SET_LOGOUT_ENABLED = 34;
3804     /** @hide */
3805     @TestApi
3806     public static final int OPERATION_SET_MASTER_VOLUME_MUTED = 35;
3807     /** @hide */
3808     @TestApi
3809     public static final int OPERATION_SET_OVERRIDE_APNS_ENABLED = 36;
3810     /** @hide */
3811     @TestApi
3812     public static final int OPERATION_SET_PERMISSION_GRANT_STATE = 37;
3813     /** @hide */
3814     @TestApi
3815     public static final int OPERATION_SET_PERMISSION_POLICY = 38;
3816     /** @hide */
3817     @TestApi
3818     public static final int OPERATION_SET_RESTRICTIONS_PROVIDER = 39;
3819     /** @hide */
3820     @TestApi
3821     public static final int OPERATION_UNINSTALL_CA_CERT = 40;
3822 
3823     private static final String PREFIX_OPERATION = "OPERATION_";
3824 
3825     /** @hide */
3826     @IntDef(prefix = PREFIX_OPERATION, value = {
3827             OPERATION_LOCK_NOW,
3828             OPERATION_SWITCH_USER,
3829             OPERATION_START_USER_IN_BACKGROUND,
3830             OPERATION_STOP_USER,
3831             OPERATION_CREATE_AND_MANAGE_USER,
3832             OPERATION_REMOVE_USER,
3833             OPERATION_REBOOT,
3834             OPERATION_WIPE_DATA,
3835             OPERATION_LOGOUT_USER,
3836             OPERATION_SET_USER_RESTRICTION,
3837             OPERATION_SET_SYSTEM_SETTING,
3838             OPERATION_SET_KEYGUARD_DISABLED,
3839             OPERATION_SET_STATUS_BAR_DISABLED,
3840             OPERATION_SET_SYSTEM_UPDATE_POLICY,
3841             OPERATION_SET_APPLICATION_HIDDEN,
3842             OPERATION_SET_APPLICATION_RESTRICTIONS,
3843             OPERATION_SET_KEEP_UNINSTALLED_PACKAGES,
3844             OPERATION_SET_LOCK_TASK_FEATURES,
3845             OPERATION_SET_LOCK_TASK_PACKAGES,
3846             OPERATION_SET_PACKAGES_SUSPENDED,
3847             OPERATION_SET_TRUST_AGENT_CONFIGURATION,
3848             OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES,
3849             OPERATION_CLEAR_APPLICATION_USER_DATA,
3850             OPERATION_INSTALL_CA_CERT,
3851             OPERATION_INSTALL_KEY_PAIR,
3852             OPERATION_INSTALL_SYSTEM_UPDATE,
3853             OPERATION_REMOVE_ACTIVE_ADMIN,
3854             OPERATION_REMOVE_KEY_PAIR,
3855             OPERATION_REQUEST_BUGREPORT,
3856             OPERATION_SET_ALWAYS_ON_VPN_PACKAGE,
3857             OPERATION_SET_CAMERA_DISABLED,
3858             OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY,
3859             OPERATION_SET_GLOBAL_PRIVATE_DNS,
3860             OPERATION_SET_LOGOUT_ENABLED,
3861             OPERATION_SET_MASTER_VOLUME_MUTED,
3862             OPERATION_SET_OVERRIDE_APNS_ENABLED,
3863             OPERATION_SET_PERMISSION_GRANT_STATE,
3864             OPERATION_SET_PERMISSION_POLICY,
3865             OPERATION_SET_RESTRICTIONS_PROVIDER,
3866             OPERATION_UNINSTALL_CA_CERT
3867     })
3868     @Retention(RetentionPolicy.SOURCE)
3869     public static @interface DevicePolicyOperation {
3870     }
3871 
3872     /** @hide */
3873     @TestApi
3874     @NonNull
operationToString(@evicePolicyOperation int operation)3875     public static String operationToString(@DevicePolicyOperation int operation) {
3876         return DebugUtils.constantToString(DevicePolicyManager.class, PREFIX_OPERATION, operation);
3877     }
3878 
3879     private static final String PREFIX_OPERATION_SAFETY_REASON = "OPERATION_SAFETY_REASON_";
3880 
3881     /** @hide */
3882     @IntDef(prefix = PREFIX_OPERATION_SAFETY_REASON, value = {
3883             OPERATION_SAFETY_REASON_NONE,
3884             OPERATION_SAFETY_REASON_DRIVING_DISTRACTION
3885     })
3886     @Retention(RetentionPolicy.SOURCE)
3887     public static @interface OperationSafetyReason {
3888     }
3889 
3890     /** @hide */
3891     @TestApi
3892     public static final int OPERATION_SAFETY_REASON_NONE = -1;
3893 
3894     /**
3895      * Indicates that a {@link UnsafeStateException} was thrown because the operation would distract
3896      * the driver of the vehicle.
3897      */
3898     public static final int OPERATION_SAFETY_REASON_DRIVING_DISTRACTION = 1;
3899 
3900     /**
3901      * Prevent an app from being suspended.
3902      *
3903      * @hide
3904      */
3905     @SystemApi
3906     public static final int EXEMPT_FROM_SUSPENSION =  0;
3907 
3908     /**
3909      * Prevent an app from dismissible notifications. Starting from Android U, notifications with
3910      * the ongoing parameter can be dismissed by a user on an unlocked device. An app with
3911      * this exemption can create non-dismissible notifications.
3912      *
3913      * @hide
3914      */
3915     @SystemApi
3916     public static final int EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS =  1;
3917 
3918     /**
3919      * Allows an application to start an activity while running in the background.
3920      *
3921      * @hide
3922      */
3923     @SystemApi
3924     public static final int EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION = 2;
3925 
3926     /**
3927      * Prevent an app from entering hibernation.
3928      *
3929      * @hide
3930      */
3931     @SystemApi
3932     public static final int EXEMPT_FROM_HIBERNATION =  3;
3933 
3934     /**
3935      * Exempt an app from all power-related restrictions, including app standby and doze.
3936      * In addition, the app will be able to start foreground services from the background,
3937      * and the user will not be able to stop foreground services run by the app.
3938      *
3939      * @hide
3940      */
3941     @SystemApi
3942     public static final int EXEMPT_FROM_POWER_RESTRICTIONS =  4;
3943 
3944     /**
3945      * Exemptions to platform restrictions, given to an application through
3946      * {@link #setApplicationExemptions(String, Set)}.
3947      *
3948      * @hide
3949      */
3950     @IntDef(prefix = { "EXEMPT_FROM_"}, value = {
3951             EXEMPT_FROM_SUSPENSION,
3952             EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS,
3953             EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION,
3954             EXEMPT_FROM_HIBERNATION,
3955             EXEMPT_FROM_POWER_RESTRICTIONS
3956     })
3957     @Retention(RetentionPolicy.SOURCE)
3958     public @interface ApplicationExemptionConstants {}
3959 
3960     /**
3961      * Broadcast action: notify system apps (e.g. settings, SysUI, etc) that the device management
3962      * resources with IDs {@link #EXTRA_RESOURCE_IDS} has been updated, the updated resources can be
3963      * retrieved using {@link DevicePolicyResourcesManager#getDrawable} and
3964      * {@link DevicePolicyResourcesManager#getString}.
3965      *
3966      * <p>This broadcast is sent to registered receivers only.
3967      *
3968      * <p> {@link #EXTRA_RESOURCE_TYPE} will be included to identify the type of resource being
3969      * updated.
3970      */
3971     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3972     public static final String ACTION_DEVICE_POLICY_RESOURCE_UPDATED =
3973             "android.app.action.DEVICE_POLICY_RESOURCE_UPDATED";
3974 
3975     /**
3976      * An {@code int} extra for {@link #ACTION_DEVICE_POLICY_RESOURCE_UPDATED} to indicate the type
3977      * of the resource being updated, the type can be {@link #EXTRA_RESOURCE_TYPE_DRAWABLE} or
3978      * {@link #EXTRA_RESOURCE_TYPE_STRING}
3979      */
3980     public static final String EXTRA_RESOURCE_TYPE =
3981             "android.app.extra.RESOURCE_TYPE";
3982 
3983     /**
3984      * A {@code int} value for {@link #EXTRA_RESOURCE_TYPE} to indicate that a resource of type
3985      * {@link Drawable} is being updated.
3986      */
3987     public static final int EXTRA_RESOURCE_TYPE_DRAWABLE = 1;
3988 
3989     /**
3990      * A {@code int} value for {@link #EXTRA_RESOURCE_TYPE} to indicate that a resource of type
3991      * {@link String} is being updated.
3992      */
3993     public static final int EXTRA_RESOURCE_TYPE_STRING = 2;
3994 
3995     /**
3996      * An integer array extra for {@link #ACTION_DEVICE_POLICY_RESOURCE_UPDATED} to indicate which
3997      * resource IDs (see {@link DevicePolicyResources.Drawables} and
3998      * {@link DevicePolicyResources.Strings}) have been updated.
3999      */
4000     public static final String EXTRA_RESOURCE_IDS =
4001             "android.app.extra.RESOURCE_IDS";
4002 
4003     /**
4004      * Broadcast Action: Broadcast sent to indicate that the device financing state has changed.
4005      *
4006      * <p>This occurs when, for example, a financing kiosk app has been added or removed.
4007      *
4008      * <p>To query the current device financing state see {@link #isDeviceFinanced}.
4009      *
4010      * <p>This will be delivered to the following apps if they include a receiver for this action
4011      * in their manifest:
4012      * <ul>
4013      *     <li>Device owner admins.
4014      *     <li>Organization-owned profile owner admins
4015      *     <li>The supervision app
4016      *     <li>The device management role holder
4017      * </ul>
4018      */
4019     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
4020     @BroadcastBehavior(explicitOnly = true, includeBackground = true)
4021     public static final String ACTION_DEVICE_FINANCING_STATE_CHANGED =
4022             "android.app.admin.action.DEVICE_FINANCING_STATE_CHANGED";
4023 
4024     /** Allow the user to choose whether to enable MTE on the device. */
4025     public static final int MTE_NOT_CONTROLLED_BY_POLICY = 0;
4026 
4027     /**
4028      * Require that MTE be enabled on the device, if supported. Can be set by a device owner or a
4029      * profile owner of an organization-owned managed profile.
4030      */
4031     public static final int MTE_ENABLED = 1;
4032 
4033     /** Require that MTE be disabled on the device. Can be set by a device owner. */
4034     public static final int MTE_DISABLED = 2;
4035 
4036     /** @hide */
4037     @IntDef(
4038             prefix = {"MTE_"},
4039             value = {MTE_ENABLED, MTE_DISABLED, MTE_NOT_CONTROLLED_BY_POLICY})
4040     @Retention(RetentionPolicy.SOURCE)
4041     public static @interface MtePolicy {}
4042 
4043     /**
4044      * Called by a device owner, profile owner of an organization-owned device, to set the Memory
4045      * Tagging Extension (MTE) policy. MTE is a CPU extension that allows to protect against certain
4046      * classes of security problems at a small runtime performance cost overhead.
4047      *
4048      * <p>The MTE policy can only be set to {@link #MTE_DISABLED} if called by a device owner.
4049      * Otherwise a {@link SecurityException} will be thrown.
4050      *
4051      * <p>The device needs to be rebooted to apply changes to the MTE policy.
4052      *
4053      * @throws SecurityException if caller is not permitted to set Mte policy
4054      * @throws UnsupportedOperationException if the device does not support MTE
4055      * @param policy the MTE policy to be set
4056      */
4057     @RequiresPermission(value = MANAGE_DEVICE_POLICY_MTE, conditional = true)
setMtePolicy(@tePolicy int policy)4058     public void setMtePolicy(@MtePolicy int policy) {
4059         throwIfParentInstance("setMtePolicy");
4060         if (mService != null) {
4061             try {
4062                 mService.setMtePolicy(policy, mContext.getPackageName());
4063             } catch (RemoteException e) {
4064                 throw e.rethrowFromSystemServer();
4065             }
4066         }
4067     }
4068 
4069     /**
4070      * Called by a device owner, profile owner of an organization-owned device to
4071      * get the Memory Tagging Extension (MTE) policy
4072      *
4073      * <a href="https://source.android.com/docs/security/test/memory-safety/arm-mte">
4074      * Learn more about MTE</a>
4075      *
4076      * @throws SecurityException if caller is not permitted to set Mte policy
4077      * @return the currently set MTE policy
4078      */
4079     @RequiresPermission(value = MANAGE_DEVICE_POLICY_MTE, conditional = true)
getMtePolicy()4080     public @MtePolicy int getMtePolicy() {
4081         throwIfParentInstance("setMtePolicy");
4082         if (mService != null) {
4083             try {
4084                 return mService.getMtePolicy(mContext.getPackageName());
4085             } catch (RemoteException e) {
4086                 throw e.rethrowFromSystemServer();
4087             }
4088         }
4089         return MTE_NOT_CONTROLLED_BY_POLICY;
4090     }
4091 
4092     /**
4093      * This object is a single place to tack on invalidation and disable calls.  All
4094      * binder caches in this class derive from this Config, so all can be invalidated or
4095      * disabled through this Config.
4096      */
4097     private static final IpcDataCache.Config sDpmCaches =
4098             new IpcDataCache.Config(8, IpcDataCache.MODULE_SYSTEM, "DevicePolicyManagerCaches");
4099 
4100     /** @hide */
invalidateBinderCaches()4101     public static void invalidateBinderCaches() {
4102         sDpmCaches.invalidateCache();
4103     }
4104 
4105     /** @hide */
disableLocalCaches()4106     public static void disableLocalCaches() {
4107         sDpmCaches.disableAllForCurrentProcess();
4108     }
4109 
4110     /** @hide */
4111     @NonNull
4112     @TestApi
operationSafetyReasonToString(@perationSafetyReason int reason)4113     public static String operationSafetyReasonToString(@OperationSafetyReason int reason) {
4114         return DebugUtils.constantToString(DevicePolicyManager.class,
4115                 PREFIX_OPERATION_SAFETY_REASON, reason);
4116     }
4117 
4118     /** @hide */
isValidOperationSafetyReason(@perationSafetyReason int reason)4119     public static boolean isValidOperationSafetyReason(@OperationSafetyReason int reason) {
4120         return reason == OPERATION_SAFETY_REASON_DRIVING_DISTRACTION;
4121     }
4122 
4123     /**
4124      * Checks if it's safe to run operations that can be affected by the given {@code reason}.
4125      *
4126      * <p><b>Note:</b> notice that the operation safety state might change between the time this
4127      * method returns and the operation's method is called, so calls to the latter could still throw
4128      * a {@link UnsafeStateException} even when this method returns {@code true}.
4129      *
4130      * @param reason currently, only supported reason is
4131      * {@link #OPERATION_SAFETY_REASON_DRIVING_DISTRACTION}.
4132      *
4133      * @return whether it's safe to run operations that can be affected by the given {@code reason}.
4134      */
4135     // TODO(b/173541467): should it throw SecurityException if caller is not admin?
isSafeOperation(@perationSafetyReason int reason)4136     public boolean isSafeOperation(@OperationSafetyReason int reason) {
4137         throwIfParentInstance("isSafeOperation");
4138         if (mService == null) return false;
4139 
4140         try {
4141             return mService.isSafeOperation(reason);
4142         } catch (RemoteException e) {
4143             throw e.rethrowFromSystemServer();
4144         }
4145     }
4146 
4147     /**
4148      * Acknoledges that the new managed user disclaimer was viewed by the (human) user
4149      * so that {@link #ACTION_SHOW_NEW_USER_DISCLAIMER broadcast} is not sent again the next time
4150      * this user is switched to.
4151      *
4152      * @hide
4153      */
4154     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
4155             android.Manifest.permission.INTERACT_ACROSS_USERS})
4156     @UserHandleAware
4157     @TestApi
4158     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
acknowledgeNewUserDisclaimer()4159     public void acknowledgeNewUserDisclaimer() {
4160         if (mService != null) {
4161             try {
4162                 mService.acknowledgeNewUserDisclaimer(mContext.getUserId());
4163             } catch (RemoteException e) {
4164                 throw e.rethrowFromSystemServer();
4165             }
4166         }
4167     }
4168 
4169     /**
4170      * Checks whether the new managed user disclaimer was viewed by the user.
4171      *
4172      * @hide
4173      */
4174     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
4175             android.Manifest.permission.INTERACT_ACROSS_USERS})
4176     @TestApi
4177     @UserHandleAware
isNewUserDisclaimerAcknowledged()4178     public boolean isNewUserDisclaimerAcknowledged() {
4179         if (mService != null) {
4180             try {
4181                 return mService.isNewUserDisclaimerAcknowledged(mContext.getUserId());
4182             } catch (RemoteException e) {
4183                 throw e.rethrowFromSystemServer();
4184             }
4185         }
4186         return false;
4187     }
4188 
4189     /**
4190      * Return true if the given administrator component is currently active (enabled) in the system.
4191      *
4192      * @param admin The administrator component to check for.
4193      * @return {@code true} if {@code admin} is currently enabled in the system, {@code false}
4194      *         otherwise
4195      */
isAdminActive(@onNull ComponentName admin)4196     public boolean isAdminActive(@NonNull ComponentName admin) {
4197         throwIfParentInstance("isAdminActive");
4198         return isAdminActiveAsUser(admin, myUserId());
4199     }
4200 
4201     /**
4202      * @see #isAdminActive(ComponentName)
4203      * @hide
4204      */
isAdminActiveAsUser(@onNull ComponentName admin, int userId)4205     public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
4206         if (mService != null) {
4207             try {
4208                 return mService.isAdminActive(admin, userId);
4209             } catch (RemoteException e) {
4210                 throw e.rethrowFromSystemServer();
4211             }
4212         }
4213         return false;
4214     }
4215 
4216     /**
4217      * Return true if the given administrator component is currently being removed
4218      * for the user.
4219      * @hide
4220      */
4221     @TestApi
isRemovingAdmin(@onNull ComponentName admin, int userId)4222     public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
4223         if (mService != null) {
4224             try {
4225                 return mService.isRemovingAdmin(admin, userId);
4226             } catch (RemoteException e) {
4227                 throw e.rethrowFromSystemServer();
4228             }
4229         }
4230         return false;
4231     }
4232 
4233     /**
4234      * Return a list of all currently active device administrators' component
4235      * names.  If there are no administrators {@code null} may be
4236      * returned.
4237      */
getActiveAdmins()4238     public @Nullable List<ComponentName> getActiveAdmins() {
4239         throwIfParentInstance("getActiveAdmins");
4240         return getActiveAdminsAsUser(myUserId());
4241     }
4242 
4243     /**
4244      * @see #getActiveAdmins()
4245      * @hide
4246      */
4247     @UnsupportedAppUsage
getActiveAdminsAsUser(int userId)4248     public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) {
4249         if (mService != null) {
4250             try {
4251                 return mService.getActiveAdmins(userId);
4252             } catch (RemoteException e) {
4253                 throw e.rethrowFromSystemServer();
4254             }
4255         }
4256         return null;
4257     }
4258 
4259     /**
4260      * Used by package administration code to determine if a package can be stopped
4261      * or uninstalled.
4262      * @hide
4263      */
4264     @SystemApi
4265     @RequiresPermission(INTERACT_ACROSS_USERS_FULL)
packageHasActiveAdmins(String packageName)4266     public boolean packageHasActiveAdmins(String packageName) {
4267         return packageHasActiveAdmins(packageName, myUserId());
4268     }
4269 
4270     /**
4271      * Used by package administration code to determine if a package can be stopped
4272      * or uninstalled.
4273      * @hide
4274      */
4275     @UnsupportedAppUsage
packageHasActiveAdmins(String packageName, int userId)4276     public boolean packageHasActiveAdmins(String packageName, int userId) {
4277         if (mService != null) {
4278             try {
4279                 return mService.packageHasActiveAdmins(packageName, userId);
4280             } catch (RemoteException e) {
4281                 throw e.rethrowFromSystemServer();
4282             }
4283         }
4284         return false;
4285     }
4286 
4287     /**
4288      * Remove a current administration component.  This can only be called
4289      * by the application that owns the administration component; if you
4290      * try to remove someone else's component, a security exception will be
4291      * thrown.
4292      *
4293      * <p>Note that the operation is not synchronous and the admin might still be active (as
4294      * indicated by {@link #getActiveAdmins()}) by the time this method returns.
4295      *
4296      * @param admin The administration compononent to remove.
4297      * @throws SecurityException if the caller is not in the owner application of {@code admin}.
4298      */
removeActiveAdmin(@onNull ComponentName admin)4299     public void removeActiveAdmin(@NonNull ComponentName admin) {
4300         throwIfParentInstance("removeActiveAdmin");
4301         if (mService != null) {
4302             try {
4303                 mService.removeActiveAdmin(admin, myUserId());
4304             } catch (RemoteException e) {
4305                 throw e.rethrowFromSystemServer();
4306             }
4307         }
4308     }
4309 
4310     /**
4311      * Returns true if an administrator has been granted a particular device policy. This can be
4312      * used to check whether the administrator was activated under an earlier set of policies, but
4313      * requires additional policies after an upgrade.
4314      *
4315      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be an
4316      *            active administrator, or an exception will be thrown.
4317      * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
4318      * @throws SecurityException if {@code admin} is not an active administrator.
4319      */
hasGrantedPolicy(@onNull ComponentName admin, int usesPolicy)4320     public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) {
4321         throwIfParentInstance("hasGrantedPolicy");
4322         if (mService != null) {
4323             try {
4324                 return mService.hasGrantedPolicy(admin, usesPolicy, myUserId());
4325             } catch (RemoteException e) {
4326                 throw e.rethrowFromSystemServer();
4327             }
4328         }
4329         return false;
4330     }
4331 
4332     /**
4333      * Constant for {@link #setPasswordQuality}: the policy has no requirements
4334      * for the password.  Note that quality constants are ordered so that higher
4335      * values are more restrictive.
4336      */
4337     public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
4338 
4339     /**
4340      * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
4341      * recognition technology.  This implies technologies that can recognize the identity of
4342      * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
4343      * Note that quality constants are ordered so that higher values are more restrictive.
4344      */
4345     public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
4346 
4347     /**
4348      * Constant for {@link #setPasswordQuality}: the policy requires some kind
4349      * of password or pattern, but doesn't care what it is. Note that quality constants
4350      * are ordered so that higher values are more restrictive.
4351      */
4352     public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
4353 
4354     /**
4355      * Constant for {@link #setPasswordQuality}: the user must have entered a
4356      * password containing at least numeric characters.  Note that quality
4357      * constants are ordered so that higher values are more restrictive.
4358      */
4359     public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
4360 
4361     /**
4362      * Constant for {@link #setPasswordQuality}: the user must have entered a
4363      * password containing at least numeric characters with no repeating (4444)
4364      * or ordered (1234, 4321, 2468) sequences.  Note that quality
4365      * constants are ordered so that higher values are more restrictive.
4366      */
4367     public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
4368 
4369     /**
4370      * Constant for {@link #setPasswordQuality}: the user must have entered a
4371      * password containing at least alphabetic (or other symbol) characters.
4372      * Note that quality constants are ordered so that higher values are more
4373      * restrictive.
4374      */
4375     public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
4376 
4377     /**
4378      * Constant for {@link #setPasswordQuality}: the user must have entered a
4379      * password containing at least <em>both></em> numeric <em>and</em>
4380      * alphabetic (or other symbol) characters.  Note that quality constants are
4381      * ordered so that higher values are more restrictive.
4382      */
4383     public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
4384 
4385     /**
4386      * Constant for {@link #setPasswordQuality}: allows the admin to set precisely how many
4387      * characters of various types the password should contain to satisfy the policy. The admin
4388      * should set these requirements via {@link #setPasswordMinimumLetters},
4389      * {@link #setPasswordMinimumNumeric}, {@link #setPasswordMinimumSymbols},
4390      * {@link #setPasswordMinimumUpperCase}, {@link #setPasswordMinimumLowerCase},
4391      * {@link #setPasswordMinimumNonLetter}, and {@link #setPasswordMinimumLength}.
4392      * Note that quality constants are ordered so that higher values are more restrictive.
4393      */
4394     public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
4395 
4396     /**
4397      * Constant for {@link #setPasswordQuality}: the user is not allowed to
4398      * modify password. In case this password quality is set, the password is
4399      * managed by a profile owner. The profile owner can set any password,
4400      * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note
4401      * that quality constants are ordered so that higher values are more
4402      * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is
4403      * the highest.
4404      * @hide
4405      */
4406     public static final int PASSWORD_QUALITY_MANAGED = 0x80000;
4407 
4408     /**
4409      * @hide
4410      *
4411      * adb shell dpm set-{device,profile}-owner will normally not allow installing an owner to
4412      * a user with accounts.  {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED}
4413      * and {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} are the account features
4414      * used by authenticator to exempt their accounts from this:
4415      *
4416      * <ul>
4417      *     <li>Non-test-only DO/PO still can't be installed when there are accounts.
4418      *     <p>In order to make an apk test-only, add android:testOnly="true" to the
4419      *     &lt;application&gt; tag in the manifest.
4420      *
4421      *     <li>Test-only DO/PO can be installed even when there are accounts, as long as all the
4422      *     accounts have the {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} feature.
4423      *     Some authenticators claim to have any features, so to detect it, we also check
4424      *     {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} and disallow installing
4425      *     if any of the accounts have it.
4426      * </ul>
4427      */
4428     @SystemApi
4429     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED =
4430             "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED";
4431 
4432     /** @hide See {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} */
4433     @SystemApi
4434     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED =
4435             "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED";
4436 
4437     /**
4438      * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
4439      * manifest element, which declares that the module should be considered a required app for
4440      * managed users.
4441      * <p>Being declared as a required app prevents removal of this package during the
4442      * provisioning process.
4443      * @hide
4444      */
4445     @SystemApi
4446     public static final String REQUIRED_APP_MANAGED_USER = "android.app.REQUIRED_APP_MANAGED_USER";
4447 
4448     /**
4449      * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
4450      * manifest element, which declares that the module should be considered a required app for
4451      * managed devices.
4452      * <p>Being declared as a required app prevents removal of this package during the
4453      * provisioning process.
4454      * @hide
4455      */
4456     @SystemApi
4457     public static final String REQUIRED_APP_MANAGED_DEVICE =
4458             "android.app.REQUIRED_APP_MANAGED_DEVICE";
4459 
4460     /**
4461      * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
4462      * manifest element, which declares that the module should be considered a required app for
4463      * managed profiles.
4464      * <p>Being declared as a required app prevents removal of this package during the
4465      * provisioning process.
4466      * @hide
4467      */
4468     @SystemApi
4469     public static final String REQUIRED_APP_MANAGED_PROFILE =
4470             "android.app.REQUIRED_APP_MANAGED_PROFILE";
4471 
4472     /**
4473      * Called by an application that is administering the device to set the password restrictions it
4474      * is imposing. After setting this, the user will not be able to enter a new password that is
4475      * not at least as restrictive as what has been set. Note that the current password will remain
4476      * until the user has set a new one, so the change does not take place immediately. To prompt
4477      * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
4478      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after calling this method.
4479      * <p>
4480      * Quality constants are ordered so that higher values are more restrictive; thus the highest
4481      * requested quality constant (between the policy set here, the user's preference, and any other
4482      * considerations) is the one that is in effect.
4483      * <p>
4484      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4485      * password is always treated as empty.
4486      * <p>
4487      * The calling device admin must have requested
4488      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4489      * not, a security exception will be thrown.
4490      * <p>
4491      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4492      * {@link DevicePolicyManager} instance returned by
4493      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4494      * profile. Apps targeting {@link android.os.Build.VERSION_CODES#S} and above, with the
4495      * exception of a profile owner on an organization-owned device (as can be identified by
4496      * {@link #isOrganizationOwnedDeviceWithManagedProfile}), will get a
4497      * {@code IllegalArgumentException} when calling this method on the parent
4498      * {@link DevicePolicyManager} instance.
4499      *
4500      * <p><strong>Note:</strong> Specifying password requirements using this method clears the
4501      * password complexity requirements set using {@link #setRequiredPasswordComplexity(int)}.
4502      * If this method is called on the {@link DevicePolicyManager} instance returned by
4503      * {@link #getParentProfileInstance(ComponentName)}, then password complexity requirements
4504      * set on the primary {@link DevicePolicyManager} must be cleared first by calling
4505      * {@link #setRequiredPasswordComplexity} with {@link #PASSWORD_COMPLEXITY_NONE) first.
4506      *
4507      * <p><string>Note:</strong> this method is ignored on
4508      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4509      *
4510      * @deprecated Prefer using {@link #setRequiredPasswordComplexity(int)}, to require a password
4511      * that satisfies a complexity level defined by the platform, rather than specifying custom
4512      * password requirement.
4513      * Setting custom, overly-complicated password requirements leads to passwords that are hard
4514      * for users to remember and may not provide any security benefits given as Android uses
4515      * hardware-backed throttling to thwart online and offline brute-forcing of the device's
4516      * screen lock. Company-owned devices (fully-managed and organization-owned managed profile
4517      * devices) are able to continue using this method, though it is recommended that
4518      * {@link #setRequiredPasswordComplexity(int)} should be used instead.
4519      *
4520      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4521      * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED},
4522      *            {@link #PASSWORD_QUALITY_BIOMETRIC_WEAK},
4523      *            {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC},
4524      *            {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
4525      *            {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
4526      * @throws SecurityException if {@code admin} is not an active administrator, if {@code admin}
4527      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} or if the
4528      *             calling app is targeting {@link android.os.Build.VERSION_CODES#S} and above,
4529      *             and is calling the method the {@link DevicePolicyManager} instance returned by
4530      *             {@link #getParentProfileInstance(ComponentName)}.
4531      * @throws IllegalStateException if the caller is trying to set password quality on the parent
4532      *             {@link DevicePolicyManager} instance while password complexity was set on the
4533      *             primary {@link DevicePolicyManager} instance.
4534      */
4535     @Deprecated
setPasswordQuality(@onNull ComponentName admin, int quality)4536     public void setPasswordQuality(@NonNull ComponentName admin, int quality) {
4537         if (mService != null) {
4538             try {
4539                 mService.setPasswordQuality(admin, quality, mParentInstance);
4540             } catch (RemoteException e) {
4541                 throw e.rethrowFromSystemServer();
4542             }
4543         }
4544     }
4545 
4546     /**
4547      * Retrieve the current minimum password quality for a particular admin or all admins that set
4548      * restrictions on this user and its participating profiles. Restrictions on profiles that have
4549      * a separate challenge are not taken into account.
4550      *
4551      * <p>This method can be called on the {@link DevicePolicyManager} instance
4552      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4553      * restrictions on the parent profile.
4554      *
4555      * <p>Note: on devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
4556      * the password is always treated as empty.
4557      *
4558      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4559      *
4560      * @param admin The name of the admin component to check, or {@code null} to aggregate
4561      * all admins.
4562      */
4563     @Deprecated
getPasswordQuality(@ullable ComponentName admin)4564     public int getPasswordQuality(@Nullable ComponentName admin) {
4565         return getPasswordQuality(admin, myUserId());
4566     }
4567 
4568     /** @hide per-user version */
4569     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordQuality(@ullable ComponentName admin, int userHandle)4570     public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) {
4571         if (mService != null) {
4572             try {
4573                 return mService.getPasswordQuality(admin, userHandle, mParentInstance);
4574             } catch (RemoteException e) {
4575                 throw e.rethrowFromSystemServer();
4576             }
4577         }
4578         return PASSWORD_QUALITY_UNSPECIFIED;
4579     }
4580 
4581     /**
4582      * Called by an application that is administering the device to set the minimum allowed password
4583      * length. After setting this, the user will not be able to enter a new password that is not at
4584      * least as restrictive as what has been set. Note that the current password will remain until
4585      * the user has set a new one, so the change does not take place immediately. To prompt the user
4586      * for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
4587      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
4588      * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
4589      * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
4590      * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with
4591      * {@link #setPasswordQuality}. If an app targeting SDK level
4592      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
4593      * password quality to one of these values first, this method will throw
4594      * {@link IllegalStateException}.
4595      * <p>
4596      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4597      * password is always treated as empty.
4598      * <p>
4599      * The calling device admin must have requested
4600      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4601      * not, a security exception will be thrown.
4602      * <p>
4603      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4604      * {@link DevicePolicyManager} instance returned by
4605      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4606      * profile.
4607      *
4608      * <p><string>Note:</strong> this method is ignored on
4609      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4610      *
4611      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4612      *
4613      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4614      * @param length The new desired minimum password length. A value of 0 means there is no
4615      *     restriction.
4616      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4617      *     does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4618      * @throws IllegalStateException if the calling app is targeting SDK level
4619      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4620      *     quality requirement prior to calling this method.
4621      */
4622     @Deprecated
setPasswordMinimumLength(@onNull ComponentName admin, int length)4623     public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
4624         if (mService != null) {
4625             try {
4626                 mService.setPasswordMinimumLength(admin, length, mParentInstance);
4627             } catch (RemoteException e) {
4628                 throw e.rethrowFromSystemServer();
4629             }
4630         }
4631     }
4632 
4633     /**
4634      * Retrieve the current minimum password length for a particular admin or all admins that set
4635      * restrictions on this user and its participating profiles. Restrictions on profiles that have
4636      * a separate challenge are not taken into account.
4637      *
4638      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4639      * password is always treated as empty.
4640      *
4641      * <p>This method can be called on the {@link DevicePolicyManager} instance
4642      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4643      * restrictions on the parent profile.
4644      *
4645      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4646      *
4647      * @param admin The name of the admin component to check, or {@code null} to aggregate
4648      * all admins.
4649      */
4650     @Deprecated
getPasswordMinimumLength(@ullable ComponentName admin)4651     public int getPasswordMinimumLength(@Nullable ComponentName admin) {
4652         return getPasswordMinimumLength(admin, myUserId());
4653     }
4654 
4655     /** @hide per-user version */
4656     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLength(@ullable ComponentName admin, int userHandle)4657     public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) {
4658         if (mService != null) {
4659             try {
4660                 return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance);
4661             } catch (RemoteException e) {
4662                 throw e.rethrowFromSystemServer();
4663             }
4664         }
4665         return 0;
4666     }
4667 
4668     /**
4669      * Called by an application that is administering the device to set the minimum number of upper
4670      * case letters required in the password. After setting this, the user will not be able to enter
4671      * a new password that is not at least as restrictive as what has been set. Note that the
4672      * current password will remain until the user has set a new one, so the change does not take
4673      * place immediately. To prompt the user for a new password, use
4674      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
4675      * setting this value. This constraint is only imposed if the administrator has also requested
4676      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
4677      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
4678      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4679      * {@link IllegalStateException}. The default value is 0.
4680      * <p>
4681      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4682      * password is always treated as empty.
4683      * <p>
4684      * The calling device admin must have requested
4685      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4686      * not, a security exception will be thrown.
4687      * <p>
4688      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4689      * {@link DevicePolicyManager} instance returned by
4690      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4691      * profile.
4692      *
4693      * <p><string>Note:</strong> this method is ignored on
4694      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4695      *
4696      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4697      *
4698      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4699      * @param length The new desired minimum number of upper case letters required in the password.
4700      *            A value of 0 means there is no restriction.
4701      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4702      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4703      * @throws IllegalStateException if the calling app is targeting SDK level
4704      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4705      *     quality requirement prior to calling this method.
4706      */
4707     @Deprecated
setPasswordMinimumUpperCase(@onNull ComponentName admin, int length)4708     public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
4709         if (mService != null) {
4710             try {
4711                 mService.setPasswordMinimumUpperCase(admin, length, mParentInstance);
4712             } catch (RemoteException e) {
4713                 throw e.rethrowFromSystemServer();
4714             }
4715         }
4716     }
4717 
4718     /**
4719      * Retrieve the current number of upper case letters required in the password
4720      * for a particular admin or all admins that set restrictions on this user and
4721      * its participating profiles. Restrictions on profiles that have a separate challenge
4722      * are not taken into account.
4723      * This is the same value as set by
4724      * {@link #setPasswordMinimumUpperCase(ComponentName, int)}
4725      * and only applies when the password quality is
4726      * {@link #PASSWORD_QUALITY_COMPLEX}.
4727      *
4728      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4729      * password is always treated as empty.
4730      *
4731      * <p>This method can be called on the {@link DevicePolicyManager} instance
4732      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4733      * restrictions on the parent profile.
4734      *
4735      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4736      *
4737      * @param admin The name of the admin component to check, or {@code null} to
4738      *            aggregate all admins.
4739      * @return The minimum number of upper case letters required in the
4740      *         password.
4741      */
4742     @Deprecated
getPasswordMinimumUpperCase(@ullable ComponentName admin)4743     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) {
4744         return getPasswordMinimumUpperCase(admin, myUserId());
4745     }
4746 
4747     /** @hide per-user version */
4748     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumUpperCase(@ullable ComponentName admin, int userHandle)4749     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) {
4750         if (mService != null) {
4751             try {
4752                 return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance);
4753             } catch (RemoteException e) {
4754                 throw e.rethrowFromSystemServer();
4755             }
4756         }
4757         return 0;
4758     }
4759 
4760     /**
4761      * Called by an application that is administering the device to set the minimum number of lower
4762      * case letters required in the password. After setting this, the user will not be able to enter
4763      * a new password that is not at least as restrictive as what has been set. Note that the
4764      * current password will remain until the user has set a new one, so the change does not take
4765      * place immediately. To prompt the user for a new password, use
4766      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
4767      * setting this value. This constraint is only imposed if the administrator has also requested
4768      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
4769      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
4770      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4771      * {@link IllegalStateException}. The default value is 0.
4772      * <p>
4773      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4774      * password is always treated as empty.
4775      * <p>
4776      * The calling device admin must have requested
4777      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4778      * not, a security exception will be thrown.
4779      * <p>
4780      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4781      * {@link DevicePolicyManager} instance returned by
4782      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4783      * profile.
4784      *
4785      * <p><string>Note:</strong> this method is ignored on
4786      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4787      *
4788      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4789      *
4790      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4791      * @param length The new desired minimum number of lower case letters required in the password.
4792      *            A value of 0 means there is no restriction.
4793      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4794      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4795      * @throws IllegalStateException if the calling app is targeting SDK level
4796      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4797      *     quality requirement prior to calling this method.
4798      */
4799     @Deprecated
setPasswordMinimumLowerCase(@onNull ComponentName admin, int length)4800     public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
4801         if (mService != null) {
4802             try {
4803                 mService.setPasswordMinimumLowerCase(admin, length, mParentInstance);
4804             } catch (RemoteException e) {
4805                 throw e.rethrowFromSystemServer();
4806             }
4807         }
4808     }
4809 
4810     /**
4811      * Retrieve the current number of lower case letters required in the password
4812      * for a particular admin or all admins that set restrictions on this user
4813      * and its participating profiles. Restrictions on profiles that have
4814      * a separate challenge are not taken into account.
4815      * This is the same value as set by
4816      * {@link #setPasswordMinimumLowerCase(ComponentName, int)}
4817      * and only applies when the password quality is
4818      * {@link #PASSWORD_QUALITY_COMPLEX}.
4819      *
4820      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4821      * password is always treated as empty.
4822      *
4823      * <p>This method can be called on the {@link DevicePolicyManager} instance
4824      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4825      * restrictions on the parent profile.
4826      *
4827      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4828      *
4829      * @param admin The name of the admin component to check, or {@code null} to
4830      *            aggregate all admins.
4831      * @return The minimum number of lower case letters required in the
4832      *         password.
4833      */
4834     @Deprecated
getPasswordMinimumLowerCase(@ullable ComponentName admin)4835     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) {
4836         return getPasswordMinimumLowerCase(admin, myUserId());
4837     }
4838 
4839     /** @hide per-user version */
4840     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLowerCase(@ullable ComponentName admin, int userHandle)4841     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) {
4842         if (mService != null) {
4843             try {
4844                 return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance);
4845             } catch (RemoteException e) {
4846                 throw e.rethrowFromSystemServer();
4847             }
4848         }
4849         return 0;
4850     }
4851 
4852     /**
4853      * Called by an application that is administering the device to set the minimum number of
4854      * letters required in the password. After setting this, the user will not be able to enter a
4855      * new password that is not at least as restrictive as what has been set. Note that the current
4856      * password will remain until the user has set a new one, so the change does not take place
4857      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
4858      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
4859      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
4860      * {@link #setPasswordQuality}. If an app targeting SDK level
4861      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
4862      * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4863      * {@link IllegalStateException}. The default value is 1.
4864      * <p>
4865      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4866      * password is always treated as empty.
4867      * <p>
4868      * The calling device admin must have requested
4869      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4870      * not, a security exception will be thrown.
4871      * <p>
4872      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4873      * {@link DevicePolicyManager} instance returned by
4874      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4875      * profile.
4876      *
4877      * <p><string>Note:</strong> this method is ignored on
4878      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4879      *
4880      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4881      *
4882      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4883      * @param length The new desired minimum number of letters required in the password. A value of
4884      *            0 means there is no restriction.
4885      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4886      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4887      * @throws IllegalStateException if the calling app is targeting SDK level
4888      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4889      *     quality requirement prior to calling this method.
4890      */
4891     @Deprecated
setPasswordMinimumLetters(@onNull ComponentName admin, int length)4892     public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
4893         if (mService != null) {
4894             try {
4895                 mService.setPasswordMinimumLetters(admin, length, mParentInstance);
4896             } catch (RemoteException e) {
4897                 throw e.rethrowFromSystemServer();
4898             }
4899         }
4900     }
4901 
4902     /**
4903      * Retrieve the current number of letters required in the password
4904      * for a particular admin or all admins that set restrictions on this user
4905      * and its participating profiles. Restrictions on profiles that have
4906      * a separate challenge are not taken into account.
4907      * This is the same value as set by
4908      * {@link #setPasswordMinimumLetters(ComponentName, int)}
4909      * and only applies when the password quality is
4910      * {@link #PASSWORD_QUALITY_COMPLEX}.
4911      *
4912      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4913      * password is always treated as empty.
4914      *
4915      * <p>This method can be called on the {@link DevicePolicyManager} instance
4916      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4917      * restrictions on the parent profile.
4918      *
4919      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4920      *
4921      * @param admin The name of the admin component to check, or {@code null} to
4922      *            aggregate all admins.
4923      * @return The minimum number of letters required in the password.
4924      */
4925     @Deprecated
getPasswordMinimumLetters(@ullable ComponentName admin)4926     public int getPasswordMinimumLetters(@Nullable ComponentName admin) {
4927         return getPasswordMinimumLetters(admin, myUserId());
4928     }
4929 
4930     /** @hide per-user version */
4931     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLetters(@ullable ComponentName admin, int userHandle)4932     public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) {
4933         if (mService != null) {
4934             try {
4935                 return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance);
4936             } catch (RemoteException e) {
4937                 throw e.rethrowFromSystemServer();
4938             }
4939         }
4940         return 0;
4941     }
4942 
4943     /**
4944      * Called by an application that is administering the device to set the minimum number of
4945      * numerical digits required in the password. After setting this, the user will not be able to
4946      * enter a new password that is not at least as restrictive as what has been set. Note that the
4947      * current password will remain until the user has set a new one, so the change does not take
4948      * place immediately. To prompt the user for a new password, use
4949      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
4950      * setting this value. This constraint is only imposed if the administrator has also requested
4951      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
4952      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
4953      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4954      * {@link IllegalStateException}. The default value is 1.
4955      * <p>
4956      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4957      * password is always treated as empty.
4958      * <p>
4959      * The calling device admin must have requested
4960      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4961      * not, a security exception will be thrown.
4962      * <p>
4963      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4964      * {@link DevicePolicyManager} instance returned by
4965      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4966      * profile.
4967      *
4968      * <p><string>Note:</strong> this method is ignored on
4969      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4970      *
4971      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4972      *
4973      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4974      * @param length The new desired minimum number of numerical digits required in the password. A
4975      *            value of 0 means there is no restriction.
4976      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4977      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4978      * @throws IllegalStateException if the calling app is targeting SDK level
4979      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4980      *     quality requirement prior to calling this method.
4981      */
4982     @Deprecated
setPasswordMinimumNumeric(@onNull ComponentName admin, int length)4983     public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
4984         if (mService != null) {
4985             try {
4986                 mService.setPasswordMinimumNumeric(admin, length, mParentInstance);
4987             } catch (RemoteException e) {
4988                 throw e.rethrowFromSystemServer();
4989             }
4990         }
4991     }
4992 
4993     /**
4994      * Retrieve the current number of numerical digits required in the password
4995      * for a particular admin or all admins that set restrictions on this user
4996      * and its participating profiles. Restrictions on profiles that have
4997      * a separate challenge are not taken into account.
4998      * This is the same value as set by
4999      * {@link #setPasswordMinimumNumeric(ComponentName, int)}
5000      * and only applies when the password quality is
5001      * {@link #PASSWORD_QUALITY_COMPLEX}.
5002      *
5003      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5004      * password is always treated as empty.
5005      *
5006      * <p>This method can be called on the {@link DevicePolicyManager} instance
5007      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5008      * restrictions on the parent profile.
5009      *
5010      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
5011      *
5012      * @param admin The name of the admin component to check, or {@code null} to
5013      *            aggregate all admins.
5014      * @return The minimum number of numerical digits required in the password.
5015      */
5016     @Deprecated
getPasswordMinimumNumeric(@ullable ComponentName admin)5017     public int getPasswordMinimumNumeric(@Nullable ComponentName admin) {
5018         return getPasswordMinimumNumeric(admin, myUserId());
5019     }
5020 
5021     /** @hide per-user version */
5022     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumNumeric(@ullable ComponentName admin, int userHandle)5023     public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) {
5024         if (mService != null) {
5025             try {
5026                 return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance);
5027             } catch (RemoteException e) {
5028                 throw e.rethrowFromSystemServer();
5029             }
5030         }
5031         return 0;
5032     }
5033 
5034     /**
5035      * Called by an application that is administering the device to set the minimum number of
5036      * symbols required in the password. After setting this, the user will not be able to enter a
5037      * new password that is not at least as restrictive as what has been set. Note that the current
5038      * password will remain until the user has set a new one, so the change does not take place
5039      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
5040      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
5041      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
5042      * {@link #setPasswordQuality}. If an app targeting SDK level
5043      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
5044      * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
5045      * {@link IllegalStateException}. The default value is 1.
5046      * <p>
5047      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5048      * password is always treated as empty.
5049      * <p>
5050      * The calling device admin must have requested
5051      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
5052      * not, a security exception will be thrown.
5053      * <p>
5054      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
5055      * {@link DevicePolicyManager} instance returned by
5056      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5057      * profile.
5058      *
5059      * <p><string>Note:</strong> this method is ignored on
5060      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
5061      *
5062      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
5063      *
5064      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5065      * @param length The new desired minimum number of symbols required in the password. A value of
5066      *            0 means there is no restriction.
5067      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
5068      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
5069      * @throws IllegalStateException if the calling app is targeting SDK level
5070      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
5071      *     quality requirement prior to calling this method.
5072      */
5073     @Deprecated
setPasswordMinimumSymbols(@onNull ComponentName admin, int length)5074     public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
5075         if (mService != null) {
5076             try {
5077                 mService.setPasswordMinimumSymbols(admin, length, mParentInstance);
5078             } catch (RemoteException e) {
5079                 throw e.rethrowFromSystemServer();
5080             }
5081         }
5082     }
5083 
5084     /**
5085      * Retrieve the current number of symbols required in the password
5086      * for a particular admin or all admins that set restrictions on this user
5087      * and its participating profiles. Restrictions on profiles that have
5088      * a separate challenge are not taken into account. This is the same value as
5089      * set by {@link #setPasswordMinimumSymbols(ComponentName, int)}
5090      * and only applies when the password quality is
5091      * {@link #PASSWORD_QUALITY_COMPLEX}.
5092      *
5093      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5094      * password is always treated as empty.
5095      *
5096      * <p>This method can be called on the {@link DevicePolicyManager} instance
5097      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5098      * restrictions on the parent profile.
5099      *
5100      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
5101      *
5102      * @param admin The name of the admin component to check, or {@code null} to
5103      *            aggregate all admins.
5104      * @return The minimum number of symbols required in the password.
5105      */
5106     @Deprecated
getPasswordMinimumSymbols(@ullable ComponentName admin)5107     public int getPasswordMinimumSymbols(@Nullable ComponentName admin) {
5108         return getPasswordMinimumSymbols(admin, myUserId());
5109     }
5110 
5111     /** @hide per-user version */
5112     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumSymbols(@ullable ComponentName admin, int userHandle)5113     public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) {
5114         if (mService != null) {
5115             try {
5116                 return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance);
5117             } catch (RemoteException e) {
5118                 throw e.rethrowFromSystemServer();
5119             }
5120         }
5121         return 0;
5122     }
5123 
5124     /**
5125      * Called by an application that is administering the device to set the minimum number of
5126      * non-letter characters (numerical digits or symbols) required in the password. After setting
5127      * this, the user will not be able to enter a new password that is not at least as restrictive
5128      * as what has been set. Note that the current password will remain until the user has set a new
5129      * one, so the change does not take place immediately. To prompt the user for a new password,
5130      * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
5131      * setting this value. This constraint is only imposed if the administrator has also requested
5132      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
5133      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
5134      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
5135      * {@link IllegalStateException}. The default value is 0.
5136      * <p>
5137      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5138      * password is always treated as empty.
5139      * <p>
5140      * The calling device admin must have requested
5141      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
5142      * not, a security exception will be thrown.
5143      * <p>
5144      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
5145      * {@link DevicePolicyManager} instance returned by
5146      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5147      * profile.
5148      *
5149      * <p><string>Note:</strong> this method is ignored on
5150      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
5151      *
5152      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
5153      *
5154      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5155      * @param length The new desired minimum number of letters required in the password. A value of
5156      *            0 means there is no restriction.
5157      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
5158      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
5159      * @throws IllegalStateException if the calling app is targeting SDK level
5160      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
5161      *     quality requirement prior to calling this method.
5162      */
5163     @Deprecated
setPasswordMinimumNonLetter(@onNull ComponentName admin, int length)5164     public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
5165         if (mService != null) {
5166             try {
5167                 mService.setPasswordMinimumNonLetter(admin, length, mParentInstance);
5168             } catch (RemoteException e) {
5169                 throw e.rethrowFromSystemServer();
5170             }
5171         }
5172     }
5173 
5174     /**
5175      * Retrieve the current number of non-letter characters required in the password
5176      * for a particular admin or all admins that set restrictions on this user
5177      * and its participating profiles. Restrictions on profiles that have
5178      * a separate challenge are not taken into account.
5179      * This is the same value as set by
5180      * {@link #setPasswordMinimumNonLetter(ComponentName, int)}
5181      * and only applies when the password quality is
5182      * {@link #PASSWORD_QUALITY_COMPLEX}.
5183      *
5184      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5185      * password is always treated as empty.
5186      *
5187      * <p>This method can be called on the {@link DevicePolicyManager} instance
5188      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5189      * restrictions on the parent profile.
5190      *
5191      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
5192      *
5193      * @param admin The name of the admin component to check, or {@code null} to
5194      *            aggregate all admins.
5195      * @return The minimum number of letters required in the password.
5196      */
5197     @Deprecated
getPasswordMinimumNonLetter(@ullable ComponentName admin)5198     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) {
5199         return getPasswordMinimumNonLetter(admin, myUserId());
5200     }
5201 
5202     /** @hide per-user version */
5203     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumNonLetter(@ullable ComponentName admin, int userHandle)5204     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) {
5205         if (mService != null) {
5206             try {
5207                 return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance);
5208             } catch (RemoteException e) {
5209                 throw e.rethrowFromSystemServer();
5210             }
5211         }
5212         return 0;
5213     }
5214 
5215     /**
5216      * Returns minimum PasswordMetrics that satisfies all admin policies.
5217      *
5218      * @hide
5219      */
getPasswordMinimumMetrics(@serIdInt int userHandle)5220     public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle) {
5221         return getPasswordMinimumMetrics(userHandle, false);
5222     }
5223 
5224     /**
5225      * Returns minimum PasswordMetrics that satisfies all admin policies.
5226      * If requested, only consider device-wide admin policies and ignore policies set on the
5227      * managed profile instance (as if the managed profile had separate work challenge).
5228      *
5229      * @hide
5230      */
getPasswordMinimumMetrics(@serIdInt int userHandle, boolean deviceWideOnly)5231     public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle,
5232             boolean deviceWideOnly) {
5233         if (mService != null) {
5234             try {
5235                 return mService.getPasswordMinimumMetrics(userHandle, deviceWideOnly);
5236             } catch (RemoteException e) {
5237                 throw e.rethrowFromSystemServer();
5238             }
5239         }
5240         return null;
5241     }
5242 
5243     /**
5244      * Called by an application that is administering the device to set the length of the password
5245      * history. After setting this, the user will not be able to enter a new password that is the
5246      * same as any password in the history. Note that the current password will remain until the
5247      * user has set a new one, so the change does not take place immediately. To prompt the user for
5248      * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
5249      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value.
5250      * <p>
5251      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5252      * password history length is always 0.
5253      * <p>
5254      * The calling device admin must have requested
5255      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
5256      * not, a security exception will be thrown.
5257      * <p>
5258      * This method can be called on the {@link DevicePolicyManager} instance returned by
5259      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5260      * profile.
5261      *
5262      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5263      * @param length The new desired length of password history. A value of 0 means there is no
5264      *            restriction.
5265      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
5266      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
5267      */
5268     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setPasswordHistoryLength(@onNull ComponentName admin, int length)5269     public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
5270         if (mService != null) {
5271             try {
5272                 mService.setPasswordHistoryLength(admin, length, mParentInstance);
5273             } catch (RemoteException e) {
5274                 throw e.rethrowFromSystemServer();
5275             }
5276         }
5277     }
5278 
5279     /**
5280      * Called by a device admin to set the password expiration timeout. Calling this method will
5281      * restart the countdown for password expiration for the given admin, as will changing the
5282      * device password (for all admins).
5283      * <p>
5284      * The provided timeout is the time delta in ms and will be added to the current time. For
5285      * example, to have the password expire 5 days from now, timeout would be 5 * 86400 * 1000 =
5286      * 432000000 ms for timeout.
5287      * <p>
5288      * To disable password expiration, a value of 0 may be used for timeout.
5289      * <p>
5290      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5291      * password expiration is always disabled.
5292      * <p>
5293      * A calling device admin must have requested
5294      * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this method; if it has
5295      * not, a security exception will be thrown.
5296      * <p>
5297      * Note that setting the password will automatically reset the expiration time for all active
5298      * admins. Active admins do not need to explicitly call this method in that case.
5299      * <p>
5300      * This method can be called on the {@link DevicePolicyManager} instance returned by
5301      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5302      * profile.
5303      *
5304      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
5305      *              caller is not a device admin
5306      * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 means
5307      *            there is no restriction (unlimited).
5308      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
5309      *             does not use {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD}
5310      */
5311     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5312     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true)
setPasswordExpirationTimeout(@ullable ComponentName admin, long timeout)5313     public void setPasswordExpirationTimeout(@Nullable ComponentName admin, long timeout) {
5314         if (mService != null) {
5315             try {
5316                 mService.setPasswordExpirationTimeout(
5317                         admin, mContext.getPackageName(), timeout, mParentInstance);
5318             } catch (RemoteException e) {
5319                 throw e.rethrowFromSystemServer();
5320             }
5321         }
5322     }
5323 
5324     /**
5325      * Get the password expiration timeout for the given admin. The expiration timeout is the
5326      * recurring expiration timeout provided in the call to
5327      * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
5328      * aggregate of all participating policy administrators if {@code admin} is null. Admins that
5329      * have set restrictions on profiles that have a separate challenge are not taken into account.
5330      *
5331      * <p>This method can be called on the {@link DevicePolicyManager} instance
5332      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5333      * restrictions on the parent profile.
5334      *
5335      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5336      * password expiration is always disabled and this method always returns 0.
5337      *
5338      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
5339      * @return The timeout for the given admin or the minimum of all timeouts
5340      */
5341     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordExpirationTimeout(@ullable ComponentName admin)5342     public long getPasswordExpirationTimeout(@Nullable ComponentName admin) {
5343         if (mService != null) {
5344             try {
5345                 return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance);
5346             } catch (RemoteException e) {
5347                 throw e.rethrowFromSystemServer();
5348             }
5349         }
5350         return 0;
5351     }
5352 
5353     /**
5354      * Get the current password expiration time for a particular admin or all admins that set
5355      * restrictions on this user and its participating profiles. Restrictions on profiles that have
5356      * a separate challenge are not taken into account. If admin is {@code null}, then a composite
5357      * of all expiration times is returned - which will be the minimum of all of them.
5358      *
5359      * <p>This method can be called on the {@link DevicePolicyManager} instance
5360      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5361      * the password expiration for the parent profile.
5362      *
5363      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5364      * password expiration is always disabled and this method always returns 0.
5365      *
5366      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
5367      * @return The password expiration time, in milliseconds since epoch.
5368      */
5369     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordExpiration(@ullable ComponentName admin)5370     public long getPasswordExpiration(@Nullable ComponentName admin) {
5371         if (mService != null) {
5372             try {
5373                 return mService.getPasswordExpiration(admin, myUserId(), mParentInstance);
5374             } catch (RemoteException e) {
5375                 throw e.rethrowFromSystemServer();
5376             }
5377         }
5378         return 0;
5379     }
5380 
5381     /**
5382      * Retrieve the current password history length for a particular admin or all admins that
5383      * set restrictions on this user and its participating profiles. Restrictions on profiles that
5384      * have a separate challenge are not taken into account.
5385      *
5386      * <p>This method can be called on the {@link DevicePolicyManager} instance
5387      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5388      * restrictions on the parent profile.
5389      *
5390      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5391      * password history length is always 0.
5392      *
5393      * @param admin The name of the admin component to check, or {@code null} to aggregate
5394      * all admins.
5395      * @return The length of the password history
5396      */
5397     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordHistoryLength(@ullable ComponentName admin)5398     public int getPasswordHistoryLength(@Nullable ComponentName admin) {
5399         return getPasswordHistoryLength(admin, myUserId());
5400     }
5401 
5402     /** @hide per-user version */
5403     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
5404     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordHistoryLength(@ullable ComponentName admin, int userHandle)5405     public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) {
5406         if (mService != null) {
5407             try {
5408                 return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance);
5409             } catch (RemoteException e) {
5410                 throw e.rethrowFromSystemServer();
5411             }
5412         }
5413         return 0;
5414     }
5415 
5416     /**
5417      * Return the maximum password length that the device supports for a
5418      * particular password quality.
5419      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5420      * password is always empty and this method always returns 0.
5421      * @param quality The quality being interrogated.
5422      * @return Returns the maximum length that the user can enter.
5423      */
getPasswordMaximumLength(int quality)5424     public int getPasswordMaximumLength(int quality) {
5425         PackageManager pm = mContext.getPackageManager();
5426         if (!pm.hasSystemFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)) {
5427             return 0;
5428         }
5429         return MAX_PASSWORD_LENGTH;
5430     }
5431 
5432     /**
5433      * Determines whether the calling user's current password meets policy requirements
5434      * (e.g. quality, minimum length). The user must be unlocked to perform this check.
5435      *
5436      * <p>Policy requirements which affect this check can be set by admins of the user, but also
5437      * by the admin of a managed profile associated with the calling user (when the managed profile
5438      * doesn't have a separate work challenge). When a managed profile has a separate work
5439      * challenge, its policy requirements only affect the managed profile.
5440      *
5441      * <p>Depending on the user, this method checks the policy requirement against one of the
5442      * following passwords:
5443      * <ul>
5444      * <li>For the primary user or secondary users: the personal keyguard password.
5445      * <li>For managed profiles: a work challenge if set, otherwise the parent user's personal
5446      *     keyguard password.
5447      * <ul/>
5448      * In other words, it's always checking the requirement against the password that is protecting
5449      * the calling user.
5450      *
5451      * <p>Note that this method considers all policy requirements targeting the password in
5452      * question. For example a profile owner might set a requirement on the parent profile i.e.
5453      * personal keyguard but not on the profile itself. When the device has a weak personal keyguard
5454      * password and no separate work challenge, calling this method will return {@code false}
5455      * despite the profile owner not setting a policy on the profile itself. This is because the
5456      * profile's current password is the personal keyguard password, and it does not meet all policy
5457      * requirements.
5458      *
5459      * <p>Device admins must request {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} before
5460      * calling this method. Note, this policy type is deprecated for device admins in Android 9.0
5461      * (API level 28) or higher.
5462      *
5463      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
5464      * {@link #getParentProfileInstance(ComponentName)} in order to determine if the password set on
5465      * the parent profile is sufficient.
5466      *
5467      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5468      * password is always treated as empty - i.e. this method will always return false on such
5469      * devices, provided any password requirements were set.
5470      *
5471      * @return {@code true} if the password meets the policy requirements, {@code false} otherwise
5472      * @throws SecurityException if the calling application isn't an active admin that uses
5473      *     {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
5474      * @throws IllegalStateException if the user isn't unlocked
5475      */
5476     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true)
isActivePasswordSufficient()5477     public boolean isActivePasswordSufficient() {
5478         if (mService != null) {
5479             try {
5480                 return mService.isActivePasswordSufficient(
5481                         mContext.getPackageName(), myUserId(), mParentInstance);
5482             } catch (RemoteException e) {
5483                 throw e.rethrowFromSystemServer();
5484             }
5485         }
5486         return false;
5487     }
5488 
5489     /**
5490      * Called by profile owner of a managed profile to determine whether the current device password
5491      * meets policy requirements set explicitly device-wide.
5492      * <p> This API is similar to {@link #isActivePasswordSufficient()}, with two notable
5493      * differences:
5494      * <ul>
5495      * <li>this API always targets the device password. As a result it should always be called on
5496      *   the {@link #getParentProfileInstance(ComponentName)} instance.</li>
5497      * <li>password policy requirement set on the managed profile is not taken into consideration
5498      *   by this API, even if the device currently does not have a separate work challenge set.</li>
5499      * </ul>
5500      *
5501      * <p>This API is designed to facilite progressive password enrollment flows when the DPC
5502      * imposes both device and profile password policies. DPC applies profile password policy by
5503      * calling {@link #setPasswordQuality(ComponentName, int)} or
5504      * {@link #setRequiredPasswordComplexity} on the regular {@link DevicePolicyManager} instance,
5505      * while it applies device-wide policy by calling {@link #setRequiredPasswordComplexity} on the
5506      * {@link #getParentProfileInstance(ComponentName)} instance. The DPC can utilize this check to
5507      * guide the user to set a device password first taking into consideration the device-wide
5508      * policy only, and then prompt the user to either upgrade it to be fully compliant, or enroll a
5509      * separate work challenge to satisfy the profile password policy only.
5510      *
5511      * <p>The device user must be unlocked (@link {@link UserManager#isUserUnlocked(UserHandle)})
5512      * to perform this check.
5513      *
5514      * @return {@code true} if the device password meets explicit requirement set on it,
5515      *   {@code false} otherwise.
5516      * @throws SecurityException if the calling application is not a profile owner of a managed
5517      *   profile, or if this API is not called on the parent DevicePolicyManager instance.
5518      * @throws IllegalStateException if the user isn't unlocked
5519      * @see #EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY
5520      */
isActivePasswordSufficientForDeviceRequirement()5521     public boolean isActivePasswordSufficientForDeviceRequirement() {
5522         if (!mParentInstance) {
5523             throw new SecurityException("only callable on the parent instance");
5524         }
5525         if (mService != null) {
5526             try {
5527                 return mService.isActivePasswordSufficientForDeviceRequirement();
5528             } catch (RemoteException e) {
5529                 throw e.rethrowFromSystemServer();
5530             }
5531         }
5532         return false;
5533     }
5534 
5535     /**
5536      * Returns how complex the current user's screen lock is.
5537      *
5538      * <p>Note that when called from a profile which uses an unified challenge with its parent, the
5539      * screen lock complexity of the parent will be returned.
5540      *
5541      * <p>Apps need the {@link permission#REQUEST_PASSWORD_COMPLEXITY} permission to call this
5542      * method. On Android {@link android.os.Build.VERSION_CODES#S} and above, the calling
5543      * application does not need this permission if it is a device owner or a profile owner.
5544      *
5545      * <p>This method can be called on the {@link DevicePolicyManager} instance
5546      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5547      * restrictions on the parent profile.
5548      *
5549      * @throws IllegalStateException if the user is not unlocked.
5550      * @throws SecurityException     if the calling application does not have the permission
5551      *                               {@link permission#REQUEST_PASSWORD_COMPLEXITY}, and is not a
5552      *                               device owner or a profile owner.
5553      */
5554     @PasswordComplexity
5555     @RequiresPermission(anyOf={MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, REQUEST_PASSWORD_COMPLEXITY}, conditional = true)
getPasswordComplexity()5556     public int getPasswordComplexity() {
5557         if (mService == null) {
5558             return PASSWORD_COMPLEXITY_NONE;
5559         }
5560 
5561         try {
5562             return mService.getPasswordComplexity(mParentInstance);
5563         } catch (RemoteException e) {
5564             throw e.rethrowFromSystemServer();
5565         }
5566     }
5567 
5568     /**
5569      * Sets a minimum password complexity requirement for the user's screen lock.
5570      * The complexity level is one of the pre-defined levels, and the user is unable to set a
5571      * password with a lower complexity level.
5572      *
5573      * <p>Note that when called on a profile which uses an unified challenge with its parent, the
5574      * complexity would apply to the unified challenge.
5575      *
5576      * <p>This method can be called on the {@link DevicePolicyManager} instance
5577      * returned by {@link #getParentProfileInstance(ComponentName)} in order to set
5578      * restrictions on the parent profile.
5579      *
5580      * <p><strong>Note:</strong> Specifying password requirements using this method clears any
5581      * password requirements set using the obsolete {@link #setPasswordQuality(ComponentName, int)}
5582      * and any of its associated methods.
5583      * Additionally, if there are password requirements set using the obsolete
5584      * {@link #setPasswordQuality(ComponentName, int)} on the parent {@code DevicePolicyManager}
5585      * instance, they must be cleared by calling {@link #setPasswordQuality(ComponentName, int)}
5586      * with {@link #PASSWORD_QUALITY_UNSPECIFIED} on that instance prior to setting complexity
5587      * requirement for the managed profile.
5588      *
5589      * @throws SecurityException if the calling application is not a device owner or a profile
5590      * owner.
5591      * @throws IllegalArgumentException if the complexity level is not one of the four above.
5592      * @throws IllegalStateException if the caller is trying to set password complexity while there
5593      * are password requirements specified using {@link #setPasswordQuality(ComponentName, int)}
5594      * on the parent {@code DevicePolicyManager} instance.
5595      */
5596     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true)
setRequiredPasswordComplexity(@asswordComplexity int passwordComplexity)5597     public void setRequiredPasswordComplexity(@PasswordComplexity int passwordComplexity) {
5598         if (mService == null) {
5599             return;
5600         }
5601 
5602         try {
5603             mService.setRequiredPasswordComplexity(
5604                     mContext.getPackageName(), passwordComplexity, mParentInstance);
5605         } catch (RemoteException e) {
5606             throw e.rethrowFromSystemServer();
5607         }
5608     }
5609 
5610 
5611     /**
5612      * Gets the password complexity requirement set by {@link #setRequiredPasswordComplexity(int)},
5613      * for the current user.
5614      *
5615      * <p>The difference between this method and {@link #getPasswordComplexity()} is that this
5616      * method simply returns the value set by {@link #setRequiredPasswordComplexity(int)} while
5617      * {@link #getPasswordComplexity()} returns the complexity of the actual password.
5618      *
5619      * <p>This method can be called on the {@link DevicePolicyManager} instance
5620      * returned by {@link #getParentProfileInstance(ComponentName)} in order to get
5621      * restrictions on the parent profile.
5622      *
5623      * @throws SecurityException if the calling application is not a device owner or a profile
5624      * owner.
5625      */
5626     @PasswordComplexity
5627     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true)
getRequiredPasswordComplexity()5628     public int getRequiredPasswordComplexity() {
5629         if (mService == null) {
5630             return PASSWORD_COMPLEXITY_NONE;
5631         }
5632 
5633         try {
5634             return mService.getRequiredPasswordComplexity(
5635                     mContext.getPackageName(), mParentInstance);
5636         } catch (RemoteException e) {
5637             throw e.rethrowFromSystemServer();
5638         }
5639     }
5640 
5641     /**
5642      * Returns the password complexity that applies to this user, aggregated from other users if
5643      * necessary (for example, if the DPC has set password complexity requirements on the parent
5644      * profile DPM instance of a managed profile user, they would apply to the primary user on the
5645      * device).
5646      * @hide
5647      */
5648     @PasswordComplexity
getAggregatedPasswordComplexityForUser(int userId)5649     public int getAggregatedPasswordComplexityForUser(int userId) {
5650         return getAggregatedPasswordComplexityForUser(userId, false);
5651     }
5652 
5653     /**
5654      * Returns the password complexity that applies to this user, aggregated from other users if
5655      * necessary (for example, if the DPC has set password complexity requirements on the parent
5656      * profile DPM instance of a managed profile user, they would apply to the primary user on the
5657      * device). If {@code deviceWideOnly} is {@code true}, ignore policies set on the
5658      * managed profile DPM instance (as if the managed profile had separate work challenge).
5659      * @hide
5660      */
5661     @PasswordComplexity
getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly)5662     public int getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly) {
5663         if (mService == null) {
5664             return PASSWORD_COMPLEXITY_NONE;
5665         }
5666 
5667         try {
5668             return mService.getAggregatedPasswordComplexityForUser(userId, deviceWideOnly);
5669         } catch (RemoteException e) {
5670             throw e.rethrowFromSystemServer();
5671         }
5672     }
5673 
5674 
5675     /**
5676      * When called by a profile owner of a managed profile returns true if the profile uses unified
5677      * challenge with its parent user.
5678      *
5679      * <strong>Note</strong>: This method is not concerned with password quality and will return
5680      * false if the profile has empty password as a separate challenge.
5681      *
5682      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5683      * @throws SecurityException if {@code admin} is not a profile owner of a managed profile.
5684      * @see UserManager#DISALLOW_UNIFIED_PASSWORD
5685      */
isUsingUnifiedPassword(@onNull ComponentName admin)5686     public boolean isUsingUnifiedPassword(@NonNull ComponentName admin) {
5687         throwIfParentInstance("isUsingUnifiedPassword");
5688         if (mService != null) {
5689             try {
5690                 return mService.isUsingUnifiedPassword(admin);
5691             } catch (RemoteException e) {
5692                 throw e.rethrowFromSystemServer();
5693             }
5694         }
5695         return true;
5696     }
5697 
5698     /**
5699      * Returns whether the given user's credential will be sufficient for all password policy
5700      * requirement, once the user's profile has switched to unified challenge.
5701      *
5702      * <p>This is different from {@link #isActivePasswordSufficient()} since once the profile
5703      * switches to unified challenge, policies set explicitly on the profile will start to affect
5704      * the parent user.
5705      * @param userHandle the user whose password requirement will be checked
5706      * @param profileUser the profile user whose lockscreen challenge will be unified.
5707      * @hide
5708      */
isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser)5709     public boolean isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser) {
5710         if (mService != null) {
5711             try {
5712                 return mService.isPasswordSufficientAfterProfileUnification(userHandle,
5713                         profileUser);
5714             } catch (RemoteException e) {
5715                 throw e.rethrowFromSystemServer();
5716             }
5717         }
5718         return false;
5719     }
5720     /**
5721      * Retrieve the number of times the user has failed at entering a password since that last
5722      * successful password entry.
5723      * <p>
5724      * This method can be called on the {@link DevicePolicyManager} instance returned by
5725      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the number of failed
5726      * password attemts for the parent user.
5727      * <p>
5728      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
5729      * to be able to call this method; if it has not, a security exception will be thrown.
5730      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5731      * password is always empty and this method always returns 0.
5732      *
5733      * @return The number of times user has entered an incorrect password since the last correct
5734      *         password entry.
5735      * @throws SecurityException if the calling application does not own an active administrator
5736      *             that uses {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
5737      */
5738     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5739     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true)
getCurrentFailedPasswordAttempts()5740     public int getCurrentFailedPasswordAttempts() {
5741         return getCurrentFailedPasswordAttempts(myUserId());
5742     }
5743 
5744     /**
5745      * Retrieve the number of times the given user has failed at entering a
5746      * password since that last successful password entry.
5747      *
5748      * <p>The calling device admin must have requested
5749      * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call this method; if it has
5750      * not and it is not the system uid, a security exception will be thrown.
5751      *
5752      * @hide
5753      */
5754     @UnsupportedAppUsage
getCurrentFailedPasswordAttempts(int userHandle)5755     public int getCurrentFailedPasswordAttempts(int userHandle) {
5756         if (mService != null) {
5757             try {
5758                 return mService.getCurrentFailedPasswordAttempts(
5759                         mContext.getPackageName(), userHandle, mParentInstance);
5760             } catch (RemoteException e) {
5761                 throw e.rethrowFromSystemServer();
5762             }
5763         }
5764         return -1;
5765     }
5766 
5767     /**
5768      * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set.
5769      *
5770      * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set.
5771      * @hide
5772      */
getDoNotAskCredentialsOnBoot()5773     public boolean getDoNotAskCredentialsOnBoot() {
5774         if (mService != null) {
5775             try {
5776                 return mService.getDoNotAskCredentialsOnBoot();
5777             } catch (RemoteException e) {
5778                 throw e.rethrowFromSystemServer();
5779             }
5780         }
5781         return false;
5782     }
5783 
5784     /**
5785      * Setting this to a value greater than zero enables a policy that will perform a
5786      * device or profile wipe after too many incorrect device-unlock passwords have been entered.
5787      * This policy combines watching for failed passwords and wiping the device, and
5788      * requires that calling Device Admins request both
5789      * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
5790      * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
5791      * <p>
5792      * When this policy is set on the system or the main user, the device will be factory reset
5793      * after too many incorrect password attempts. When set on any other user, only the
5794      * corresponding user or profile will be wiped.
5795      * <p>
5796      * To implement any other policy (e.g. wiping data for a particular application only, erasing or
5797      * revoking credentials, or reporting the failure to a server), you should implement
5798      * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)} instead. Do not
5799      * use this API, because if the maximum count is reached, the device or profile will be wiped
5800      * immediately, and your callback will not be invoked.
5801      * <p>
5802      * This method can be called on the {@link DevicePolicyManager} instance returned by
5803      * {@link #getParentProfileInstance(ComponentName)} in order to set a value on the parent
5804      * profile.
5805      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5806      * password is always empty and this method has no effect - i.e. the policy is not set.
5807      *
5808      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
5809      *              caller is not a device admin.
5810      * @param num The number of failed password attempts at which point the device or profile will
5811      *            be wiped.
5812      * @throws SecurityException if {@code admin} is not null, and {@code admin} is not an active
5813      *            administrator or does not use both
5814      *            {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
5815      *            {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}, or if {@code admin} is null and the
5816      *            caller does not have permission to wipe the device.
5817      */
5818     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIPE_DATA, conditional = true)
5819     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setMaximumFailedPasswordsForWipe(@ullable ComponentName admin, int num)5820     public void setMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int num) {
5821         if (mService != null) {
5822             try {
5823                 mService.setMaximumFailedPasswordsForWipe(
5824                         admin, mContext.getPackageName(), num, mParentInstance);
5825             } catch (RemoteException e) {
5826                 throw e.rethrowFromSystemServer();
5827             }
5828         }
5829     }
5830 
5831     /**
5832      * Retrieve the current maximum number of login attempts that are allowed before the device
5833      * or profile is wiped, for a particular admin or all admins that set restrictions on this user
5834      * and its participating profiles. Restrictions on profiles that have a separate challenge are
5835      * not taken into account.
5836      *
5837      * <p>This method can be called on the {@link DevicePolicyManager} instance
5838      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5839      * the value for the parent profile.
5840      *
5841      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5842      * password is always empty and this method returns a default value (0) indicating that the
5843      * policy is not set.
5844      *
5845      * @param admin The name of the admin component to check, or {@code null} to aggregate
5846      * all admins.
5847      */
5848     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin)5849     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) {
5850         return getMaximumFailedPasswordsForWipe(admin, myUserId());
5851     }
5852 
5853     /** @hide per-user version */
5854     @UnsupportedAppUsage
5855     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin, int userHandle)5856     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) {
5857         if (mService != null) {
5858             try {
5859                 return mService.getMaximumFailedPasswordsForWipe(
5860                         admin, userHandle, mParentInstance);
5861             } catch (RemoteException e) {
5862                 throw e.rethrowFromSystemServer();
5863             }
5864         }
5865         return 0;
5866     }
5867 
5868     /**
5869      * Returns the user that will be wiped first when too many failed attempts are made to unlock
5870      * user {@code userHandle}. That user is either the same as {@code userHandle} or belongs to the
5871      * same profile group. When there is no such policy, returns {@code UserHandle.USER_NULL}.
5872      * E.g. managed profile user may be wiped as a result of failed primary profile password
5873      * attempts when using unified challenge. Primary user may be wiped as a result of failed
5874      * password attempts on the managed profile on an organization-owned device.
5875      * @hide Used only by Keyguard
5876      */
5877     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getProfileWithMinimumFailedPasswordsForWipe(int userHandle)5878     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
5879         if (mService != null) {
5880             try {
5881                 return mService.getProfileWithMinimumFailedPasswordsForWipe(
5882                         userHandle, mParentInstance);
5883             } catch (RemoteException e) {
5884                 throw e.rethrowFromSystemServer();
5885             }
5886         }
5887         return UserHandle.USER_NULL;
5888     }
5889 
5890     /**
5891      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't allow other admins
5892      * to change the password again until the user has entered it.
5893      */
5894     public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
5895 
5896     /**
5897      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't ask for user
5898      * credentials on device boot.
5899      * If the flag is set, the device can be booted without asking for user password.
5900      * The absence of this flag does not change the current boot requirements. This flag
5901      * can be set by the device owner only. If the app is not the device owner, the flag
5902      * is ignored. Once the flag is set, it cannot be reverted back without resetting the
5903      * device to factory defaults.
5904      */
5905     public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
5906 
5907     /**
5908      * Force a new password for device unlock (the password needed to access the entire device) or
5909      * the work profile challenge on the current user. This takes effect immediately.
5910      *
5911      * <p> Before {@link android.os.Build.VERSION_CODES#N}, this API is available to device admin,
5912      * profile owner and device owner. Starting from {@link android.os.Build.VERSION_CODES#N},
5913      * legacy device admin (who is not also profile owner or device owner) can only call this
5914      * API to set a new password if there is currently no password set. Profile owner and device
5915      * owner can continue to force change an existing password as long as the target user is
5916      * unlocked, although device owner will not be able to call this API at all if there is also a
5917      * managed profile on the device.
5918      *
5919      * <p> Between {@link android.os.Build.VERSION_CODES#O},
5920      * {@link android.os.Build.VERSION_CODES#P} and {@link android.os.Build.VERSION_CODES#Q},
5921      * profile owner and devices owner targeting SDK level {@link android.os.Build.VERSION_CODES#O}
5922      * or above who attempt to call this API will receive {@link SecurityException}; they are
5923      * encouraged to migrate to the new {@link #resetPasswordWithToken} API instead.
5924      * Profile owner and device owner targeting older SDK levels are not affected: they continue
5925      * to experience the existing behaviour described in the previous paragraph.
5926      *
5927      * <p><em>Starting from {@link android.os.Build.VERSION_CODES#R}, this API is no longer
5928      * supported in most cases.</em> Device owner and profile owner calling
5929      * this API will receive {@link SecurityException} if they target SDK level
5930      * {@link android.os.Build.VERSION_CODES#O} or above, or they will receive a silent failure
5931      * (API returning {@code false}) if they target lower SDK level.
5932      * For legacy device admins, this API throws {@link SecurityException} if they target SDK level
5933      * {@link android.os.Build.VERSION_CODES#N} or above, and returns {@code false} otherwise. Only
5934      * privileged apps holding RESET_PASSWORD permission which are part of
5935      * the system factory image can still call this API to set a new password if there is currently
5936      * no password set. In this case, if the device already has a password, this API will throw
5937      * {@link SecurityException}.
5938      *
5939      * <p>
5940      * The given password must be sufficient for the current password quality and length constraints
5941      * as returned by {@link #getPasswordQuality(ComponentName)} and
5942      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
5943      * it will be rejected and false returned. Note that the password may be a stronger quality
5944      * (containing alphanumeric characters when the requested quality is only numeric), in which
5945      * case the currently active quality will be increased to match.
5946      *
5947      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
5948      * methods does nothing.
5949      * <p>
5950      * The calling device admin must have requested
5951      * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call this method; if it has
5952      * not, a security exception will be thrown.
5953      *
5954      * @param password The new password for the user. Null or empty clears the password.
5955      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
5956      *            {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
5957      * @return Returns true if the password was applied, or false if it is not acceptable for the
5958      *         current constraints.
5959      * @throws SecurityException if the calling application does not own an active administrator
5960      *             that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
5961      * @throws IllegalStateException if the calling user is locked or has a managed profile.
5962      * @deprecated Please use {@link #resetPasswordWithToken} instead.
5963      */
5964     @Deprecated
5965     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
resetPassword(String password, int flags)5966     public boolean resetPassword(String password, int flags) {
5967         throwIfParentInstance("resetPassword");
5968         if (mService != null) {
5969             try {
5970                 return mService.resetPassword(password, flags);
5971             } catch (RemoteException e) {
5972                 throw e.rethrowFromSystemServer();
5973             }
5974         }
5975         return false;
5976     }
5977 
5978     /**
5979      * Called by a profile or device owner to provision a token which can later be used to reset the
5980      * device lockscreen password (if called by device owner), or managed profile challenge (if
5981      * called by profile owner), via {@link #resetPasswordWithToken}.
5982      * <p>
5983      * If the user currently has a lockscreen password, the provisioned token will not be
5984      * immediately usable; it only becomes active after the user performs a confirm credential
5985      * operation, which can be triggered by {@link KeyguardManager#createConfirmDeviceCredentialIntent}.
5986      * If the user has no lockscreen password, the token is activated immediately. In all cases,
5987      * the active state of the current token can be checked by {@link #isResetPasswordTokenActive}.
5988      * For security reasons, un-activated tokens are only stored in memory and will be lost once
5989      * the device reboots. In this case a new token needs to be provisioned again.
5990      * <p>
5991      * Once provisioned and activated, the token will remain effective even if the user changes
5992      * or clears the lockscreen password.
5993      * <p>
5994      * <em>This token is highly sensitive and should be treated at the same level as user
5995      * credentials. In particular, NEVER store this token on device in plaintext. Do not store
5996      * the plaintext token in device-encrypted storage if it will be needed to reset password on
5997      * file-based encryption devices before user unlocks. Consider carefully how any password token
5998      * will be stored on your server and who will need access to them. Tokens may be the subject of
5999      * legal access requests.
6000      * </em>
6001      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
6002      * reset token is not set and this method returns false.
6003      *
6004      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
6005      *              caller is not a device admin.
6006      * @param token a secure token a least 32-byte long, which must be generated by a
6007      *        cryptographically strong random number generator.
6008      * @return true if the operation is successful, false otherwise.
6009      * @throws SecurityException if admin is not a device or profile owner.
6010      * @throws IllegalArgumentException if the supplied token is invalid.
6011      */
6012     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
6013     @RequiresPermission(value = MANAGE_DEVICE_POLICY_RESET_PASSWORD, conditional = true)
setResetPasswordToken(@ullable ComponentName admin, byte[] token)6014     public boolean setResetPasswordToken(@Nullable ComponentName admin, byte[] token) {
6015         throwIfParentInstance("setResetPasswordToken");
6016         if (mService != null) {
6017             try {
6018                 return mService.setResetPasswordToken(admin, mContext.getPackageName(), token);
6019             } catch (RemoteException e) {
6020                 throw e.rethrowFromSystemServer();
6021             }
6022         }
6023         return false;
6024     }
6025 
6026     /**
6027      * Called by a profile, device owner or holder of the permission
6028      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_RESET_PASSWORD}
6029      * to revoke the current password reset token.
6030      *
6031      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
6032      * method has no effect - the reset token should not have been set in the first place - and
6033      * false is returned.
6034      *
6035      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
6036      *              caller is not a device admin.
6037      * @return true if the operation is successful, false otherwise.
6038      * @throws SecurityException if admin is not a device or profile owner and if the caller does
6039      * not the permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_RESET_PASSWORD}.
6040      */
6041     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
6042     @RequiresPermission(value = MANAGE_DEVICE_POLICY_RESET_PASSWORD, conditional = true)
clearResetPasswordToken(@ullable ComponentName admin)6043     public boolean clearResetPasswordToken(@Nullable ComponentName admin) {
6044         throwIfParentInstance("clearResetPasswordToken");
6045         if (mService != null) {
6046             try {
6047                 return mService.clearResetPasswordToken(admin, mContext.getPackageName());
6048             } catch (RemoteException e) {
6049                 throw e.rethrowFromSystemServer();
6050             }
6051         }
6052         return false;
6053     }
6054 
6055     /**
6056      * Called by a profile, device owner or a holder of the permission
6057      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_RESET_PASSWORD}
6058      * to check if the current reset password token is active.
6059      *
6060      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
6061      * false is always returned.
6062      *
6063      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
6064      *              caller is not a device admin.
6065      * @return true if the token is active, false otherwise.
6066      * @throws SecurityException if admin is not a device or profile owner and not a holder of the
6067      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_RESET_PASSWORD}
6068      * @throws IllegalStateException if no token has been set.
6069      */
6070     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
6071     @RequiresPermission(value = MANAGE_DEVICE_POLICY_RESET_PASSWORD, conditional = true)
isResetPasswordTokenActive(@ullable ComponentName admin)6072     public boolean isResetPasswordTokenActive(@Nullable ComponentName admin) {
6073         throwIfParentInstance("isResetPasswordTokenActive");
6074         if (mService != null) {
6075             try {
6076                 return mService.isResetPasswordTokenActive(admin, mContext.getPackageName());
6077             } catch (RemoteException e) {
6078                 throw e.rethrowFromSystemServer();
6079             }
6080         }
6081         return false;
6082     }
6083 
6084     /**
6085      * Called by device or profile owner to force set a new device unlock password or a managed
6086      * profile challenge on current user. This takes effect immediately.
6087      * <p>
6088      * Unlike {@link #resetPassword}, this API can change the password even before the user or
6089      * device is unlocked or decrypted. The supplied token must have been previously provisioned via
6090      * {@link #setResetPasswordToken}, and in active state {@link #isResetPasswordTokenActive}.
6091      * <p>
6092      * The given password must be sufficient for the current password quality and length constraints
6093      * as returned by {@link #getPasswordQuality(ComponentName)} and
6094      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
6095      * it will be rejected and false returned. Note that the password may be a stronger quality, for
6096      * example, a password containing alphanumeric characters when the requested quality is only
6097      * numeric.
6098      * <p>
6099      * Calling with a {@code null} or empty password will clear any existing PIN, pattern or
6100      * password if the current password constraints allow it.
6101      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
6102      * calling this methods has no effect - the password is always empty - and false is returned.
6103      *
6104      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
6105      *              caller is not a device admin.
6106      * @param password The new password for the user. {@code null} or empty clears the password.
6107      * @param token the password reset token previously provisioned by
6108      *        {@link #setResetPasswordToken}.
6109      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
6110      *        {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
6111      * @return Returns true if the password was applied, or false if it is not acceptable for the
6112      *         current constraints.
6113      * @throws SecurityException if admin is not a device or profile owner.
6114      * @throws IllegalStateException if the provided token is not valid.
6115      */
6116     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
6117     @RequiresPermission(value = MANAGE_DEVICE_POLICY_RESET_PASSWORD, conditional = true)
resetPasswordWithToken(@ullable ComponentName admin, String password, byte[] token, int flags)6118     public boolean resetPasswordWithToken(@Nullable ComponentName admin, String password,
6119             byte[] token, int flags) {
6120         throwIfParentInstance("resetPassword");
6121         if (mService != null) {
6122             try {
6123                 return mService.resetPasswordWithToken(admin, mContext.getPackageName(), password,
6124                         token, flags);
6125             } catch (RemoteException e) {
6126                 throw e.rethrowFromSystemServer();
6127             }
6128         }
6129         return false;
6130     }
6131 
6132     /**
6133      * Called by an application that is administering the device to set the maximum time for user
6134      * activity until the device will lock. This limits the length that the user can set. It takes
6135      * effect immediately.
6136      * <p>
6137      * A calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
6138      * to be able to call this method; if it has not, a security exception will be thrown.
6139      * <p>
6140      * This method can be called on the {@link DevicePolicyManager} instance returned by
6141      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
6142      * profile.
6143      *
6144      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
6145      *              caller is not a device admin
6146      * @param timeMs The new desired maximum time to lock in milliseconds. A value of 0 means there
6147      *            is no restriction.
6148      * @throws SecurityException if {@code admin} is not an active administrator or it does not use
6149      *             {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
6150      */
6151     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK, conditional = true)
setMaximumTimeToLock(@ullable ComponentName admin, long timeMs)6152     public void setMaximumTimeToLock(@Nullable ComponentName admin, long timeMs) {
6153         if (mService != null) {
6154             try {
6155                 mService.setMaximumTimeToLock(admin, mContext.getPackageName(), timeMs, mParentInstance);
6156             } catch (RemoteException e) {
6157                 throw e.rethrowFromSystemServer();
6158             }
6159         }
6160     }
6161 
6162     /**
6163      * Retrieve the current maximum time to unlock for a particular admin or all admins that set
6164      * restrictions on this user and its participating profiles. Restrictions on profiles that have
6165      * a separate challenge are not taken into account.
6166      *
6167      * <p>This method can be called on the {@link DevicePolicyManager} instance
6168      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
6169      * restrictions on the parent profile.
6170      *
6171      * @param admin The name of the admin component to check, or {@code null} to aggregate
6172      * all admins.
6173      * @return time in milliseconds for the given admin or the minimum value (strictest) of
6174      * all admins if admin is null. Returns 0 if there are no restrictions.
6175      */
getMaximumTimeToLock(@ullable ComponentName admin)6176     public long getMaximumTimeToLock(@Nullable ComponentName admin) {
6177         return getMaximumTimeToLock(admin, myUserId());
6178     }
6179 
6180     /** @hide per-user version */
6181     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getMaximumTimeToLock(@ullable ComponentName admin, int userHandle)6182     public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) {
6183         if (mService != null) {
6184             try {
6185                 return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance);
6186             } catch (RemoteException e) {
6187                 throw e.rethrowFromSystemServer();
6188             }
6189         }
6190         return 0;
6191     }
6192 
6193     /**
6194      * Called by a device/profile owner to set the timeout after which unlocking with secondary, non
6195      * strong auth (e.g. fingerprint, face, trust agents) times out, i.e. the user has to use a
6196      * strong authentication method like password, pin or pattern.
6197      *
6198      * <p>This timeout is used internally to reset the timer to require strong auth again after
6199      * specified timeout each time it has been successfully used.
6200      *
6201      * <p>Fingerprint can also be disabled altogether using {@link #KEYGUARD_DISABLE_FINGERPRINT}.
6202      *
6203      * <p>Trust agents can also be disabled altogether using {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
6204      *
6205      * <p>A calling device admin can verify the value it has set by calling
6206      * {@link #getRequiredStrongAuthTimeout(ComponentName)} and passing in its instance.
6207      *
6208      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
6209      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
6210      * profile.
6211      *
6212      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
6213      * calling this methods has no effect - i.e. the timeout is not set.
6214      *
6215      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
6216      *              caller is not a device admin
6217      * @param timeoutMs The new timeout in milliseconds, after which the user will have to unlock
6218      *         with strong authentication method. A value of 0 means the admin is not participating
6219      *         in controlling the timeout.
6220      *         The minimum and maximum timeouts are platform-defined and are typically 1 hour and
6221      *         72 hours, respectively. Though discouraged, the admin may choose to require strong
6222      *         auth at all times using {@link #KEYGUARD_DISABLE_FINGERPRINT} and/or
6223      *         {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
6224      *
6225      * @throws SecurityException if {@code admin} is not a device or profile owner.
6226      */
6227     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
6228     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true)
setRequiredStrongAuthTimeout(@ullable ComponentName admin, long timeoutMs)6229     public void setRequiredStrongAuthTimeout(@Nullable ComponentName admin,
6230             long timeoutMs) {
6231         if (mService != null) {
6232             try {
6233                 mService.setRequiredStrongAuthTimeout(
6234                         admin, mContext.getPackageName(), timeoutMs, mParentInstance);
6235             } catch (RemoteException e) {
6236                 throw e.rethrowFromSystemServer();
6237             }
6238         }
6239     }
6240 
6241     /**
6242      * Determine for how long the user will be able to use secondary, non strong auth for
6243      * authentication, since last strong method authentication (password, pin or pattern) was used.
6244      * After the returned timeout the user is required to use strong authentication method.
6245      *
6246      * <p>This method can be called on the {@link DevicePolicyManager} instance
6247      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
6248      * restrictions on the parent profile.
6249      *
6250      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
6251      * 0 is returned to indicate that no timeout is configured.
6252      *
6253      * @param admin The name of the admin component to check, or {@code null} to aggregate
6254      *         across all participating admins.
6255      * @return The timeout in milliseconds or 0 if not configured for the provided admin.
6256      */
6257     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getRequiredStrongAuthTimeout(@ullable ComponentName admin)6258     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin) {
6259         return getRequiredStrongAuthTimeout(admin, myUserId());
6260     }
6261 
6262     /** @hide per-user version */
6263     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
6264     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getRequiredStrongAuthTimeout(@ullable ComponentName admin, @UserIdInt int userId)6265     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin, @UserIdInt int userId) {
6266         if (mService != null) {
6267             try {
6268                 return mService.getRequiredStrongAuthTimeout(admin, userId, mParentInstance);
6269             } catch (RemoteException e) {
6270                 throw e.rethrowFromSystemServer();
6271             }
6272         }
6273         return DEFAULT_STRONG_AUTH_TIMEOUT_MS;
6274     }
6275 
6276     /**
6277      * Flag for {@link #lockNow(int)}: also evict the user's credential encryption key from the
6278      * keyring. The user's credential will need to be entered again in order to derive the
6279      * credential encryption key that will be stored back in the keyring for future use.
6280      * <p>
6281      * This flag can only be used by a profile owner when locking a managed profile when
6282      * {@link #getStorageEncryptionStatus} returns {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
6283      * <p>
6284      * In order to secure user data, the user will be stopped and restarted so apps should wait
6285      * until they are next run to perform further actions.
6286      */
6287     public static final int FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY = 1;
6288 
6289     /** @hide */
6290     @Retention(RetentionPolicy.SOURCE)
6291     @IntDef(flag = true, prefix = { "FLAG_EVICT_" }, value = {
6292             FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY
6293     })
6294     public @interface LockNowFlag {}
6295 
6296     /**
6297      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
6298      * this call.
6299      * <p>
6300      * This method secures the device in response to an urgent situation, such as a lost or stolen
6301      * device. After this method is called, the device must be unlocked using strong authentication
6302      * (PIN, pattern, or password). This API is intended for use only by device admins.
6303      * <p>
6304      * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have
6305      * the LOCK_DEVICE permission or the device must have the device admin feature; if neither is
6306      * true, then the method will return without completing any action. Before version
6307      * {@link android.os.Build.VERSION_CODES#R}, the device needed the device admin feature,
6308      * regardless of the caller's permissions.
6309      * <p>
6310      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
6311      * to be able to call this method; if it has not, a security exception will be thrown.
6312      * <p>
6313      * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
6314      * the device. Device admins who find the device in this state can lock an otherwise-insecure
6315      * device by first calling {@link #resetPassword} to set the password and then lock the device.
6316      * <p>
6317      * This method can be called on the {@link DevicePolicyManager} instance returned by
6318      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
6319      * <p>
6320      * NOTE: on {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, this
6321      * method doesn't turn off the screen as it would be a driving safety distraction.
6322      * <p>
6323      * Equivalent to calling {@link #lockNow(int)} with no flags.
6324      *
6325      * @throws SecurityException if the calling application does not own an active administrator
6326      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
6327      */
6328     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK, conditional = true)
lockNow()6329     public void lockNow() {
6330         lockNow(0);
6331     }
6332 
6333     /**
6334      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
6335      * this call.
6336      * <p>
6337      * This method secures the device in response to an urgent situation, such as a lost or stolen
6338      * device. After this method is called, the device must be unlocked using strong authentication
6339      * (PIN, pattern, or password). This API is for use only by device admins and holders of the
6340      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK} permission.
6341      * <p>
6342      * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have
6343      * the LOCK_DEVICE permission or the device must have the device admin feature; if neither is
6344      * true, then the method will return without completing any action. Before version
6345      * {@link android.os.Build.VERSION_CODES#R}, the device needed the device admin feature,
6346      * regardless of the caller's permissions.
6347      * <p>
6348      * A calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
6349      * to be able to call this method; if it has not, a security exception will be thrown.
6350      * <p>
6351      * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
6352      * the device. Device admins who find the device in this state can lock an otherwise-insecure
6353      * device by first calling {@link #resetPassword} to set the password and then lock the device.
6354      * <p>
6355      * This method can be called on the {@link DevicePolicyManager} instance returned by
6356      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile as
6357      * well as the managed profile.
6358      * <p>
6359      * NOTE: In order to lock the parent profile and evict the encryption key of the managed
6360      * profile, {@link #lockNow()} must be called twice: First, {@link #lockNow()} should be called
6361      * on the {@link DevicePolicyManager} instance returned by
6362      * {@link #getParentProfileInstance(ComponentName)}, then {@link #lockNow(int)} should be
6363      * called on the {@link DevicePolicyManager} instance associated with the managed profile,
6364      * with the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag.
6365      * Calling the method twice in this order ensures that all users are locked and does not
6366      * stop the device admin on the managed profile from issuing a second call to lock its own
6367      * profile.
6368      * <p>
6369      * NOTE: on {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, this
6370      * method doesn't turn off the screen as it would be a driving safety distraction.
6371      *
6372      * @param flags May be 0 or {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}.
6373      * @throws SecurityException if the calling application does not own an active administrator
6374      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} and the does not hold
6375      *             the {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK} permission, or
6376      *             the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is passed by an
6377      *             application that is not a profile owner of a managed profile.
6378      * @throws IllegalArgumentException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is
6379      *             passed when locking the parent profile.
6380      * @throws UnsupportedOperationException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}
6381      *             flag is passed when {@link #getStorageEncryptionStatus} does not return
6382      *             {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
6383      */
6384     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK, conditional = true)
lockNow(@ockNowFlag int flags)6385     public void lockNow(@LockNowFlag int flags) {
6386         if (mService != null) {
6387             try {
6388                 mService.lockNow(flags, mContext.getPackageName(), mParentInstance);
6389             } catch (RemoteException e) {
6390                 throw e.rethrowFromSystemServer();
6391             }
6392         }
6393     }
6394 
6395     /**
6396      * Flag for {@link #wipeData(int)}: also erase the device's external
6397      * storage (such as SD cards).
6398      */
6399     public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
6400 
6401     /**
6402      * Flag for {@link #wipeData(int)}: also erase the factory reset protection
6403      * data.
6404      *
6405      * <p>This flag may only be set by device owner admins; if it is set by
6406      * other admins a {@link SecurityException} will be thrown.
6407      */
6408     public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
6409 
6410     /**
6411      * Flag for {@link #wipeData(int)}: also erase the device's eUICC data.
6412      */
6413     public static final int WIPE_EUICC = 0x0004;
6414 
6415     /**
6416      * Flag for {@link #wipeData(int)}: won't show reason for wiping to the user.
6417      */
6418     public static final int WIPE_SILENTLY = 0x0008;
6419 
6420     /**
6421      * See {@link #wipeData(int, CharSequence)}
6422      *
6423      * @param flags Bit mask of additional options: currently supported flags are
6424      *              {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA},
6425      *              {@link #WIPE_EUICC} and {@link #WIPE_SILENTLY}.
6426      * @throws SecurityException if the calling application does not own an active
6427      *                           administrator
6428      *                           that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} and is
6429      *                           not granted the
6430      *                           {@link android.Manifest.permission#MASTER_CLEAR} or
6431      *                           {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_WIPE_DATA}
6432      *                            permissions.
6433      * @throws IllegalStateException if called on last full-user or system-user
6434      * @see #wipeDevice(int)
6435      * @see #wipeData(int, CharSequence)
6436      */
6437     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIPE_DATA, conditional = true)
wipeData(int flags)6438     public void wipeData(int flags) {
6439         wipeDataInternal(flags,
6440                 /* wipeReasonForUser= */ "",
6441                 /* factoryReset= */ false);
6442     }
6443 
6444     /**
6445      * Ask that all user data be wiped.
6446      *
6447      * <p>
6448      * If called as a secondary user or managed profile, the user itself and its associated user
6449      * data will be wiped. In particular, If the caller is a profile owner of an
6450      * organization-owned managed profile, calling this method will relinquish the device for
6451      * personal use, removing the managed profile and all policies set by the profile owner.
6452      * </p>
6453      *
6454      * <p> Calling this method from the primary user will only work if the calling app is
6455      * targeting SDK level {@link Build.VERSION_CODES#TIRAMISU} or below, in which case it will
6456      * cause the device to reboot, erasing all device data - including all the secondary users
6457      * and their data - while booting up. If an app targeting SDK level
6458      * {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE} and above is calling this method from the
6459      * primary user or last full user, {@link IllegalStateException} will be thrown. </p>
6460      *
6461      * If an app wants to wipe the entire device irrespective of which user they are from, they
6462      * should use {@link #wipeDevice} instead.
6463      *
6464      * @param flags Bit mask of additional options: currently supported flags are
6465      *            {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA} and
6466      *            {@link #WIPE_EUICC}.
6467      * @param reason a string that contains the reason for wiping data, which can be
6468      *            presented to the user.
6469      * @throws SecurityException if the calling application does not own an active administrator
6470      *            that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} and is not granted the
6471      *            {@link android.Manifest.permission#MASTER_CLEAR} or
6472      *            {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_WIPE_DATA} permissions.
6473      * @throws IllegalArgumentException if the input reason string is null or empty, or if
6474      *            {@link #WIPE_SILENTLY} is set.
6475      * @throws IllegalStateException if called on last full-user or system-user
6476      * @see #wipeDevice(int)
6477      * @see #wipeData(int)
6478      */
6479     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIPE_DATA, conditional = true)
wipeData(int flags, @NonNull CharSequence reason)6480     public void wipeData(int flags, @NonNull CharSequence reason) {
6481         Objects.requireNonNull(reason, "reason string is null");
6482         Preconditions.checkStringNotEmpty(reason, "reason string is empty");
6483         Preconditions.checkArgument((flags & WIPE_SILENTLY) == 0, "WIPE_SILENTLY cannot be set");
6484         wipeDataInternal(flags, reason.toString(), /* factoryReset= */ false);
6485     }
6486 
6487     /**
6488      * Ask that the device be wiped and factory reset.
6489      *
6490      * <p>
6491      * The calling Device Owner or Organization Owned Profile Owner must have requested
6492      * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to be able to call this method; if it has
6493      * not, a security exception will be thrown.
6494      *
6495      * @param flags Bit mask of additional options: currently supported flags are
6496      *              {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA},
6497      *              {@link #WIPE_EUICC} and {@link #WIPE_SILENTLY}.
6498      * @throws SecurityException if the calling application does not own an active administrator
6499      *                       that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} and is not
6500      *                       granted the {@link android.Manifest.permission#MASTER_CLEAR}
6501      *                       or both the
6502      *                       {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_WIPE_DATA} and
6503      *                       {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_ACROSS_USERS}
6504      *                       permissions.
6505      * @see #wipeData(int)
6506      * @see #wipeData(int, CharSequence)
6507      */
6508     // TODO(b/255323293) Add host-side tests
6509     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIPE_DATA, conditional = true)
wipeDevice(int flags)6510     public void wipeDevice(int flags) {
6511         wipeDataInternal(flags,
6512                 /* wipeReasonForUser= */ "",
6513                 /* factoryReset= */ true);
6514     }
6515 
6516     /**
6517      * Internal function for {@link #wipeData(int)}, {@link #wipeData(int, CharSequence)}
6518      * and {@link #wipeDevice(int)} to call.
6519      *
6520      * @hide
6521      * @see #wipeData(int)
6522      * @see #wipeData(int, CharSequence)
6523      * @see #wipeDevice(int)
6524      */
wipeDataInternal(int flags, @NonNull String wipeReasonForUser, boolean factoryReset)6525     private void wipeDataInternal(int flags, @NonNull String wipeReasonForUser,
6526             boolean factoryReset) {
6527         if (mService != null) {
6528             try {
6529                 mService.wipeDataWithReason(mContext.getPackageName(), flags, wipeReasonForUser,
6530                         mParentInstance, factoryReset);
6531             } catch (RemoteException e) {
6532                 throw e.rethrowFromSystemServer();
6533             }
6534         }
6535     }
6536 
6537     /**
6538      * Callable by device owner or profile owner of an organization-owned device, to set a
6539      * factory reset protection (FRP) policy. When a new policy is set, the system
6540      * notifies the FRP management agent of a policy change by broadcasting
6541      * {@code ACTION_RESET_PROTECTION_POLICY_CHANGED}.
6542      *
6543      * @param admin  Which {@link DeviceAdminReceiver} this request is associated with. Null if the
6544      *               caller is not a device admin
6545      * @param policy the new FRP policy, or {@code null} to clear the current policy.
6546      * @throws SecurityException if {@code admin} is not a device owner or a profile owner of
6547      *                           an organization-owned device.
6548      * @throws UnsupportedOperationException if factory reset protection is not
6549      *                           supported on the device.
6550      */
6551     @RequiresPermission(value = MANAGE_DEVICE_POLICY_FACTORY_RESET, conditional = true)
setFactoryResetProtectionPolicy(@ullable ComponentName admin, @Nullable FactoryResetProtectionPolicy policy)6552     public void setFactoryResetProtectionPolicy(@Nullable ComponentName admin,
6553             @Nullable FactoryResetProtectionPolicy policy) {
6554         throwIfParentInstance("setFactoryResetProtectionPolicy");
6555         if (mService != null) {
6556             try {
6557                 mService.setFactoryResetProtectionPolicy(admin, mContext.getPackageName(), policy);
6558             } catch (RemoteException e) {
6559                 throw e.rethrowFromSystemServer();
6560             }
6561         }
6562     }
6563 
6564     /**
6565      * Callable by device owner or profile owner of an organization-owned device, to retrieve
6566      * the current factory reset protection (FRP) policy set previously by
6567      * {@link #setFactoryResetProtectionPolicy}.
6568      * <p>
6569      * This method can also be called by the FRP management agent on device or with the permission
6570      * {@link android.Manifest.permission#MASTER_CLEAR}, in which case, it can pass {@code null}
6571      * as the ComponentName.
6572      *
6573      * @param admin Which {@link DeviceAdminReceiver} this request is associated with or
6574      *              {@code null} if the caller is not a device admin
6575      * @return The current FRP policy object or {@code null} if no policy is set.
6576      * @throws SecurityException if {@code admin} is not a device owner, a profile owner of
6577      *                           an organization-owned device or the FRP management agent.
6578      * @throws UnsupportedOperationException if factory reset protection is not
6579      *                           supported on the device.
6580      */
6581     @RequiresPermission(value = MANAGE_DEVICE_POLICY_FACTORY_RESET, conditional = true)
getFactoryResetProtectionPolicy( @ullable ComponentName admin)6582     public @Nullable FactoryResetProtectionPolicy getFactoryResetProtectionPolicy(
6583             @Nullable ComponentName admin) {
6584         throwIfParentInstance("getFactoryResetProtectionPolicy");
6585         if (mService != null) {
6586             try {
6587                 return mService.getFactoryResetProtectionPolicy(admin);
6588             } catch (RemoteException e) {
6589                 throw e.rethrowFromSystemServer();
6590             }
6591         }
6592         return null;
6593     }
6594 
6595     /**
6596      * Send a lost mode location update to the admin. This API is limited to organization-owned
6597      * devices, which includes devices with a device owner or devices with a profile owner on an
6598      * organization-owned managed profile.
6599      *
6600      * <p>The caller must hold the
6601      * {@link android.Manifest.permission#TRIGGER_LOST_MODE} permission.
6602      *
6603      * <p>Register a broadcast receiver to receive lost mode location updates. This receiver should
6604      * subscribe to the {@link #ACTION_LOST_MODE_LOCATION_UPDATE} action and receive the location
6605      * from an intent extra {@link #EXTRA_LOST_MODE_LOCATION}.
6606      *
6607      * <p> Not for use by third-party applications.
6608      *
6609      * @param executor The executor through which the callback should be invoked.
6610      * @param callback A callback object that will inform the caller whether a lost mode location
6611      *                 update was successfully sent
6612      * @hide
6613      */
6614     @SystemApi
6615     @RequiresPermission(android.Manifest.permission.TRIGGER_LOST_MODE)
sendLostModeLocationUpdate(@onNull @allbackExecutor Executor executor, @NonNull Consumer<Boolean> callback)6616     public void sendLostModeLocationUpdate(@NonNull @CallbackExecutor Executor executor,
6617             @NonNull Consumer<Boolean> callback) {
6618         throwIfParentInstance("sendLostModeLocationUpdate");
6619         if (mService == null) {
6620             executeCallback(AndroidFuture.completedFuture(false), executor, callback);
6621             return;
6622         }
6623         try {
6624             final AndroidFuture<Boolean> future = new AndroidFuture<>();
6625             mService.sendLostModeLocationUpdate(future);
6626             executeCallback(future, executor, callback);
6627         } catch (RemoteException e) {
6628             throw e.rethrowFromSystemServer();
6629         }
6630     }
6631 
executeCallback(AndroidFuture<Boolean> future, @CallbackExecutor @NonNull Executor executor, Consumer<Boolean> callback)6632     private void executeCallback(AndroidFuture<Boolean> future,
6633             @CallbackExecutor @NonNull Executor executor,
6634             Consumer<Boolean> callback) {
6635         future.whenComplete((result, error) -> executor.execute(() -> {
6636             final long token = Binder.clearCallingIdentity();
6637             try {
6638                 if (error != null) {
6639                     callback.accept(false);
6640                 } else {
6641                     callback.accept(result);
6642                 }
6643             } finally {
6644                 Binder.restoreCallingIdentity(token);
6645             }
6646         }));
6647     }
6648 
6649     /**
6650      * Called by an application that is administering the device to set the
6651      * global proxy and exclusion list.
6652      * <p>
6653      * The calling device admin must have requested
6654      * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
6655      * this method; if it has not, a security exception will be thrown.
6656      * Only the first device admin can set the proxy. If a second admin attempts
6657      * to set the proxy, the {@link ComponentName} of the admin originally setting the
6658      * proxy will be returned. If successful in setting the proxy, {@code null} will
6659      * be returned.
6660      * The method can be called repeatedly by the device admin alrady setting the
6661      * proxy to update the proxy and exclusion list.
6662      *
6663      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6664      * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
6665      *            Pass Proxy.NO_PROXY to reset the proxy.
6666      * @param exclusionList a list of domains to be excluded from the global proxy.
6667      * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
6668      *            of the device admin that sets the proxy.
6669      * @hide
6670      */
6671     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setGlobalProxy(@onNull ComponentName admin, Proxy proxySpec, List<String> exclusionList )6672     public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
6673             List<String> exclusionList ) {
6674         throwIfParentInstance("setGlobalProxy");
6675         if (proxySpec == null) {
6676             throw new NullPointerException();
6677         }
6678         if (mService != null) {
6679             try {
6680                 String hostSpec;
6681                 String exclSpec;
6682                 if (proxySpec.equals(Proxy.NO_PROXY)) {
6683                     hostSpec = null;
6684                     exclSpec = null;
6685                 } else {
6686                     if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
6687                         throw new IllegalArgumentException();
6688                     }
6689                     final Pair<String, String> proxyParams =
6690                             getProxyParameters(proxySpec, exclusionList);
6691                     hostSpec = proxyParams.first;
6692                     exclSpec = proxyParams.second;
6693                 }
6694                 return mService.setGlobalProxy(admin, hostSpec, exclSpec);
6695             } catch (RemoteException e) {
6696                 throw e.rethrowFromSystemServer();
6697             }
6698         }
6699         return null;
6700     }
6701 
6702     /**
6703      * Build HTTP proxy parameters for {@link IDevicePolicyManager#setGlobalProxy}.
6704      * @throws IllegalArgumentException Invalid proxySpec
6705      * @hide
6706      */
6707     @VisibleForTesting
getProxyParameters(Proxy proxySpec, List<String> exclusionList)6708     public Pair<String, String> getProxyParameters(Proxy proxySpec, List<String> exclusionList) {
6709         InetSocketAddress sa = (InetSocketAddress) proxySpec.address();
6710         String hostName = sa.getHostName();
6711         int port = sa.getPort();
6712         final List<String> trimmedExclList;
6713         if (exclusionList == null) {
6714             trimmedExclList = Collections.emptyList();
6715         } else {
6716             trimmedExclList = new ArrayList<>(exclusionList.size());
6717             for (String exclDomain : exclusionList) {
6718                 trimmedExclList.add(exclDomain.trim());
6719             }
6720         }
6721         final ProxyInfo info = ProxyInfo.buildDirectProxy(hostName, port, trimmedExclList);
6722         // The hostSpec is built assuming that there is a specified port and hostname,
6723         // but ProxyInfo.isValid() accepts 0 / empty as unspecified: also reject them.
6724         if (port == 0 || TextUtils.isEmpty(hostName) || !info.isValid()) {
6725             throw new IllegalArgumentException();
6726         }
6727 
6728         return new Pair<>(hostName + ":" + port, TextUtils.join(",", trimmedExclList));
6729     }
6730 
6731     /**
6732      * Set a network-independent global HTTP proxy. This is not normally what you want for typical
6733      * HTTP proxies - they are generally network dependent. However if you're doing something
6734      * unusual like general internal filtering this may be useful. On a private network where the
6735      * proxy is not accessible, you may break HTTP using this.
6736      * <p>
6737      * This method requires the caller to be the device owner.
6738      * <p>
6739      * This proxy is only a recommendation and it is possible that some apps will ignore it.
6740      * <p>
6741      * Note: The device owner won't be able to set a global HTTP proxy if there are unaffiliated
6742      * secondary users or profiles on the device. It's recommended that affiliation ids are set for
6743      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
6744      *
6745      * @see ProxyInfo
6746      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6747      * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A
6748      *            {@code null} value will clear the global HTTP proxy.
6749      * @throws SecurityException if {@code admin} is not the device owner.
6750      */
setRecommendedGlobalProxy(@onNull ComponentName admin, @Nullable ProxyInfo proxyInfo)6751     public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
6752             proxyInfo) {
6753         throwIfParentInstance("setRecommendedGlobalProxy");
6754         if (mService != null) {
6755             try {
6756                 mService.setRecommendedGlobalProxy(admin, proxyInfo);
6757             } catch (RemoteException e) {
6758                 throw e.rethrowFromSystemServer();
6759             }
6760         }
6761     }
6762 
6763     /**
6764      * Returns the component name setting the global proxy.
6765      * @return ComponentName object of the device admin that set the global proxy, or {@code null}
6766      *         if no admin has set the proxy.
6767      * @hide
6768      */
getGlobalProxyAdmin()6769     public @Nullable ComponentName getGlobalProxyAdmin() {
6770         if (mService != null) {
6771             try {
6772                 return mService.getGlobalProxyAdmin(myUserId());
6773             } catch (RemoteException e) {
6774                 throw e.rethrowFromSystemServer();
6775             }
6776         }
6777         return null;
6778     }
6779 
6780     /**
6781      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
6782      * indicating that encryption is not supported.
6783      */
6784     public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
6785 
6786     /**
6787      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
6788      * indicating that encryption is supported, but is not currently active.
6789      * <p>
6790      * {@link #getStorageEncryptionStatus} can only return this value on devices that use Full Disk
6791      * Encryption.  Support for Full Disk Encryption was entirely removed in API level 33, having
6792      * been replaced by File Based Encryption.  Devices that use File Based Encryption always
6793      * automatically activate their encryption on first boot.
6794      * <p>
6795      * {@link #setStorageEncryption} can still return this value for an unrelated reason, but {@link
6796      * #setStorageEncryption} is deprecated since it doesn't do anything useful.
6797      */
6798     public static final int ENCRYPTION_STATUS_INACTIVE = 1;
6799 
6800     /**
6801      * Result code for {@link #getStorageEncryptionStatus}: indicating that encryption is not
6802      * currently active, but is currently being activated.
6803      * <p>
6804      * @deprecated This result code has never actually been used, so there is no reason for apps to
6805      * check for it.
6806      */
6807     @Deprecated
6808     public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
6809 
6810     /**
6811      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
6812      * indicating that encryption is active.
6813      * <p>
6814      * {@link #getStorageEncryptionStatus} can only return this value for apps targeting API level
6815      * 23 or lower, or on devices that use Full Disk Encryption.  Support for Full Disk Encryption
6816      * was entirely removed in API level 33, having been replaced by File Based Encryption.  The
6817      * result code {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER} is used on devices that use File Based
6818      * Encryption, except when the app targets API level 23 or lower.
6819      * <p>
6820      * {@link #setStorageEncryption} can still return this value for an unrelated reason, but {@link
6821      * #setStorageEncryption} is deprecated since it doesn't do anything useful.
6822      */
6823     public static final int ENCRYPTION_STATUS_ACTIVE = 3;
6824 
6825     /**
6826      * Result code for {@link #getStorageEncryptionStatus}: indicating that encryption is active,
6827      * but the encryption key is not cryptographically protected by the user's credentials.
6828      * <p>
6829      * This value can only be returned on devices that use Full Disk Encryption.  Support for Full
6830      * Disk Encryption was entirely removed in API level 33, having been replaced by File Based
6831      * Encryption.  With File Based Encryption, each user's credential-encrypted storage is always
6832      * cryptographically protected by the user's credentials.
6833      */
6834     public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
6835 
6836     /**
6837      * Result code for {@link #getStorageEncryptionStatus}:
6838      * indicating that encryption is active and the encryption key is tied to the user or profile.
6839      * <p>
6840      * This value is only returned to apps targeting API level 24 and above. For apps targeting
6841      * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the
6842      * encryption key is specific to the user or profile.
6843      */
6844     public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5;
6845 
6846     /**
6847      * Activity action: begin the process of encrypting data on the device.  This activity should
6848      * be launched after using {@link #setStorageEncryption} to request encryption be activated.
6849      * After resuming from this activity, use {@link #getStorageEncryption}
6850      * to check encryption status.  However, on some devices this activity may never return, as
6851      * it may trigger a reboot and in some cases a complete data wipe of the device.
6852      */
6853     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
6854     public static final String ACTION_START_ENCRYPTION
6855             = "android.app.action.START_ENCRYPTION";
6856 
6857     /**
6858      * Activity action: launch the DPC to check policy compliance. This intent is launched when
6859      * the user taps on the notification about personal apps suspension. When handling this intent
6860      * the DPC must check if personal apps should still be suspended and either unsuspend them or
6861      * instruct the user on how to resolve the noncompliance causing the suspension.
6862      *
6863      * @see #setPersonalAppsSuspended
6864      */
6865     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
6866     public static final String ACTION_CHECK_POLICY_COMPLIANCE =
6867             "android.app.action.CHECK_POLICY_COMPLIANCE";
6868 
6869     /**
6870      * Broadcast action: notify managed provisioning that PO/DO provisioning has completed.
6871      *
6872      * @hide
6873      */
6874     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
6875     public static final String ACTION_PROVISIONING_COMPLETED =
6876             "android.app.action.PROVISIONING_COMPLETED";
6877 
6878     /**
6879      * Extra for {@link #ACTION_PROVISIONING_COMPLETED} to indicate the provisioning action that has
6880      * been completed, this can either be {@link #ACTION_PROVISION_MANAGED_PROFILE},
6881      * {@link #ACTION_PROVISION_MANAGED_DEVICE}, or {@link #ACTION_PROVISION_MANAGED_USER}.
6882      *
6883      * @hide
6884      */
6885     public static final String EXTRA_PROVISIONING_ACTION =
6886             "android.app.extra.PROVISIONING_ACTION";
6887 
6888     /**
6889      * Broadcast action: notify system that a new (Android) user was added when the device is
6890      * managed by a device owner, so receivers can show the proper disclaimer to the (human) user.
6891      *
6892      * @hide
6893      */
6894     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
6895     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
6896     public static final String ACTION_SHOW_NEW_USER_DISCLAIMER =
6897             "android.app.action.SHOW_NEW_USER_DISCLAIMER";
6898 
6899     /**
6900      * Widgets are enabled in keyguard
6901      */
6902     public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
6903 
6904     /**
6905      * Disable all keyguard widgets. Has no effect starting from
6906      * {@link android.os.Build.VERSION_CODES#LOLLIPOP} since keyguard widget is only supported
6907      * on Android versions lower than 5.0.
6908      */
6909     public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
6910 
6911     /**
6912      * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
6913      */
6914     public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
6915 
6916     /**
6917      * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
6918      */
6919     public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
6920 
6921     /**
6922      * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
6923      */
6924     public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
6925 
6926     /**
6927      * Disable trust agents on secure keyguard screens (e.g. PIN/Pattern/Password).
6928      * By setting this flag alone, all trust agents are disabled. If the admin then wants to
6929      * allowlist specific features of some trust agent, {@link #setTrustAgentConfiguration} can be
6930      * used in conjuction to set trust-agent-specific configurations.
6931      */
6932     public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
6933 
6934     /**
6935      * Disable fingerprint authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
6936      */
6937     public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
6938 
6939     /**
6940      * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
6941      * @deprecated This flag was added in version {@link android.os.Build.VERSION_CODES#N}, but it
6942      * never had any effect.
6943      */
6944     @Deprecated
6945     public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
6946 
6947     /**
6948      * Disable face authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
6949      */
6950     public static final int KEYGUARD_DISABLE_FACE = 1 << 7;
6951 
6952     /**
6953      * Disable iris authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
6954      */
6955     public static final int KEYGUARD_DISABLE_IRIS = 1 << 8;
6956 
6957     /**
6958      * Disable all keyguard shortcuts.
6959      */
6960     public static final int KEYGUARD_DISABLE_SHORTCUTS_ALL = 1 << 9;
6961 
6962     /**
6963      * NOTE: Please remember to update the DevicePolicyManagerTest's testKeyguardDisabledFeatures
6964      * CTS test when adding to the list above.
6965      */
6966 
6967     /**
6968      * Disable all biometric authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
6969      */
6970     public static final int KEYGUARD_DISABLE_BIOMETRICS =
6971             DevicePolicyManager.KEYGUARD_DISABLE_FACE
6972             | DevicePolicyManager.KEYGUARD_DISABLE_IRIS
6973             | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
6974 
6975     /**
6976      * Disable all current and future keyguard customizations.
6977      */
6978     public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
6979 
6980     /**
6981      * Keyguard features that when set on a non-organization-owned managed profile that doesn't
6982      * have its own challenge will affect the profile's parent user. These can also be set on the
6983      * managed profile's parent {@link DevicePolicyManager} instance to explicitly control the
6984      * parent user.
6985      *
6986      * <p>
6987      * Organization-owned managed profile supports disabling additional keyguard features on the
6988      * parent user as defined in {@link #ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY}.
6989      *
6990      * @hide
6991      */
6992     public static final int NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
6993             DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
6994             | DevicePolicyManager.KEYGUARD_DISABLE_BIOMETRICS;
6995 
6996     /**
6997      * Keyguard features that when set by the profile owner of an organization-owned managed
6998      * profile will affect the profile's parent user if set on the managed profile's parent
6999      * {@link DevicePolicyManager} instance.
7000      *
7001      * @hide
7002      */
7003     public static final int ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY =
7004             DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA
7005                     | DevicePolicyManager.KEYGUARD_DISABLE_SECURE_NOTIFICATIONS
7006                     | DevicePolicyManager.KEYGUARD_DISABLE_SHORTCUTS_ALL;
7007 
7008     /**
7009      * Keyguard features that when set on a normal or organization-owned managed profile, have
7010      * the potential to affect the profile's parent user.
7011      *
7012      * @hide
7013      */
7014     public static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
7015             DevicePolicyManager.NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER
7016                     | DevicePolicyManager.ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY;
7017 
7018     /**
7019      * @deprecated This method does not actually modify the storage encryption of the device.
7020      * It has never affected the encryption status of a device.
7021      *
7022      * Called by an application that is administering the device to request that the storage system
7023      * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
7024      * <p>
7025      * When multiple device administrators attempt to control device encryption, the most secure,
7026      * supported setting will always be used. If any device administrator requests device
7027      * encryption, it will be enabled; Conversely, if a device administrator attempts to disable
7028      * device encryption while another device administrator has enabled it, the call to disable will
7029      * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
7030      * <p>
7031      * This policy controls encryption of the secure (application data) storage area. Data written
7032      * to other storage areas may or may not be encrypted, and this policy does not require or
7033      * control the encryption of any other storage areas. There is one exception: If
7034      * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the
7035      * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be
7036      * written to disk within the encrypted storage area.
7037      * <p>
7038      * Important Note: On some devices, it is possible to encrypt storage without requiring the user
7039      * to create a device PIN or Password. In this case, the storage is encrypted, but the
7040      * encryption key may not be fully secured. For maximum security, the administrator should also
7041      * require (and check for) a pattern, PIN, or password.
7042      *
7043      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7044      * @param encrypt true to request encryption, false to release any previous request
7045      * @return the new total request status (for all active admins), or {@link
7046      *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user.
7047      *         Will be one of {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link
7048      *         #ENCRYPTION_STATUS_INACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value
7049      *         of the requests; use {@link #getStorageEncryptionStatus()} to query the actual device
7050      *         state.
7051      *
7052      * @throws SecurityException if {@code admin} is not an active administrator or does not use
7053      *             {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE}
7054      */
7055     @Deprecated
setStorageEncryption(@onNull ComponentName admin, boolean encrypt)7056     public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
7057         throwIfParentInstance("setStorageEncryption");
7058         if (mService != null) {
7059             try {
7060                 return mService.setStorageEncryption(admin, encrypt);
7061             } catch (RemoteException e) {
7062                 throw e.rethrowFromSystemServer();
7063             }
7064         }
7065         return ENCRYPTION_STATUS_UNSUPPORTED;
7066     }
7067 
7068     /**
7069      * @deprecated This method only returns the value set by {@link #setStorageEncryption}.
7070      * It does not actually reflect the storage encryption status.
7071      * Use {@link #getStorageEncryptionStatus} for that.
7072      *
7073      * Called by an application that is administering the device to
7074      * determine the requested setting for secure storage.
7075      *
7076      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
7077      * this will return the requested encryption setting as an aggregate of all active
7078      * administrators.
7079      * @return true if the admin(s) are requesting encryption, false if not.
7080      */
7081     @Deprecated
getStorageEncryption(@ullable ComponentName admin)7082     public boolean getStorageEncryption(@Nullable ComponentName admin) {
7083         throwIfParentInstance("getStorageEncryption");
7084         if (mService != null) {
7085             try {
7086                 return mService.getStorageEncryption(admin, myUserId());
7087             } catch (RemoteException e) {
7088                 throw e.rethrowFromSystemServer();
7089             }
7090         }
7091         return false;
7092     }
7093 
7094     /**
7095      * Called by an application that is administering the device to
7096      * determine the current encryption status of the device.
7097      * <p>
7098      * Depending on the returned status code, the caller may proceed in different
7099      * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
7100      * storage system does not support encryption.  If the
7101      * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
7102      * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
7103      * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
7104      * storage system has enabled encryption but no password is set so further action
7105      * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING},
7106      * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER},
7107      * no further action is required.
7108      *
7109      * @return current status of encryption. The value will be one of
7110      * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
7111      * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
7112      * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
7113      *
7114      * @throws SecurityException if called on a parent instance.
7115      */
getStorageEncryptionStatus()7116     public int getStorageEncryptionStatus() {
7117         throwIfParentInstance("getStorageEncryptionStatus");
7118         return getStorageEncryptionStatus(myUserId());
7119     }
7120 
7121     /** @hide per-user version */
7122     @UnsupportedAppUsage
getStorageEncryptionStatus(int userHandle)7123     public int getStorageEncryptionStatus(int userHandle) {
7124         if (mService != null) {
7125             try {
7126                 return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle);
7127             } catch (RemoteException e) {
7128                 throw e.rethrowFromSystemServer();
7129             }
7130         }
7131         return ENCRYPTION_STATUS_UNSUPPORTED;
7132     }
7133 
7134     /**
7135      * Mark a CA certificate as approved by the device user. This means that they have been notified
7136      * of the installation, were made aware of the risks, viewed the certificate and still wanted to
7137      * keep the certificate on the device.
7138      *
7139      * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to
7140      * this certificate.
7141      *
7142      * @hide
7143      */
approveCaCert(String alias, int userHandle, boolean approval)7144     public boolean approveCaCert(String alias, int userHandle, boolean approval) {
7145         if (mService != null) {
7146             try {
7147                 return mService.approveCaCert(alias, userHandle, approval);
7148             } catch (RemoteException e) {
7149                 throw e.rethrowFromSystemServer();
7150             }
7151         }
7152         return false;
7153     }
7154 
7155     /**
7156      * Check whether a CA certificate has been approved by the device user.
7157      *
7158      * @hide
7159      */
isCaCertApproved(String alias, int userHandle)7160     public boolean isCaCertApproved(String alias, int userHandle) {
7161         if (mService != null) {
7162             try {
7163                 return mService.isCaCertApproved(alias, userHandle);
7164             } catch (RemoteException e) {
7165                 throw e.rethrowFromSystemServer();
7166             }
7167         }
7168         return false;
7169     }
7170 
7171     /**
7172      * Installs the given certificate as a user CA.
7173      * <p>
7174      * Inserted user CAs aren't automatically trusted by apps in Android 7.0 (API level 24) and
7175      * higher. App developers can change the default behavior for an app by adding a
7176      * <a href="{@docRoot}training/articles/security-config.html">Security Configuration
7177      * File</a> to the app manifest file.
7178      *
7179      * The caller must be a profile or device owner on that user, or a delegate package given the
7180      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
7181      * security exception will be thrown.
7182      *
7183      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7184      *              {@code null} if calling from a delegated certificate installer.
7185      * @param certBuffer encoded form of the certificate to install.
7186      *
7187      * @return false if the certBuffer cannot be parsed or installation is
7188      *         interrupted, true otherwise.
7189      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7190      *         owner.
7191      * @see #setDelegatedScopes
7192      * @see #DELEGATION_CERT_INSTALL
7193      */
installCaCert(@ullable ComponentName admin, byte[] certBuffer)7194     public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
7195         throwIfParentInstance("installCaCert");
7196         if (mService != null) {
7197             try {
7198                 return mService.installCaCert(admin, mContext.getPackageName(), certBuffer);
7199             } catch (RemoteException e) {
7200                 throw e.rethrowFromSystemServer();
7201             }
7202         }
7203         return false;
7204     }
7205 
7206     /**
7207      * Uninstalls the given certificate from trusted user CAs, if present.
7208      *
7209      * The caller must be a profile or device owner on that user, or a delegate package given the
7210      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
7211      * security exception will be thrown.
7212      *
7213      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7214      *              {@code null} if calling from a delegated certificate installer.
7215      * @param certBuffer encoded form of the certificate to remove.
7216      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7217      *         owner.
7218      * @see #setDelegatedScopes
7219      * @see #DELEGATION_CERT_INSTALL
7220      */
uninstallCaCert(@ullable ComponentName admin, byte[] certBuffer)7221     public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
7222         throwIfParentInstance("uninstallCaCert");
7223         if (mService != null) {
7224             try {
7225                 final String alias = getCaCertAlias(certBuffer);
7226                 mService.uninstallCaCerts(admin, mContext.getPackageName(), new String[] {alias});
7227             } catch (CertificateException e) {
7228                 Log.w(TAG, "Unable to parse certificate", e);
7229             } catch (RemoteException e) {
7230                 throw e.rethrowFromSystemServer();
7231             }
7232         }
7233     }
7234 
7235     /**
7236      * Returns all CA certificates that are currently trusted, excluding system CA certificates.
7237      * If a user has installed any certificates by other means than device policy these will be
7238      * included too.
7239      *
7240      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7241      *              {@code null} if calling from a delegated certificate installer.
7242      * @return a List of byte[] arrays, each encoding one user CA certificate.
7243      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7244      *         owner.
7245      */
getInstalledCaCerts(@ullable ComponentName admin)7246     public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
7247         final List<byte[]> certs = new ArrayList<byte[]>();
7248         throwIfParentInstance("getInstalledCaCerts");
7249         if (mService != null) {
7250             try {
7251                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
7252                 final TrustedCertificateStore certStore = new TrustedCertificateStore();
7253                 for (String alias : certStore.userAliases()) {
7254                     try {
7255                         certs.add(certStore.getCertificate(alias).getEncoded());
7256                     } catch (CertificateException ce) {
7257                         Log.w(TAG, "Could not encode certificate: " + alias, ce);
7258                     }
7259                 }
7260             } catch (RemoteException re) {
7261                 throw re.rethrowFromSystemServer();
7262             }
7263         }
7264         return certs;
7265     }
7266 
7267     /**
7268      * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
7269      * means other than device policy will also be removed, except for system CA certificates.
7270      *
7271      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7272      *              {@code null} if calling from a delegated certificate installer.
7273      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7274      *         owner.
7275      */
uninstallAllUserCaCerts(@ullable ComponentName admin)7276     public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
7277         throwIfParentInstance("uninstallAllUserCaCerts");
7278         if (mService != null) {
7279             try {
7280                 mService.uninstallCaCerts(admin, mContext.getPackageName(),
7281                         new TrustedCertificateStore().userAliases() .toArray(new String[0]));
7282             } catch (RemoteException re) {
7283                 throw re.rethrowFromSystemServer();
7284             }
7285         }
7286     }
7287 
7288     /**
7289      * Returns whether this certificate is installed as a trusted CA.
7290      *
7291      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7292      *              {@code null} if calling from a delegated certificate installer.
7293      * @param certBuffer encoded form of the certificate to look up.
7294      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7295      *         owner.
7296      */
hasCaCertInstalled(@ullable ComponentName admin, byte[] certBuffer)7297     public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
7298         throwIfParentInstance("hasCaCertInstalled");
7299         if (mService != null) {
7300             try {
7301                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
7302                 return getCaCertAlias(certBuffer) != null;
7303             } catch (RemoteException re) {
7304                 throw re.rethrowFromSystemServer();
7305             } catch (CertificateException ce) {
7306                 Log.w(TAG, "Could not parse certificate", ce);
7307             }
7308         }
7309         return false;
7310     }
7311 
7312     /**
7313      * This API can be called by the following to install a certificate and corresponding
7314      * private key:
7315      * <ul>
7316      *    <li>Device owner</li>
7317      *    <li>Profile owner</li>
7318      *    <li>Delegated certificate installer</li>
7319      *    <li>Credential management app</li>
7320      *    <li>An app that holds the
7321      *    {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission</li>
7322      * </ul>
7323      * All apps within the profile will be able to access the certificate and use the private key,
7324      * given direct user approval.
7325      *
7326      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7327      * can call this API. However, this API sets the key pair as user selectable by default,
7328      * which is not permitted when called by the credential management app. Instead,
7329      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)} should be
7330      * called with {@link #INSTALLKEY_SET_USER_SELECTABLE} not set as a flag.
7331      *
7332      * <p>Access to the installed credentials will not be granted to the caller of this API without
7333      * direct user approval. This is for security - should a certificate installer become
7334      * compromised, certificates it had already installed will be protected.
7335      *
7336      * <p>If the installer must have access to the credentials, call
7337      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead.
7338      *
7339      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
7340      * have been given to access the key and certificates associated with this alias will be
7341      * revoked.
7342      *
7343      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7344      *            {@code null} if the caller is not a device admin.
7345      * @param privKey The private key to install.
7346      * @param cert The certificate to install.
7347      * @param alias The private key alias under which to install the certificate. If a certificate
7348      * with that alias already exists, it will be overwritten.
7349      * @return {@code true} if the keys were installed, {@code false} otherwise.
7350      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7351      *         owner, or {@code admin} is null and the calling application does not have the
7352      *         {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission.
7353      * @see #setDelegatedScopes
7354      * @see #DELEGATION_CERT_INSTALL
7355      */
7356     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true)
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate cert, @NonNull String alias)7357     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
7358             @NonNull Certificate cert, @NonNull String alias) {
7359         return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false);
7360     }
7361 
7362     /**
7363      * This API can be called by the following to install a certificate chain and corresponding
7364      * private key for the leaf certificate:
7365      * <ul>
7366      *    <li>Device owner</li>
7367      *    <li>Profile owner</li>
7368      *    <li>Delegated certificate installer</li>
7369      *    <li>Credential management app</li>
7370      *    <li>An app that holds the
7371      *    {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission</li>
7372      * </ul>
7373      * All apps within the profile will be able to access the certificate chain and use the private
7374      * key, given direct user approval.
7375      *
7376      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7377      * can call this API. However, this API sets the key pair as user selectable by default,
7378      * which is not permitted when called by the credential management app. Instead,
7379      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)} should be
7380      * called with {@link #INSTALLKEY_SET_USER_SELECTABLE} not set as a flag.
7381      * Note, there can only be a credential management app on an unmanaged device.
7382      *
7383      * <p>The caller of this API may grant itself access to the certificate and private key
7384      * immediately, without user approval. It is a best practice not to request this unless strictly
7385      * necessary since it opens up additional security vulnerabilities.
7386      *
7387      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
7388      * have been given to access the key and certificates associated with this alias will be
7389      * revoked.
7390      *
7391      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7392      *        {@code null} if the caller is not a device admin.
7393      * @param privKey The private key to install.
7394      * @param certs The certificate chain to install. The chain should start with the leaf
7395      *        certificate and include the chain of trust in order. This will be returned by
7396      *        {@link android.security.KeyChain#getCertificateChain}.
7397      * @param alias The private key alias under which to install the certificate. If a certificate
7398      *        with that alias already exists, it will be overwritten.
7399      * @param requestAccess {@code true} to request that the calling app be granted access to the
7400      *        credentials immediately. Otherwise, access to the credentials will be gated by user
7401      *        approval.
7402      * @return {@code true} if the keys were installed, {@code false} otherwise.
7403      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7404      *         owner, or {@code admin} is null and the calling application does not have the
7405      *         {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission.
7406      * @see android.security.KeyChain#getCertificateChain
7407      * @see #setDelegatedScopes
7408      * @see #DELEGATION_CERT_INSTALL
7409      */
7410     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true)
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess)7411     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
7412             @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) {
7413         int flags = INSTALLKEY_SET_USER_SELECTABLE;
7414         if (requestAccess) {
7415             flags |= INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
7416         }
7417         return installKeyPair(admin, privKey, certs, alias, flags);
7418     }
7419 
7420     /**
7421      * This API can be called by the following to install a certificate chain and corresponding
7422      * private key for the leaf certificate:
7423      * <ul>
7424      *    <li>Device owner</li>
7425      *    <li>Profile owner</li>
7426      *    <li>Delegated certificate installer</li>
7427      *    <li>Credential management app</li>
7428      *    <li>An app that holds the
7429      *    {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission</li>
7430      * </ul>
7431      * All apps within the profile will be able to access the certificate chain and use the
7432      * private key, given direct user approval (if the user is allowed to select the private key).
7433      *
7434      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7435      * can call this API. If called by the credential management app:
7436      * <ul>
7437      *    <li>The componentName must be {@code null}r</li>
7438      *    <li>The alias must exist in the credential management app's
7439      *    {@link android.security.AppUriAuthenticationPolicy}</li>
7440      *    <li>The key pair must not be user selectable</li>
7441      * </ul>
7442      * Note, there can only be a credential management app on an unmanaged device.
7443      *
7444      * <p>The caller of this API may grant itself access to the certificate and private key
7445      * immediately, without user approval. It is a best practice not to request this unless strictly
7446      * necessary since it opens up additional security vulnerabilities.
7447      *
7448      * <p>Include {@link #INSTALLKEY_SET_USER_SELECTABLE} in the {@code flags} argument to allow
7449      * the user to select the key from a dialog.
7450      *
7451      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
7452      * have been given to access the key and certificates associated with this alias will be
7453      * revoked.
7454      *
7455      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7456      *        {@code null} if the caller is not a device admin.
7457      * @param privKey The private key to install.
7458      * @param certs The certificate chain to install. The chain should start with the leaf
7459      *        certificate and include the chain of trust in order. This will be returned by
7460      *        {@link android.security.KeyChain#getCertificateChain}.
7461      * @param alias The private key alias under which to install the certificate. If a certificate
7462      *        with that alias already exists, it will be overwritten.
7463      * @param flags Flags to request that the calling app be granted access to the credentials
7464      *        and set the key to be user-selectable. See {@link #INSTALLKEY_SET_USER_SELECTABLE} and
7465      *        {@link #INSTALLKEY_REQUEST_CREDENTIALS_ACCESS}.
7466      * @return {@code true} if the keys were installed, {@code false} otherwise.
7467      * @throws SecurityException if {@code admin} is not {@code null} and not a device or
7468      *        profile owner, or {@code admin} is null but the calling application is not a
7469      *        delegated certificate installer, credential management app and does not have the
7470      *        {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission.
7471      * @see android.security.KeyChain#getCertificateChain
7472      * @see #setDelegatedScopes
7473      * @see #DELEGATION_CERT_INSTALL
7474      */
7475     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true)
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, int flags)7476     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
7477             @NonNull Certificate[] certs, @NonNull String alias, int flags) {
7478         throwIfParentInstance("installKeyPair");
7479         boolean requestAccess = (flags & INSTALLKEY_REQUEST_CREDENTIALS_ACCESS)
7480                 == INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
7481         boolean isUserSelectable = (flags & INSTALLKEY_SET_USER_SELECTABLE)
7482                 == INSTALLKEY_SET_USER_SELECTABLE;
7483         try {
7484             final byte[] pemCert = Credentials.convertToPem(certs[0]);
7485             byte[] pemChain = null;
7486             if (certs.length > 1) {
7487                 pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length));
7488             }
7489             final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
7490                     .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
7491             return mService.installKeyPair(admin, mContext.getPackageName(), pkcs8Key, pemCert,
7492                     pemChain, alias, requestAccess, isUserSelectable);
7493         } catch (RemoteException e) {
7494             throw e.rethrowFromSystemServer();
7495         } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
7496             Log.w(TAG, "Failed to obtain private key material", e);
7497         } catch (CertificateException | IOException e) {
7498             Log.w(TAG, "Could not pem-encode certificate", e);
7499         }
7500         return false;
7501     }
7502 
7503     /**
7504      * This API can be called by the following to remove a certificate and private key pair
7505      * installed under a given alias:
7506      * <ul>
7507      *    <li>Device owner</li>
7508      *    <li>Profile owner</li>
7509      *    <li>Delegated certificate installer</li>
7510      *    <li>Credential management app</li>
7511      * </ul>
7512      *
7513      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7514      * can call this API. If called by the credential management app, the componentName must be
7515      * {@code null}. Note, there can only be a credential management app on an unmanaged device.
7516      *
7517      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7518      *        {@code null} if the caller is not a device admin.
7519      * @param alias The private key alias under which the certificate is installed.
7520      * @return {@code true} if the private key alias no longer exists, {@code false} otherwise.
7521      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7522      *         owner, or {@code admin} is null but the calling application is not a delegated
7523      *         certificate installer or credential management app.
7524      * @see #setDelegatedScopes
7525      * @see #DELEGATION_CERT_INSTALL
7526      */
7527     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true)
removeKeyPair(@ullable ComponentName admin, @NonNull String alias)7528     public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
7529         throwIfParentInstance("removeKeyPair");
7530         try {
7531             return mService.removeKeyPair(admin, mContext.getPackageName(), alias);
7532         } catch (RemoteException e) {
7533             throw e.rethrowFromSystemServer();
7534         }
7535     }
7536 
7537     // STOPSHIP(b/174298501): clarify the expected return value following generateKeyPair call.
7538     /**
7539      * This API can be called by the following to query whether a certificate and private key are
7540      * installed under a given alias:
7541      * <ul>
7542      *    <li>Device owner</li>
7543      *    <li>Profile owner</li>
7544      *    <li>Delegated certificate installer</li>
7545      *    <li>Credential management app</li>
7546      *    <li>An app that holds the
7547      *    {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission</li>
7548      * </ul>
7549      *
7550      * If called by the credential management app, the alias must exist in the credential
7551      * management app's {@link android.security.AppUriAuthenticationPolicy}.
7552      *
7553      * @param alias The alias under which the key pair is installed.
7554      * @return {@code true} if a key pair with this alias exists, {@code false} otherwise.
7555      * @throws SecurityException if the caller is not a device or profile owner, a delegated
7556      *         certificate installer, the credential management app and does not have the
7557      *         {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission.
7558      * @see #setDelegatedScopes
7559      * @see #DELEGATION_CERT_INSTALL
7560      */
7561     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true)
hasKeyPair(@onNull String alias)7562     public boolean hasKeyPair(@NonNull String alias) {
7563         throwIfParentInstance("hasKeyPair");
7564         try {
7565             return mService.hasKeyPair(mContext.getPackageName(), alias);
7566         } catch (RemoteException e) {
7567             throw e.rethrowFromSystemServer();
7568         }
7569     }
7570 
7571     /**
7572      * This API can be called by the following to generate a new private/public key pair:
7573      * <ul>
7574      *    <li>Device owner</li>
7575      *    <li>Profile owner</li>
7576      *    <li>Delegated certificate installer</li>
7577      *    <li>Credential management app</li>
7578      *    <li>An app that holds the
7579      *    {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission</li>
7580      * </ul>
7581      * If the device supports key generation via secure hardware, this method is useful for
7582      * creating a key in KeyChain that never left the secure hardware. Access to the key is
7583      * controlled the same way as in {@link #installKeyPair}.
7584      *
7585      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7586      * can call this API. If called by the credential management app, the componentName must be
7587      * {@code null}. Note, there can only be a credential management app on an unmanaged device.
7588      *
7589      * <p>Because this method might take several seconds to complete, it should only be called from
7590      * a worker thread. This method returns {@code null} when called from the main thread.
7591      *
7592      * <p>This method is not thread-safe, calling it from multiple threads at the same time will
7593      * result in undefined behavior. If the calling thread is interrupted while the invocation is
7594      * in-flight, it will eventually terminate and return {@code null}.
7595      *
7596      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
7597      * have been given to access the key and certificates associated with this alias will be
7598      * revoked.
7599      *
7600      * <p>Attestation: to enable attestation, set an attestation challenge in {@code keySpec} via
7601      * {@link KeyGenParameterSpec.Builder#setAttestationChallenge}. By specifying flags to the
7602      * {@code idAttestationFlags} parameter, it is possible to request the device's unique
7603      * identity to be included in the attestation record.
7604      *
7605      * <p>Specific identifiers can be included in the attestation record, and an individual
7606      * attestation certificate can be used to sign the attestation record. To find out if the device
7607      * supports these features, refer to {@link #isDeviceIdAttestationSupported()} and
7608      * {@link #isUniqueDeviceAttestationSupported()}.
7609      *
7610      * <p>Device owner, profile owner, their delegated certificate installer and the credential
7611      * management app can use {@link #ID_TYPE_BASE_INFO} to request inclusion of the general device
7612      * information including manufacturer, model, brand, device and product in the attestation
7613      * record.
7614      * Only device owner, profile owner on an organization-owned device or affiliated user, and
7615      * their delegated certificate installers can use {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI}
7616      * and {@link #ID_TYPE_MEID} to request unique device identifiers to be attested (the serial
7617      * number, IMEI and MEID correspondingly), if supported by the device
7618      * (see {@link #isDeviceIdAttestationSupported()}).
7619      * Additionally, device owner, profile owner on an organization-owned device and their delegated
7620      * certificate installers can also request the attestation record to be signed using an
7621      * individual attestation certificate by specifying the {@link #ID_TYPE_INDIVIDUAL_ATTESTATION}
7622      * flag (if supported by the device, see {@link #isUniqueDeviceAttestationSupported()}).
7623      * <p>
7624      * If any of {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID}
7625      * is set, it is implicitly assumed that {@link #ID_TYPE_BASE_INFO} is also set.
7626      * <p>
7627      * Attestation using {@link #ID_TYPE_INDIVIDUAL_ATTESTATION} can only be requested if
7628      * key generation is done in StrongBox.
7629      *
7630      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7631      *            {@code null} if the caller is not a device admin.
7632      * @param algorithm The key generation algorithm, see {@link java.security.KeyPairGenerator}.
7633      * @param keySpec Specification of the key to generate, see
7634      * {@link java.security.KeyPairGenerator}.
7635      * @param idAttestationFlags A bitmask of the identifiers that should be included in the
7636      *        attestation record ({@code ID_TYPE_BASE_INFO}, {@code ID_TYPE_SERIAL},
7637      *        {@code ID_TYPE_IMEI} and {@code ID_TYPE_MEID}), and
7638      *        {@code ID_TYPE_INDIVIDUAL_ATTESTATION} if the attestation record should be signed
7639      *        using an individual attestation certificate.
7640      *        <p>
7641      *        {@code 0} should be passed in if no device identification is required in the
7642      *        attestation record and the batch attestation certificate should be used.
7643      *        <p>
7644      *        If any flag is specified, then an attestation challenge must be included in the
7645      *        {@code keySpec}.
7646      * @return A non-null {@code AttestedKeyPair} if the key generation succeeded, null otherwise.
7647      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7648      *         owner, or {@code admin} is null but the calling application is not a delegated
7649      *         certificate installer or credential management app. If Device ID attestation is
7650      *         requested (using {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} or
7651      *         {@link #ID_TYPE_MEID}), the caller must be the Device Owner or the Certificate
7652      *         Installer delegate.
7653      * @throws IllegalArgumentException in the following cases:
7654      *         <p>
7655      *         <ul>
7656      *         <li>The alias in {@code keySpec} is empty.</li>
7657      *         <li>The algorithm specification in {@code keySpec} is not
7658      *         {@code RSAKeyGenParameterSpec} or {@code ECGenParameterSpec}.</li>
7659      *         <li>Device ID attestation was requested but the {@code keySpec} does not contain an
7660      *         attestation challenge.</li>
7661      *         </ul>
7662      * @throws UnsupportedOperationException if Device ID attestation or individual attestation
7663      *         was requested but the underlying hardware does not support it.
7664      * @throws StrongBoxUnavailableException if the use of StrongBox for key generation was
7665      *         specified in {@code keySpec} but the device does not have one.
7666      * @see KeyGenParameterSpec.Builder#setAttestationChallenge(byte[])
7667      */
7668     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true)
generateKeyPair(@ullable ComponentName admin, @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec, @AttestationIdType int idAttestationFlags)7669     public AttestedKeyPair generateKeyPair(@Nullable ComponentName admin,
7670             @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec,
7671             @AttestationIdType int idAttestationFlags) {
7672         throwIfParentInstance("generateKeyPair");
7673         try {
7674             final ParcelableKeyGenParameterSpec parcelableSpec =
7675                     new ParcelableKeyGenParameterSpec(keySpec);
7676             KeymasterCertificateChain attestationChain = new KeymasterCertificateChain();
7677 
7678             // Translate ID attestation flags to values used by AttestationUtils
7679             final boolean success = mService.generateKeyPair(
7680                     admin, mContext.getPackageName(), algorithm, parcelableSpec,
7681                     idAttestationFlags, attestationChain);
7682             if (!success) {
7683                 Log.e(TAG, "Error generating key via DevicePolicyManagerService.");
7684                 return null;
7685             }
7686 
7687             final String alias = keySpec.getKeystoreAlias();
7688             final KeyPair keyPair = KeyChain.getKeyPair(mContext, alias);
7689             Certificate[] outputChain = null;
7690             try {
7691                 if (AttestationUtils.isChainValid(attestationChain)) {
7692                     outputChain = AttestationUtils.parseCertificateChain(attestationChain);
7693                 }
7694             } catch (KeyAttestationException e) {
7695                 Log.e(TAG, "Error parsing attestation chain for alias " + alias, e);
7696                 mService.removeKeyPair(admin, mContext.getPackageName(), alias);
7697                 return null;
7698             }
7699             return new AttestedKeyPair(keyPair, outputChain);
7700         } catch (RemoteException e) {
7701             throw e.rethrowFromSystemServer();
7702         } catch (KeyChainException e) {
7703             Log.w(TAG, "Failed to generate key", e);
7704         } catch (InterruptedException e) {
7705             Log.w(TAG, "Interrupted while generating key", e);
7706             Thread.currentThread().interrupt();
7707         } catch (ServiceSpecificException e) {
7708             Log.w(TAG, String.format("Key Generation failure: %d", e.errorCode));
7709             switch (e.errorCode) {
7710                 case KEY_GEN_STRONGBOX_UNAVAILABLE:
7711                     throw new StrongBoxUnavailableException("No StrongBox for key generation.");
7712                 default:
7713                     throw new RuntimeException(
7714                             String.format("Unknown error while generating key: %d", e.errorCode));
7715             }
7716         }
7717         return null;
7718     }
7719 
7720     /**
7721      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7722      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to grant an application access
7723      * to an already-installed (or generated) KeyChain key.
7724      * This is useful (in combination with {@link #installKeyPair} or {@link #generateKeyPair}) to
7725      * let an application call {@link android.security.KeyChain#getPrivateKey} without having to
7726      * call {@link android.security.KeyChain#choosePrivateKeyAlias} first.
7727      *
7728      * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED}
7729      * broadcast when access to a key is granted.
7730      *
7731      * Starting from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} throws an
7732      * {@link IllegalArgumentException} if {@code alias} doesn't correspond to an existing key.
7733      *
7734      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7735      *        {@code null} if calling from a delegated certificate chooser.
7736      * @param alias The alias of the key to grant access to.
7737      * @param packageName The name of the (already installed) package to grant access to.
7738      * @return {@code true} if the grant was set successfully, {@code false} otherwise.
7739      *
7740      * @throws SecurityException if the caller is not a device owner, a profile owner or
7741      *         delegated certificate chooser.
7742      * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if
7743      *         {@code packageName} is not a name of an installed package.
7744      * @see #revokeKeyPairFromApp
7745      */
grantKeyPairToApp(@ullable ComponentName admin, @NonNull String alias, @NonNull String packageName)7746     public boolean grantKeyPairToApp(@Nullable ComponentName admin, @NonNull String alias,
7747             @NonNull String packageName) {
7748         throwIfParentInstance("grantKeyPairToApp");
7749         try {
7750             return mService.setKeyGrantForApp(
7751                     admin, mContext.getPackageName(), alias, packageName, true);
7752         } catch (RemoteException e) {
7753             e.rethrowFromSystemServer();
7754         }
7755         return false;
7756     }
7757 
7758     /**
7759      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7760      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to query which apps have access
7761      * to a given KeyChain key.
7762      *
7763      * Key are granted on a per-UID basis, so if several apps share the same UID, granting access to
7764      * one of them automatically grants it to others. This method returns a map containing one entry
7765      * per grantee UID. Entries have UIDs as keys and sets of corresponding package names as values.
7766      * In particular, grantee packages that don't share UID with other packages are represented by
7767      * entries having singleton sets as values.
7768      *
7769      * @param alias The alias of the key to grant access to.
7770      * @return apps that have access to a given key, arranged in a map from UID to sets of
7771      *       package names.
7772      *
7773      * @throws SecurityException if the caller is not a device owner, a profile owner or
7774      *         delegated certificate chooser.
7775      * @throws IllegalArgumentException if {@code alias} doesn't correspond to an existing key.
7776      *
7777      * @see #grantKeyPairToApp(ComponentName, String, String)
7778      */
getKeyPairGrants(@onNull String alias)7779     public @NonNull Map<Integer, Set<String>> getKeyPairGrants(@NonNull String alias) {
7780         throwIfParentInstance("getKeyPairGrants");
7781         try {
7782             // The result is wrapped into intermediate parcelable representation.
7783             return mService.getKeyPairGrants(mContext.getPackageName(), alias).getPackagesByUid();
7784         } catch (RemoteException e) {
7785             e.rethrowFromSystemServer();
7786         }
7787         return null;
7788     }
7789 
7790     /**
7791      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7792      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to revoke an application's
7793      * grant to a KeyChain key pair.
7794      * Calls by the application to {@link android.security.KeyChain#getPrivateKey}
7795      * will fail after the grant is revoked.
7796      *
7797      * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED}
7798      * broadcast when access to a key is revoked.
7799      *
7800      * Starting from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} throws an
7801      * {@link IllegalArgumentException} if {@code alias} doesn't correspond to an existing key.
7802      *
7803      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7804      *        {@code null} if calling from a delegated certificate chooser.
7805      * @param alias The alias of the key to revoke access from.
7806      * @param packageName The name of the (already installed) package to revoke access from.
7807      * @return {@code true} if the grant was revoked successfully, {@code false} otherwise.
7808      *
7809      * @throws SecurityException if the caller is not a device owner, a profile owner or
7810      *         delegated certificate chooser.
7811      * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if
7812      *         {@code packageName} is not a name of an installed package.
7813      * @see #grantKeyPairToApp
7814      */
revokeKeyPairFromApp(@ullable ComponentName admin, @NonNull String alias, @NonNull String packageName)7815     public boolean revokeKeyPairFromApp(@Nullable ComponentName admin, @NonNull String alias,
7816             @NonNull String packageName) {
7817         throwIfParentInstance("revokeKeyPairFromApp");
7818         try {
7819             return mService.setKeyGrantForApp(
7820                     admin, mContext.getPackageName(), alias, packageName, false);
7821         } catch (RemoteException e) {
7822             e.rethrowFromSystemServer();
7823         }
7824         return false;
7825     }
7826 
7827     /**
7828      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7829      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to allow using a KeyChain key
7830      * pair for authentication to Wifi networks. The key can then be used in configurations passed
7831      * to {@link android.net.wifi.WifiManager#addNetwork}.
7832      *
7833      * Starting from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} throws an
7834      * {@link IllegalArgumentException} if {@code alias} doesn't correspond to an existing key.
7835      *
7836      * @param alias The alias of the key pair.
7837      * @return {@code true} if the operation was set successfully, {@code false} otherwise.
7838      *
7839      * @throws SecurityException if the caller is not a device owner, a profile owner or
7840      *         delegated certificate chooser.
7841      * @see #revokeKeyPairFromWifiAuth
7842      */
grantKeyPairToWifiAuth(@onNull String alias)7843     public boolean grantKeyPairToWifiAuth(@NonNull String alias) {
7844         throwIfParentInstance("grantKeyPairToWifiAuth");
7845         try {
7846             return mService.setKeyGrantToWifiAuth(mContext.getPackageName(), alias, true);
7847         } catch (RemoteException e) {
7848             e.rethrowFromSystemServer();
7849         }
7850         return false;
7851     }
7852 
7853     /**
7854      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7855      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to deny using a KeyChain key
7856      * pair for authentication to Wifi networks. Configured networks using this key won't be able to
7857      * authenticate.
7858      *
7859      * Starting from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} throws an
7860      * {@link IllegalArgumentException} if {@code alias} doesn't correspond to an existing key.
7861      *
7862      * @param alias The alias of the key pair.
7863      * @return {@code true} if the operation was set successfully, {@code false} otherwise.
7864      *
7865      * @throws SecurityException if the caller is not a device owner, a profile owner or
7866      *         delegated certificate chooser.
7867      * @see #grantKeyPairToWifiAuth
7868      */
revokeKeyPairFromWifiAuth(@onNull String alias)7869     public boolean revokeKeyPairFromWifiAuth(@NonNull String alias) {
7870         throwIfParentInstance("revokeKeyPairFromWifiAuth");
7871         try {
7872             return mService.setKeyGrantToWifiAuth(mContext.getPackageName(), alias, false);
7873         } catch (RemoteException e) {
7874             e.rethrowFromSystemServer();
7875         }
7876         return false;
7877     }
7878 
7879     /**
7880      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
7881      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to query whether a KeyChain key
7882      * pair can be used for authentication to Wifi networks.
7883      *
7884      * @param alias The alias of the key pair.
7885      * @return {@code true} if the key pair can be used, {@code false} otherwise.
7886      *
7887      * @throws SecurityException if the caller is not a device owner, a profile owner or
7888      *         delegated certificate chooser.
7889      * @see #grantKeyPairToWifiAuth
7890      */
isKeyPairGrantedToWifiAuth(@onNull String alias)7891     public boolean isKeyPairGrantedToWifiAuth(@NonNull String alias) {
7892         throwIfParentInstance("isKeyPairGrantedToWifiAuth");
7893         try {
7894             return mService.isKeyPairGrantedToWifiAuth(mContext.getPackageName(), alias);
7895         } catch (RemoteException e) {
7896             e.rethrowFromSystemServer();
7897         }
7898         return false;
7899     }
7900 
7901     /**
7902      * Returns {@code true} if the device supports attestation of device identifiers in addition
7903      * to key attestation. See
7904      * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}
7905      * @return {@code true} if Device ID attestation is supported.
7906      */
isDeviceIdAttestationSupported()7907     public boolean isDeviceIdAttestationSupported() {
7908         PackageManager pm = mContext.getPackageManager();
7909         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ID_ATTESTATION);
7910     }
7911 
7912     /**
7913      * Returns {@code true} if the StrongBox Keymaster implementation on the device was provisioned
7914      * with an individual attestation certificate and can sign attestation records using it (as
7915      * attestation using an individual attestation certificate is a feature only Keymaster
7916      * implementations with StrongBox security level can implement).
7917      * For use prior to calling
7918      * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}.
7919      * @return {@code true} if individual attestation is supported.
7920      */
isUniqueDeviceAttestationSupported()7921     public boolean isUniqueDeviceAttestationSupported() {
7922         PackageManager pm = mContext.getPackageManager();
7923         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_UNIQUE_ATTESTATION);
7924     }
7925 
7926     /**
7927      * This API can be called by the following to associate certificates with a key pair that was
7928      * generated using {@link #generateKeyPair}, and set whether the key is available for the user
7929      * to choose in the certificate selection prompt:
7930      * <ul>
7931      *    <li>Device owner</li>
7932      *    <li>Profile owner</li>
7933      *    <li>Delegated certificate installer</li>
7934      *    <li>Credential management app</li>
7935      * </ul>
7936      *
7937      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7938      * can call this API. If called by the credential management app, the componentName must be
7939      * {@code null}. Note, there can only be a credential management app on an unmanaged device.
7940      *
7941      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7942      *            {@code null} if the caller is not a device admin.
7943      * @param alias The private key alias under which to install the certificate. The {@code alias}
7944      *        should denote an existing private key. If a certificate with that alias already
7945      *        exists, it will be overwritten.
7946      * @param certs The certificate chain to install. The chain should start with the leaf
7947      *        certificate and include the chain of trust in order. This will be returned by
7948      *        {@link android.security.KeyChain#getCertificateChain}.
7949      * @param isUserSelectable {@code true} to indicate that a user can select this key via the
7950      *        certificate selection prompt, {@code false} to indicate that this key can only be
7951      *        granted access by implementing
7952      *        {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
7953      * @return {@code true} if the provided {@code alias} exists and the certificates has been
7954      *        successfully associated with it, {@code false} otherwise.
7955      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7956      *         owner, or {@code admin} is null but the calling application is not a delegated
7957      *         certificate installer or credential management app.
7958      */
7959     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true)
setKeyPairCertificate(@ullable ComponentName admin, @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable)7960     public boolean setKeyPairCertificate(@Nullable ComponentName admin,
7961             @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable) {
7962         throwIfParentInstance("setKeyPairCertificate");
7963         try {
7964             final byte[] pemCert = Credentials.convertToPem(certs.get(0));
7965             byte[] pemChain = null;
7966             if (certs.size() > 1) {
7967                 pemChain = Credentials.convertToPem(
7968                         certs.subList(1, certs.size()).toArray(new Certificate[0]));
7969             }
7970             return mService.setKeyPairCertificate(admin, mContext.getPackageName(), alias, pemCert,
7971                     pemChain, isUserSelectable);
7972         } catch (RemoteException e) {
7973             throw e.rethrowFromSystemServer();
7974         } catch (CertificateException | IOException e) {
7975             Log.w(TAG, "Could not pem-encode certificate", e);
7976         }
7977         return false;
7978     }
7979 
7980     /**
7981      * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
7982      * doesn't exist.
7983      */
getCaCertAlias(byte[] certBuffer)7984     private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
7985         final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
7986         final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
7987                               new ByteArrayInputStream(certBuffer));
7988         return new TrustedCertificateStore().getCertificateAlias(cert);
7989     }
7990 
7991     /**
7992      * Called by a profile owner or device owner to grant access to privileged certificate
7993      * manipulation APIs to a third-party certificate installer app. Granted APIs include
7994      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
7995      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
7996      * <p>
7997      * Delegated certificate installer is a per-user state. The delegated access is persistent until
7998      * it is later cleared by calling this method with a null value or uninstallling the certificate
7999      * installer.
8000      * <p>
8001      * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
8002      * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
8003      * supplied certificate installer package must be installed when calling this API, otherwise an
8004      * {@link IllegalArgumentException} will be thrown.
8005      *
8006      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8007      * @param installerPackage The package name of the certificate installer which will be given
8008      *            access. If {@code null} is given the current package will be cleared.
8009      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8010      *
8011      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
8012      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
8013      */
8014     @Deprecated
setCertInstallerPackage(@onNull ComponentName admin, @Nullable String installerPackage)8015     public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
8016             installerPackage) throws SecurityException {
8017         throwIfParentInstance("setCertInstallerPackage");
8018         if (mService != null) {
8019             try {
8020                 mService.setCertInstallerPackage(admin, installerPackage);
8021             } catch (RemoteException e) {
8022                 throw e.rethrowFromSystemServer();
8023             }
8024         }
8025     }
8026 
8027     /**
8028      * Called by a profile owner or device owner to retrieve the certificate installer for the user,
8029      * or {@code null} if none is set. If there are multiple delegates this function will return one
8030      * of them.
8031      *
8032      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8033      * @return The package name of the current delegated certificate installer, or {@code null} if
8034      *         none is set.
8035      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8036      *
8037      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
8038      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
8039      */
8040     @Deprecated
getCertInstallerPackage(@onNull ComponentName admin)8041     public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
8042             throws SecurityException {
8043         throwIfParentInstance("getCertInstallerPackage");
8044         if (mService != null) {
8045             try {
8046                 return mService.getCertInstallerPackage(admin);
8047             } catch (RemoteException e) {
8048                 throw e.rethrowFromSystemServer();
8049             }
8050         }
8051         return null;
8052     }
8053 
8054     /**
8055      * Called by a profile owner or device owner to grant access to privileged APIs to another app.
8056      * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*}
8057      * constants.
8058      * <p>
8059      * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be
8060      * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra
8061      * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the
8062      * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag.
8063      * <p>
8064      * Delegated scopes are a per-user state. The delegated access is persistent until it is later
8065      * cleared by calling this method with an empty {@code scopes} list or uninstalling the
8066      * {@code delegatePackage}.
8067      *
8068      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8069      * @param delegatePackage The package name of the app which will be given access.
8070      * @param scopes The groups of privileged APIs whose access should be granted to
8071      *            {@code delegatedPackage}.
8072      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8073      */
setDelegatedScopes(@onNull ComponentName admin, @NonNull String delegatePackage, @NonNull List<String> scopes)8074      public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage,
8075             @NonNull List<String> scopes) {
8076         throwIfParentInstance("setDelegatedScopes");
8077         if (mService != null) {
8078             try {
8079                 mService.setDelegatedScopes(admin, delegatePackage, scopes);
8080             } catch (RemoteException e) {
8081                 throw e.rethrowFromSystemServer();
8082             }
8083         }
8084     }
8085 
8086     /**
8087      * Called by a profile owner or device owner to retrieve a list of the scopes given to a
8088      * delegate package. Other apps can use this method to retrieve their own delegated scopes by
8089      * passing {@code null} for {@code admin} and their own package name as
8090      * {@code delegatedPackage}.
8091      *
8092      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8093      *            {@code null} if the caller is {@code delegatedPackage}.
8094      * @param delegatedPackage The package name of the app whose scopes should be retrieved.
8095      * @return A list containing the scopes given to {@code delegatedPackage}.
8096      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8097      */
8098      @NonNull
getDelegatedScopes(@ullable ComponentName admin, @NonNull String delegatedPackage)8099      public List<String> getDelegatedScopes(@Nullable ComponentName admin,
8100              @NonNull String delegatedPackage) {
8101          throwIfParentInstance("getDelegatedScopes");
8102          if (mService != null) {
8103              try {
8104                  return mService.getDelegatedScopes(admin, delegatedPackage);
8105              } catch (RemoteException e) {
8106                  throw e.rethrowFromSystemServer();
8107              }
8108          }
8109          return null;
8110     }
8111 
8112     /**
8113      * Called by a profile owner or device owner to retrieve a list of delegate packages that were
8114      * granted a delegation scope.
8115      *
8116      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8117      * @param delegationScope The scope whose delegates should be retrieved.
8118      * @return A list of package names of the current delegated packages for
8119                {@code delegationScope}.
8120      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8121      */
8122      @Nullable
getDelegatePackages(@onNull ComponentName admin, @NonNull String delegationScope)8123      public List<String> getDelegatePackages(@NonNull ComponentName admin,
8124              @NonNull String delegationScope) {
8125         throwIfParentInstance("getDelegatePackages");
8126         if (mService != null) {
8127             try {
8128                 return mService.getDelegatePackages(admin, delegationScope);
8129             } catch (RemoteException e) {
8130                 throw e.rethrowFromSystemServer();
8131             }
8132         }
8133         return null;
8134     }
8135 
8136     /**
8137      * Service-specific error code used in implementation of {@code setAlwaysOnVpnPackage} methods.
8138      * @hide
8139      */
8140     public static final int ERROR_VPN_PACKAGE_NOT_FOUND = 1;
8141 
8142     /**
8143      * Called by a device or profile owner to configure an always-on VPN connection through a
8144      * specific application for the current user. This connection is automatically granted and
8145      * persisted after a reboot.
8146      * <p> To support the always-on feature, an app must
8147      * <ul>
8148      *     <li>declare a {@link android.net.VpnService} in its manifest, guarded by
8149      *         {@link android.Manifest.permission#BIND_VPN_SERVICE};</li>
8150      *     <li>target {@link android.os.Build.VERSION_CODES#N API 24} or above; and</li>
8151      *     <li><i>not</i> explicitly opt out of the feature through
8152      *         {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}.</li>
8153      * </ul>
8154      * The call will fail if called with the package name of an unsupported VPN app.
8155      * <p> Enabling lockdown via {@code lockdownEnabled} argument carries the risk that any failure
8156      * of the VPN provider could break networking for all apps. This method clears any lockdown
8157      * allowlist set by {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)}.
8158      * <p> Starting from {@link android.os.Build.VERSION_CODES#S API 31} calling this method with
8159      * {@code vpnPackage} set to {@code null} only removes the existing configuration if it was
8160      * previously created by this admin. To remove VPN configuration created by the user use
8161      * {@link UserManager#DISALLOW_CONFIG_VPN}.
8162      *
8163      * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
8164      *        remove an existing always-on VPN configuration.
8165      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
8166      *        {@code false} otherwise. This has no effect when clearing.
8167      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8168      * @throws NameNotFoundException if {@code vpnPackage} is not installed.
8169      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
8170      *         set as always-on, or if always-on VPN is not available.
8171      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
8172      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled)8173     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
8174             boolean lockdownEnabled) throws NameNotFoundException {
8175         setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled, Collections.emptySet());
8176     }
8177 
8178     /**
8179      * A version of {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} that allows the
8180      * admin to specify a set of apps that should be able to access the network directly when VPN
8181      * is not connected. When VPN connects these apps switch over to VPN if allowed to use that VPN.
8182      * System apps can always bypass VPN.
8183      * <p> Note that the system doesn't update the allowlist when packages are installed or
8184      * uninstalled, the admin app must call this method to keep the list up to date.
8185      * <p> When {@code lockdownEnabled} is false {@code lockdownAllowlist} is ignored . When
8186      * {@code lockdownEnabled} is {@code true} and {@code lockdownAllowlist} is {@code null} or
8187      * empty, only system apps can bypass VPN.
8188      * <p> Setting always-on VPN package to {@code null} or using
8189      * {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} clears lockdown allowlist.
8190      *
8191      * @param vpnPackage package name for an installed VPN app on the device, or {@code null}
8192      *         to remove an existing always-on VPN configuration
8193      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
8194      *         {@code false} otherwise. This has no effect when clearing.
8195      * @param lockdownAllowlist Packages that will be able to access the network directly when VPN
8196      *         is in lockdown mode but not connected. Has no effect when clearing.
8197      * @throws SecurityException if {@code admin} is not a device or a profile
8198      *         owner.
8199      * @throws NameNotFoundException if {@code vpnPackage} or one of
8200      *         {@code lockdownAllowlist} is not installed.
8201      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does
8202      *         not support being set as always-on, or if always-on VPN is not
8203      *         available.
8204      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled, @Nullable Set<String> lockdownAllowlist)8205     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
8206             boolean lockdownEnabled, @Nullable Set<String> lockdownAllowlist)
8207             throws NameNotFoundException {
8208         throwIfParentInstance("setAlwaysOnVpnPackage");
8209         if (mService != null) {
8210             try {
8211                 mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled,
8212                         lockdownAllowlist == null ? null : new ArrayList<>(lockdownAllowlist));
8213             } catch (ServiceSpecificException e) {
8214                 switch (e.errorCode) {
8215                     case ERROR_VPN_PACKAGE_NOT_FOUND:
8216                         throw new NameNotFoundException(e.getMessage());
8217                     default:
8218                         throw new RuntimeException(
8219                                 "Unknown error setting always-on VPN: " + e.errorCode, e);
8220                 }
8221             } catch (RemoteException e) {
8222                 throw e.rethrowFromSystemServer();
8223             }
8224         }
8225     }
8226 
8227     /**
8228      * Called by device or profile owner to query whether current always-on VPN is configured in
8229      * lockdown mode. Returns {@code false} when no always-on configuration is set.
8230      *
8231      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8232      *
8233      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8234      *
8235      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean)
8236      */
isAlwaysOnVpnLockdownEnabled(@onNull ComponentName admin)8237     public boolean isAlwaysOnVpnLockdownEnabled(@NonNull ComponentName admin) {
8238         throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
8239         if (mService != null) {
8240             try {
8241                 // Starting from Android R, the caller can pass the permission check in
8242                 // DevicePolicyManagerService if it holds android.permission.MAINLINE_NETWORK_STACK.
8243                 // Note that the android.permission.MAINLINE_NETWORK_STACK is a signature permission
8244                 // which is used by the NetworkStack mainline module.
8245                 return mService.isAlwaysOnVpnLockdownEnabled(admin);
8246             } catch (RemoteException e) {
8247                 throw e.rethrowFromSystemServer();
8248             }
8249         }
8250         return false;
8251     }
8252 
8253     /**
8254      * Returns whether the admin has enabled always-on VPN lockdown for the current user.
8255      *
8256      * Only callable by the system.
8257     * @hide
8258     */
8259     @UserHandleAware
isAlwaysOnVpnLockdownEnabled()8260     public boolean isAlwaysOnVpnLockdownEnabled() {
8261         throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
8262         if (mService != null) {
8263             try {
8264                 return mService.isAlwaysOnVpnLockdownEnabledForUser(myUserId());
8265             } catch (RemoteException e) {
8266                 throw e.rethrowFromSystemServer();
8267             }
8268         }
8269         return false;
8270     }
8271 
8272     /**
8273      * Called by device or profile owner to query the set of packages that are allowed to access
8274      * the network directly when always-on VPN is in lockdown mode but not connected. Returns
8275      * {@code null} when always-on VPN is not active or not in lockdown mode.
8276      *
8277      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8278      *
8279      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8280      *
8281      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
8282      */
getAlwaysOnVpnLockdownWhitelist(@onNull ComponentName admin)8283     public @Nullable Set<String> getAlwaysOnVpnLockdownWhitelist(@NonNull ComponentName admin) {
8284         throwIfParentInstance("getAlwaysOnVpnLockdownWhitelist");
8285         if (mService != null) {
8286             try {
8287                 final List<String> allowlist =
8288                         mService.getAlwaysOnVpnLockdownAllowlist(admin);
8289                 return allowlist == null ? null : new HashSet<>(allowlist);
8290             } catch (RemoteException e) {
8291                 throw e.rethrowFromSystemServer();
8292             }
8293         }
8294         return null;
8295     }
8296 
8297     /**
8298      * Called by a device or profile owner to read the name of the package administering an
8299      * always-on VPN connection for the current user. If there is no such package, or the always-on
8300      * VPN is provided by the system instead of by an application, {@code null} will be returned.
8301      *
8302      * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
8303      *         is set.
8304      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8305      */
getAlwaysOnVpnPackage(@onNull ComponentName admin)8306     public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
8307         throwIfParentInstance("getAlwaysOnVpnPackage");
8308         if (mService != null) {
8309             try {
8310                 return mService.getAlwaysOnVpnPackage(admin);
8311             } catch (RemoteException e) {
8312                 throw e.rethrowFromSystemServer();
8313             }
8314         }
8315         return null;
8316     }
8317 
8318     /**
8319      * Returns the VPN package name if the admin has enabled always-on VPN on the current user,
8320      * or {@code null} if none is set.
8321      *
8322      * Only callable by the system.
8323      * @hide
8324      */
8325     @UserHandleAware
getAlwaysOnVpnPackage()8326     public @Nullable String getAlwaysOnVpnPackage() {
8327         throwIfParentInstance("getAlwaysOnVpnPackage");
8328         if (mService != null) {
8329             try {
8330                 return mService.getAlwaysOnVpnPackageForUser(myUserId());
8331             } catch (RemoteException e) {
8332                 throw e.rethrowFromSystemServer();
8333             }
8334         }
8335         return null;
8336     }
8337 
8338     /**
8339      * Called by an application that is administering the device to disable all cameras on the
8340      * device, for this user. After setting this, no applications running as this user will be able
8341      * to access any cameras on the device.
8342      * <p>
8343      * This method can be called on the {@link DevicePolicyManager} instance,
8344      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
8345      * the profile owner of an organization-owned managed profile.
8346      * <p>
8347      * If the caller is device owner, then the restriction will be applied to all users. If
8348      * called on the parent instance, then the restriction will be applied on the personal profile.
8349      * <p>
8350      * The calling device admin must have requested
8351      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
8352      * not, a security exception will be thrown.
8353      * <p>
8354      * <b>Note</b>, this policy type is deprecated for legacy device admins since
8355      * {@link android.os.Build.VERSION_CODES#Q}. On Android
8356      * {@link android.os.Build.VERSION_CODES#Q} devices, legacy device admins targeting SDK
8357      * version {@link android.os.Build.VERSION_CODES#P} or below can still call this API to
8358      * disable camera, while legacy device admins targeting SDK version
8359      * {@link android.os.Build.VERSION_CODES#Q} will receive a SecurityException. Starting
8360      * from Android {@link android.os.Build.VERSION_CODES#R}, requests to disable camera from
8361      * legacy device admins targeting SDK version {@link android.os.Build.VERSION_CODES#P} or
8362      * below will be silently ignored.
8363      * <p>
8364      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the camera disabled
8365      * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
8366      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
8367      * successfully set or not. This callback will contain:
8368      * <ul>
8369      * <li> The policy identifier returned from
8370      * {@link DevicePolicyIdentifiers#getIdentifierForUserRestriction(String)} with user restriction
8371      * {@link UserManager#DISALLOW_CAMERA}
8372      * <li> The {@link TargetUser} that this policy relates to
8373      * <li> The {@link PolicyUpdateResult}, which will be
8374      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
8375      * reason the policy failed to be set
8376      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
8377      * </ul>
8378      * If there has been a change to the policy,
8379      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
8380      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
8381      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
8382      * will contain the reason why the policy changed.
8383      *
8384      * @param admin Which {@link DeviceAdminReceiver} this request is associated with or null if
8385                      the caller is not a device admin
8386      * @param disabled Whether or not the camera should be disabled.
8387      * @throws SecurityException if {@code admin} is not an active administrator or does not use
8388      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
8389      */
8390     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CAMERA, conditional = true)
setCameraDisabled(@ullable ComponentName admin, boolean disabled)8391     public void setCameraDisabled(@Nullable ComponentName admin, boolean disabled) {
8392         if (mService != null) {
8393             try {
8394                 mService.setCameraDisabled(admin, mContext.getPackageName(), disabled,
8395                         mParentInstance);
8396             } catch (RemoteException e) {
8397                 throw e.rethrowFromSystemServer();
8398             }
8399         }
8400     }
8401 
8402     /**
8403      * Determine whether or not the device's cameras have been disabled for this user,
8404      * either by the calling admin, if specified, or all admins.
8405      * <p>
8406      * This method can be called on the {@link DevicePolicyManager} instance,
8407      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
8408      * the profile owner of an organization-owned managed profile.
8409      *
8410      * @param admin The name of the admin component to check, or {@code null} to check whether any
8411      *              admins have disabled the camera
8412      */
8413     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CAMERA, conditional = true)
getCameraDisabled(@ullable ComponentName admin)8414     public boolean getCameraDisabled(@Nullable ComponentName admin) {
8415         return getCameraDisabled(admin, myUserId());
8416     }
8417 
8418     /** @hide per-user version */
8419     @UnsupportedAppUsage
getCameraDisabled(@ullable ComponentName admin, int userHandle)8420     public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
8421         if (mService != null) {
8422             try {
8423                 return mService.getCameraDisabled(admin, mContext.getPackageName(), userHandle,
8424                         mParentInstance);
8425             } catch (RemoteException e) {
8426                 throw e.rethrowFromSystemServer();
8427             }
8428         }
8429         return false;
8430     }
8431 
8432     /**
8433      * Called by a device owner to request a bugreport.
8434      * <p>
8435      * If the device contains secondary users or profiles, they must be affiliated with the device.
8436      * Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
8437      *
8438      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8439      * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
8440      *         wasn't triggered because a previous bugreport operation is still active (either the
8441      *         bugreport is still running or waiting for the user to share or decline)
8442      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
8443      *         profile or secondary user that is not affiliated with the device.
8444      * @see #isAffiliatedUser
8445      */
requestBugreport(@onNull ComponentName admin)8446     public boolean requestBugreport(@NonNull ComponentName admin) {
8447         throwIfParentInstance("requestBugreport");
8448         if (mService != null) {
8449             try {
8450                 return mService.requestBugreport(admin);
8451             } catch (RemoteException e) {
8452                 throw e.rethrowFromSystemServer();
8453             }
8454         }
8455         return false;
8456     }
8457 
8458     /**
8459      * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
8460      * screen capture also prevents the content from being shown on display devices that do not have
8461      * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
8462      * secure surfaces and secure displays.
8463      * <p>
8464      * This method can be called on the {@link DevicePolicyManager} instance, returned by
8465      * {@link #getParentProfileInstance(ComponentName)}, where the calling device admin must be
8466      * the profile owner of an organization-owned managed profile. If it is not, a security
8467      * exception will be thrown.
8468      * <p>
8469      * If the caller is device owner or called on the parent instance by a profile owner of an
8470      * organization-owned managed profile, then the restriction will be applied to all users.
8471      * <p>
8472      * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
8473      * assist requests for all activities of the relevant user.
8474      *
8475      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
8476      *              caller is not a device admin.
8477      * @param disabled Whether screen capture is disabled or not.
8478      * @throws SecurityException if the caller is not permitted to control screen capture policy.
8479      */
8480     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SCREEN_CAPTURE, conditional = true)
setScreenCaptureDisabled(@ullable ComponentName admin, boolean disabled)8481     public void setScreenCaptureDisabled(@Nullable ComponentName admin, boolean disabled) {
8482         if (mService != null) {
8483             try {
8484                 mService.setScreenCaptureDisabled(
8485                         admin, mContext.getPackageName(), disabled, mParentInstance);
8486             } catch (RemoteException e) {
8487                 throw e.rethrowFromSystemServer();
8488             }
8489         }
8490     }
8491 
8492     /**
8493      * Determine whether or not screen capture has been disabled by the calling
8494      * admin, if specified, or all admins.
8495      * <p>
8496      * This method can be called on the {@link DevicePolicyManager} instance,
8497      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
8498      * the profile owner of an organization-owned managed profile (the calling admin must be
8499      * specified).
8500      *
8501      * @param admin The name of the admin component to check, or {@code null} to check whether any
8502      *              admins have disabled screen capture.
8503      */
getScreenCaptureDisabled(@ullable ComponentName admin)8504     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
8505         return getScreenCaptureDisabled(admin, myUserId());
8506     }
8507 
8508     /** @hide per-user version */
getScreenCaptureDisabled(@ullable ComponentName admin, int userHandle)8509     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
8510         if (mService != null) {
8511             try {
8512                 return mService.getScreenCaptureDisabled(admin, userHandle, mParentInstance);
8513             } catch (RemoteException e) {
8514                 throw e.rethrowFromSystemServer();
8515             }
8516         }
8517         return false;
8518     }
8519 
8520     /**
8521      * Called by a device/profile owner to set nearby notification streaming policy. Notification
8522      * streaming is sending notification data from pre-installed apps to nearby devices.
8523      *
8524      * @param policy One of the {@code NearbyStreamingPolicy} constants.
8525      * @throws SecurityException if caller is not a device or profile owner
8526      */
setNearbyNotificationStreamingPolicy(@earbyStreamingPolicy int policy)8527     public void setNearbyNotificationStreamingPolicy(@NearbyStreamingPolicy int policy) {
8528         throwIfParentInstance("setNearbyNotificationStreamingPolicy");
8529         if (mService == null) {
8530             return;
8531         }
8532         try {
8533             mService.setNearbyNotificationStreamingPolicy(policy);
8534         } catch (RemoteException e) {
8535             throw e.rethrowFromSystemServer();
8536         }
8537     }
8538 
8539     /**
8540      * Returns the current runtime nearby notification streaming policy set by the device or profile
8541      * owner.
8542      * <p>
8543      * The caller must be the target user's device owner/profile owner or hold the
8544      * {@link android.Manifest.permission#READ_NEARBY_STREAMING_POLICY READ_NEARBY_STREAMING_POLICY}
8545      * permission.
8546      */
8547     @RequiresPermission(
8548             value = android.Manifest.permission.READ_NEARBY_STREAMING_POLICY,
8549             conditional = true)
getNearbyNotificationStreamingPolicy()8550     public @NearbyStreamingPolicy int getNearbyNotificationStreamingPolicy() {
8551         return getNearbyNotificationStreamingPolicy(myUserId());
8552     }
8553 
8554     /** @hide per-user version */
getNearbyNotificationStreamingPolicy(int userId)8555     public @NearbyStreamingPolicy int getNearbyNotificationStreamingPolicy(int userId) {
8556         throwIfParentInstance("getNearbyNotificationStreamingPolicy");
8557         if (mService == null) {
8558             return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
8559         }
8560         try {
8561             return mService.getNearbyNotificationStreamingPolicy(userId);
8562         } catch (RemoteException re) {
8563             throw re.rethrowFromSystemServer();
8564         }
8565     }
8566 
8567     /**
8568      * Called by a device/profile owner to set nearby app streaming policy. App streaming is when
8569      * the device starts an app on a virtual display and sends a video stream of the app to nearby
8570      * devices.
8571      *
8572      * @param policy One of the {@code NearbyStreamingPolicy} constants.
8573      * @throws SecurityException if caller is not a device or profile owner.
8574      */
setNearbyAppStreamingPolicy(@earbyStreamingPolicy int policy)8575     public void setNearbyAppStreamingPolicy(@NearbyStreamingPolicy int policy) {
8576         throwIfParentInstance("setNearbyAppStreamingPolicy");
8577         if (mService == null) {
8578             return;
8579         }
8580         try {
8581             mService.setNearbyAppStreamingPolicy(policy);
8582         } catch (RemoteException e) {
8583             throw e.rethrowFromSystemServer();
8584         }
8585     }
8586 
8587     /**
8588      * Returns the current runtime nearby app streaming policy set by the device or profile owner.
8589      * <p>
8590      * The caller must be the target user's device owner/profile owner or hold the
8591      * {@link android.Manifest.permission#READ_NEARBY_STREAMING_POLICY READ_NEARBY_STREAMING_POLICY}
8592      * permission.
8593      */
8594     @RequiresPermission(
8595             value = android.Manifest.permission.READ_NEARBY_STREAMING_POLICY,
8596             conditional = true)
getNearbyAppStreamingPolicy()8597     public @NearbyStreamingPolicy int getNearbyAppStreamingPolicy() {
8598         return getNearbyAppStreamingPolicy(myUserId());
8599     }
8600 
8601     /** @hide per-user version */
getNearbyAppStreamingPolicy(int userId)8602     public @NearbyStreamingPolicy int getNearbyAppStreamingPolicy(int userId) {
8603         throwIfParentInstance("getNearbyAppStreamingPolicy");
8604         if (mService == null) {
8605             return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
8606         }
8607         try {
8608             return mService.getNearbyAppStreamingPolicy(userId);
8609         } catch (RemoteException re) {
8610             throw re.rethrowFromSystemServer();
8611         }
8612     }
8613 
8614     /**
8615      * Called by a device owner, or alternatively a profile owner from Android 8.0 (API level 26) or
8616      * higher, to set whether auto time is required. If auto time is required, no user will be able
8617      * set the date and time and network date and time will be used.
8618      * <p>
8619      * Note: If auto time is required the user can still manually set the time zone. Staring from
8620      * Android 11, if auto time is required, the user cannot manually set the time zone.
8621      * <p>
8622      * The calling device admin must be a device owner, or alternatively a profile owner from
8623      * Android 8.0 (API level 26) or higher. If it is not, a security exception will be thrown.
8624      * <p>
8625      * Staring from Android 11, this API switches to use
8626      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} to enforce the auto time settings. Calling
8627      * this API to enforce auto time will result in
8628      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being set, while calling this API to lift
8629      * the requirement will result in {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being cleared.
8630      * From Android 11, this API can also no longer be called on a managed profile.
8631      *
8632      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8633      * @param required Whether auto time is set required or not.
8634      * @throws SecurityException if {@code admin} is not a device owner, not a profile owner or
8635      * if this API is called on a managed profile.
8636      * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #setAutoTimeEnabled}
8637      * to turn auto time on or off and use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
8638      * to prevent the user from changing this setting.
8639      */
8640     @Deprecated
setAutoTimeRequired(@onNull ComponentName admin, boolean required)8641     public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
8642         throwIfParentInstance("setAutoTimeRequired");
8643         if (mService != null) {
8644             try {
8645                 mService.setAutoTimeRequired(admin, required);
8646             } catch (RemoteException e) {
8647                 throw e.rethrowFromSystemServer();
8648             }
8649         }
8650     }
8651 
8652     /**
8653      * @return true if auto time is required.
8654      * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #getAutoTimeEnabled}
8655      */
8656     @Deprecated
getAutoTimeRequired()8657     public boolean getAutoTimeRequired() {
8658         throwIfParentInstance("getAutoTimeRequired");
8659         if (mService != null) {
8660             try {
8661                 return mService.getAutoTimeRequired();
8662             } catch (RemoteException e) {
8663                 throw e.rethrowFromSystemServer();
8664             }
8665         }
8666         return false;
8667     }
8668 
8669     /**
8670      * Called by a device owner, a profile owner for the primary user or a profile
8671      * owner of an organization-owned managed profile to turn auto time on and off.
8672      * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
8673      * to prevent the user from changing this setting.
8674      * <p>
8675      * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
8676      * no user will be able set the date and time. Instead, the network date
8677      * and time will be used.
8678      *
8679      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
8680      *              caller is not a device admin.
8681      * @param enabled Whether time should be obtained automatically from the network or not.
8682      * @throws SecurityException if caller is not a device owner, a profile owner for the
8683      * primary user, or a profile owner of an organization-owned managed profile.
8684      */
8685     @RequiresPermission(value = SET_TIME, conditional = true)
setAutoTimeEnabled(@ullable ComponentName admin, boolean enabled)8686     public void setAutoTimeEnabled(@Nullable ComponentName admin, boolean enabled) {
8687         throwIfParentInstance("setAutoTimeEnabled");
8688         if (mService != null) {
8689             try {
8690                 mService.setAutoTimeEnabled(admin, mContext.getPackageName(), enabled);
8691             } catch (RemoteException e) {
8692                 throw e.rethrowFromSystemServer();
8693             }
8694         }
8695     }
8696 
8697     /**
8698      * Returns true if auto time is enabled on the device.
8699      *
8700      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
8701      *              caller is not a device admin.
8702      * @return true if auto time is enabled on the device.
8703      * @throws SecurityException if caller is not a device owner, a profile owner for the
8704      * primary user, or a profile owner of an organization-owned managed profile.
8705      */
8706     @RequiresPermission(anyOf = {SET_TIME, QUERY_ADMIN_POLICY}, conditional = true)
getAutoTimeEnabled(@ullable ComponentName admin)8707     public boolean getAutoTimeEnabled(@Nullable ComponentName admin) {
8708         throwIfParentInstance("getAutoTimeEnabled");
8709         if (mService != null) {
8710             try {
8711                 return mService.getAutoTimeEnabled(admin, mContext.getPackageName());
8712             } catch (RemoteException e) {
8713                 throw e.rethrowFromSystemServer();
8714             }
8715         }
8716         return false;
8717     }
8718 
8719     /**
8720      * Called by a device owner, a profile owner for the primary user or a profile
8721      * owner of an organization-owned managed profile to turn auto time zone on and off.
8722      * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
8723      * to prevent the user from changing this setting.
8724      * <p>
8725      * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
8726      * no user will be able set the date and time zone. Instead, the network date
8727      * and time zone will be used.
8728      *
8729      * @param admin Which {@link DeviceAdminReceiver} this request is associated with or Null if the
8730      *              caller is not a device admin.
8731      * @param enabled Whether time zone should be obtained automatically from the network or not.
8732      * @throws SecurityException if caller is not a device owner, a profile owner for the
8733      * primary user, or a profile owner of an organization-owned managed profile.
8734      */
8735     @SupportsCoexistence
8736     @RequiresPermission(value = SET_TIME_ZONE, conditional = true)
setAutoTimeZoneEnabled(@ullable ComponentName admin, boolean enabled)8737     public void setAutoTimeZoneEnabled(@Nullable ComponentName admin, boolean enabled) {
8738         throwIfParentInstance("setAutoTimeZone");
8739         if (mService != null) {
8740             try {
8741                 mService.setAutoTimeZoneEnabled(admin, mContext.getPackageName(), enabled);
8742             } catch (RemoteException e) {
8743                 throw e.rethrowFromSystemServer();
8744             }
8745         }
8746     }
8747 
8748     /**
8749      * Returns true if auto time zone is enabled on the device.
8750      *
8751      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
8752      *              caller is not a device admin.
8753      * @return true if auto time zone is enabled on the device.
8754      * @throws SecurityException if caller is not a device owner, a profile owner for the
8755      * primary user, or a profile owner of an organization-owned managed profile.
8756      */
8757     @RequiresPermission(anyOf = {SET_TIME_ZONE, QUERY_ADMIN_POLICY}, conditional = true)
getAutoTimeZoneEnabled(@ullable ComponentName admin)8758     public boolean getAutoTimeZoneEnabled(@Nullable ComponentName admin) {
8759         throwIfParentInstance("getAutoTimeZone");
8760         if (mService != null) {
8761             try {
8762                 return mService.getAutoTimeZoneEnabled(admin, mContext.getPackageName());
8763             } catch (RemoteException e) {
8764                 throw e.rethrowFromSystemServer();
8765             }
8766         }
8767         return false;
8768     }
8769 
8770     /**
8771      * TODO (b/137101239): remove this method in follow-up CL
8772      * since it's only used for split system user.
8773      * Called by a device owner to set whether all users created on the device should be ephemeral.
8774      * @hide
8775      */
setForceEphemeralUsers( @onNull ComponentName admin, boolean forceEphemeralUsers)8776     public void setForceEphemeralUsers(
8777             @NonNull ComponentName admin, boolean forceEphemeralUsers) {
8778         throwIfParentInstance("setForceEphemeralUsers");
8779         if (mService != null) {
8780             try {
8781                 mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
8782             } catch (RemoteException e) {
8783                 throw e.rethrowFromSystemServer();
8784             }
8785         }
8786     }
8787 
8788     /**
8789      * TODO (b/137101239): remove this method in follow-up CL
8790      * since it's only used for split system user.
8791      * @return true if all users are created ephemeral.
8792      * @throws SecurityException if {@code admin} is not a device owner.
8793      * @hide
8794      */
getForceEphemeralUsers(@onNull ComponentName admin)8795     public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
8796         throwIfParentInstance("getForceEphemeralUsers");
8797         if (mService != null) {
8798             try {
8799                 return mService.getForceEphemeralUsers(admin);
8800             } catch (RemoteException e) {
8801                 throw e.rethrowFromSystemServer();
8802             }
8803         }
8804         return false;
8805     }
8806 
8807     /**
8808      * Called by an application that is administering the device to disable keyguard customizations,
8809      * such as widgets. After setting this, keyguard features will be disabled according to the
8810      * provided feature list.
8811      * <p>
8812      * A calling device admin must have requested
8813      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
8814      * if it has not, a security exception will be thrown.
8815      * <p>
8816      * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
8817      * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
8818      * profile owner of a managed profile can set:
8819      * <ul>
8820      * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
8821      * is no separate challenge set on the managed profile.
8822      * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FACE} or
8823      * {@link #KEYGUARD_DISABLE_IRIS} which affects the managed profile challenge if
8824      * there is one, or the parent user otherwise.
8825      * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
8826      * by applications in the managed profile.
8827      * </ul>
8828      * <p>
8829      * From version {@link android.os.Build.VERSION_CODES#R} the profile owner of an
8830      * organization-owned managed profile can set:
8831      * <ul>
8832      * <li>{@link #KEYGUARD_DISABLE_SECURE_CAMERA} which affects the parent user when called on the
8833      * parent profile.
8834      * <li>{@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS} which affects the parent user when called
8835      * on the parent profile.
8836      * </ul>
8837      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, {@link #KEYGUARD_DISABLE_FINGERPRINT},
8838      * {@link #KEYGUARD_DISABLE_FACE}, {@link #KEYGUARD_DISABLE_IRIS},
8839      * {@link #KEYGUARD_DISABLE_SECURE_CAMERA} and {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS}
8840      * can also be set on the {@link DevicePolicyManager} instance returned by
8841      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
8842      * profile. {@link #KEYGUARD_DISABLE_SECURE_CAMERA} can only be set on the parent profile
8843      * instance if the calling device admin is the profile owner of an organization-owned
8844      * managed profile.
8845      * <p>
8846      * Requests to disable other features on a managed profile will be ignored.
8847      * <p>
8848      * The admin can check which features have been disabled by calling
8849      * {@link #getKeyguardDisabledFeatures(ComponentName)}
8850      *
8851      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
8852      *              caller is not a device admin
8853      * @param which The disabled features flag which can be either
8854      *            {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
8855      *            {@link #KEYGUARD_DISABLE_FEATURES_ALL}, or a combination of
8856      *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
8857      *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
8858      *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
8859      *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
8860      *            {@link #KEYGUARD_DISABLE_FINGERPRINT},
8861      *            {@link #KEYGUARD_DISABLE_FACE},
8862      *            {@link #KEYGUARD_DISABLE_IRIS},
8863      *            {@link #KEYGUARD_DISABLE_SHORTCUTS_ALL}.
8864      * @throws SecurityException if {@code admin} is not an active administrator or does not use
8865      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
8866      */
8867     @RequiresPermission(value = MANAGE_DEVICE_POLICY_KEYGUARD, conditional = true)
setKeyguardDisabledFeatures(@ullable ComponentName admin, int which)8868     public void setKeyguardDisabledFeatures(@Nullable ComponentName admin, int which) {
8869         if (mService != null) {
8870             try {
8871                 mService.setKeyguardDisabledFeatures(
8872                         admin, mContext.getPackageName(), which, mParentInstance);
8873             } catch (RemoteException e) {
8874                 throw e.rethrowFromSystemServer();
8875             }
8876         }
8877     }
8878 
8879     /**
8880      * Determine whether or not features have been disabled in keyguard either by the calling
8881      * admin, if specified, or all admins that set restrictions on this user and its participating
8882      * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
8883      *
8884      * <p>This method can be called on the {@link DevicePolicyManager} instance
8885      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
8886      * restrictions on the parent profile.
8887      *
8888      * @param admin The name of the admin component to check, or {@code null} to check whether any
8889      * admins have disabled features in keyguard.
8890      * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
8891      * for a list.
8892      */
getKeyguardDisabledFeatures(@ullable ComponentName admin)8893     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
8894         return getKeyguardDisabledFeatures(admin, myUserId());
8895     }
8896 
8897     private IpcDataCache<Pair<ComponentName, Integer>, Integer> mGetKeyGuardDisabledFeaturesCache =
8898             new IpcDataCache<>(sDpmCaches.child("getKeyguardDisabledFeatures"),
8899                     (query) -> getService().getKeyguardDisabledFeatures(
8900                             query.first, query.second, isParentInstance()));
8901 
8902     /** @hide per-user version */
8903     @UnsupportedAppUsage
getKeyguardDisabledFeatures(@ullable ComponentName admin, int userHandle)8904     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
8905         if (mService != null) {
8906             return mGetKeyGuardDisabledFeaturesCache.query(new Pair<>(admin, userHandle));
8907         } else {
8908             return KEYGUARD_DISABLE_FEATURES_NONE;
8909         }
8910     }
8911 
8912     /**
8913      * @hide
8914      */
8915     @TestApi
8916     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
8917     @RequiresPermission(allOf = {
8918             MANAGE_DEVICE_ADMINS,
8919             INTERACT_ACROSS_USERS_FULL
8920     })
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing, int userHandle)8921     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
8922             int userHandle) {
8923         if (mService != null) {
8924             try {
8925                 mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
8926             } catch (RemoteException e) {
8927                 throw e.rethrowFromSystemServer();
8928             }
8929         }
8930     }
8931 
8932     /**
8933      * @hide
8934      */
8935     @UnsupportedAppUsage
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing)8936     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
8937         setActiveAdmin(policyReceiver, refreshing, myUserId());
8938     }
8939 
8940     /**
8941      * Called by a privileged caller holding {@code BIND_DEVICE_ADMIN} permission to retrieve
8942      * the remove warning for the given device admin.
8943      * @hide
8944      */
getRemoveWarning(@ullable ComponentName admin, RemoteCallback result)8945     public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
8946         if (mService != null) {
8947             try {
8948                 mService.getRemoveWarning(admin, result, myUserId());
8949             } catch (RemoteException e) {
8950                 throw e.rethrowFromSystemServer();
8951             }
8952         }
8953     }
8954 
8955     /**
8956      * @hide
8957      */
8958     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportPasswordChanged(PasswordMetrics metrics, @UserIdInt int userId)8959     public void reportPasswordChanged(PasswordMetrics metrics, @UserIdInt int userId) {
8960         if (mService != null) {
8961             try {
8962                 mService.reportPasswordChanged(metrics, userId);
8963             } catch (RemoteException e) {
8964                 throw e.rethrowFromSystemServer();
8965             }
8966         }
8967     }
8968 
8969     /**
8970      * @hide
8971      */
8972     @UnsupportedAppUsage
8973     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedPasswordAttempt(int userHandle)8974     public void reportFailedPasswordAttempt(int userHandle) {
8975         if (mService != null) {
8976             try {
8977                 mService.reportFailedPasswordAttempt(userHandle, mParentInstance);
8978             } catch (RemoteException e) {
8979                 throw e.rethrowFromSystemServer();
8980             }
8981         }
8982     }
8983 
8984     /**
8985      * @hide
8986      */
8987     @UnsupportedAppUsage
8988     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulPasswordAttempt(int userHandle)8989     public void reportSuccessfulPasswordAttempt(int userHandle) {
8990         if (mService != null) {
8991             try {
8992                 mService.reportSuccessfulPasswordAttempt(userHandle);
8993             } catch (RemoteException e) {
8994                 throw e.rethrowFromSystemServer();
8995             }
8996         }
8997     }
8998 
8999     /**
9000      * @hide
9001      */
9002     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedBiometricAttempt(int userHandle)9003     public void reportFailedBiometricAttempt(int userHandle) {
9004         if (mService != null) {
9005             try {
9006                 mService.reportFailedBiometricAttempt(userHandle);
9007             } catch (RemoteException e) {
9008                 throw e.rethrowFromSystemServer();
9009             }
9010         }
9011     }
9012 
9013     /**
9014      * @hide
9015      */
9016     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulBiometricAttempt(int userHandle)9017     public void reportSuccessfulBiometricAttempt(int userHandle) {
9018         if (mService != null) {
9019             try {
9020                 mService.reportSuccessfulBiometricAttempt(userHandle);
9021             } catch (RemoteException e) {
9022                 throw e.rethrowFromSystemServer();
9023             }
9024         }
9025     }
9026 
9027     /**
9028      * Should be called when keyguard has been dismissed.
9029      * @hide
9030      */
reportKeyguardDismissed(int userHandle)9031     public void reportKeyguardDismissed(int userHandle) {
9032         if (mService != null) {
9033             try {
9034                 mService.reportKeyguardDismissed(userHandle);
9035             } catch (RemoteException e) {
9036                 throw e.rethrowFromSystemServer();
9037             }
9038         }
9039     }
9040 
9041     /**
9042      * Should be called when keyguard view has been shown to the user.
9043      * @hide
9044      */
reportKeyguardSecured(int userHandle)9045     public void reportKeyguardSecured(int userHandle) {
9046         if (mService != null) {
9047             try {
9048                 mService.reportKeyguardSecured(userHandle);
9049             } catch (RemoteException e) {
9050                 throw e.rethrowFromSystemServer();
9051             }
9052         }
9053     }
9054 
9055     /**
9056      * Sets the given package as the device owner.
9057      *
9058      * <p>Preconditions:
9059      * <ul>
9060      *   <li>The package must already be installed.
9061      *   <li>There must not already be a device owner.
9062      *   <li>Only apps with the {@code MANAGE_PROFILE_AND_DEVICE_OWNERS} permission or the
9063      *       {@link Process#SHELL_UID Shell UID} can call this method.
9064      * </ul>
9065      *
9066      * <p>Calling this after the setup phase of the device owner user has completed is allowed only
9067      * if the caller is the {@link Process#SHELL_UID Shell UID}, and there are no additional users
9068      * (except when the device runs on headless system user mode, in which case it could have exact
9069      * one extra user, which is the current user - the device owner will be set in the
9070      * {@link UserHandle#SYSTEM system} user and a profile owner will be set in the current user)
9071      * and no accounts.
9072      *
9073      * @param who the component name to be registered as device owner.
9074      * @param userId ID of the user on which the device owner runs.
9075      *
9076      * @return whether the package was successfully registered as the device owner.
9077      *
9078      * @throws IllegalArgumentException if the package name is {@code null} or invalid.
9079      * @throws IllegalStateException If the preconditions mentioned are not met.
9080      *
9081      * @hide
9082      */
9083     @TestApi
9084     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setDeviceOwner(@onNull ComponentName who, @UserIdInt int userId)9085     public boolean setDeviceOwner(@NonNull ComponentName who, @UserIdInt int userId) {
9086         if (mService != null) {
9087             try {
9088                 return mService.setDeviceOwner(who, userId,
9089                         /* setProfileOwnerOnCurrentUserIfNecessary= */ true);
9090             } catch (RemoteException re) {
9091                 throw re.rethrowFromSystemServer();
9092             }
9093         }
9094         return false;
9095     }
9096 
9097     /**
9098      * Same as {@link #setDeviceOwner(ComponentName, int)}, but without setting the profile
9099      * owner on current user when running on headless system user mode - should be used only by
9100      * testing infra.
9101      *
9102      * @hide
9103      */
9104     @TestApi
9105     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setDeviceOwnerOnly( @onNull ComponentName who, @UserIdInt int userId)9106     public boolean setDeviceOwnerOnly(
9107             @NonNull ComponentName who, @UserIdInt int userId) {
9108         if (mService != null) {
9109             try {
9110                 return mService.setDeviceOwner(who, userId,
9111                         /* setProfileOwnerOnCurrentUserIfNecessary= */ false);
9112             } catch (RemoteException re) {
9113                 throw re.rethrowFromSystemServer();
9114             }
9115         }
9116         return false;
9117     }
9118 
9119     /**
9120      * Used to determine if a particular package has been registered as a Device Owner app.
9121      * A device owner app is a special device admin that cannot be deactivated by the user, once
9122      * activated as a device admin. It also cannot be uninstalled. To check whether a particular
9123      * package is currently registered as the device owner app, pass in the package name from
9124      * {@link Context#getPackageName()} to this method.<p/>This is useful for device
9125      * admin apps that want to check whether they are also registered as the device owner app. The
9126      * exact mechanism by which a device admin app is registered as a device owner app is defined by
9127      * the setup process.
9128      * @param packageName the package name of the app, to compare with the registered device owner
9129      * app, if any.
9130      * @return whether or not the package is registered as the device owner app.
9131      */
isDeviceOwnerApp(String packageName)9132     public boolean isDeviceOwnerApp(String packageName) {
9133         throwIfParentInstance("isDeviceOwnerApp");
9134         return isDeviceOwnerAppOnCallingUser(packageName);
9135     }
9136 
9137     /**
9138      * @return true if a package is registered as device owner, only when it's running on the
9139      * calling user.
9140      *
9141      * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
9142      * @hide
9143      */
isDeviceOwnerAppOnCallingUser(String packageName)9144     public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
9145         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
9146     }
9147 
9148     /**
9149      * @return true if a package is registered as device owner, even if it's running on a different
9150      * user.
9151      *
9152      * <p>Requires the MANAGE_USERS permission.
9153      *
9154      * @hide
9155      */
isDeviceOwnerAppOnAnyUser(String packageName)9156     public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
9157         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
9158     }
9159 
9160     /**
9161      * @return device owner component name, only when it's running on the calling user.
9162      *
9163      * @hide
9164      */
getDeviceOwnerComponentOnCallingUser()9165     public ComponentName getDeviceOwnerComponentOnCallingUser() {
9166         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
9167     }
9168 
9169     /**
9170      * @return device owner component name, even if it's running on a different user.
9171      *
9172      * @hide
9173      */
9174     @SystemApi
9175     @RequiresPermission(anyOf = {
9176             android.Manifest.permission.MANAGE_USERS,
9177             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
9178     })
getDeviceOwnerComponentOnAnyUser()9179     public ComponentName getDeviceOwnerComponentOnAnyUser() {
9180         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
9181     }
9182 
isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly)9183     private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
9184         if (packageName == null) {
9185             return false;
9186         }
9187         final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
9188         if (deviceOwner == null) {
9189             return false;
9190         }
9191         return packageName.equals(deviceOwner.getPackageName());
9192     }
9193 
getDeviceOwnerComponentInner(boolean callingUserOnly)9194     private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
9195         if (mService != null) {
9196             try {
9197                 return mService.getDeviceOwnerComponent(callingUserOnly);
9198             } catch (RemoteException re) {
9199                 throw re.rethrowFromSystemServer();
9200             }
9201         }
9202         return null;
9203     }
9204 
9205     /**
9206      * @return Handle of the user who runs device owner, or {@code null} if there's no device owner.
9207      *
9208      * @hide
9209      */
9210     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
9211     @SystemApi
getDeviceOwnerUser()9212     public @Nullable UserHandle getDeviceOwnerUser() {
9213         if (mService != null) {
9214             try {
9215                 int userId = mService.getDeviceOwnerUserId();
9216 
9217                 if (userId != UserHandle.USER_NULL) {
9218                     return UserHandle.of(userId);
9219                 }
9220             } catch (RemoteException re) {
9221                 throw re.rethrowFromSystemServer();
9222             }
9223         }
9224         return null;
9225     }
9226 
9227     /**
9228      * @hide
9229      */
getDeviceOwnerUserId()9230     public int getDeviceOwnerUserId() {
9231         if (mService != null) {
9232             try {
9233                 return mService.getDeviceOwnerUserId();
9234             } catch (RemoteException re) {
9235                 throw re.rethrowFromSystemServer();
9236             }
9237         }
9238         return UserHandle.USER_NULL;
9239     }
9240 
9241     /**
9242      * Clears the current device owner. The caller must be the device owner. This function should be
9243      * used cautiously as once it is called it cannot be undone. The device owner can only be set as
9244      * a part of device setup, before it completes.
9245      * <p>
9246      * While some policies previously set by the device owner will be cleared by this method, it is
9247      * a best-effort process and some other policies will still remain in place after the device
9248      * owner is cleared.
9249      *
9250      * @param packageName The package name of the device owner.
9251      * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
9252      *             does not own the current device owner component.
9253      *
9254      * @deprecated This method is expected to be used for testing purposes only. The device owner
9255      * will lose control of the device and its data after calling it. In order to protect any
9256      * sensitive data that remains on the device, it is advised that the device owner factory resets
9257      * the device instead of calling this method. See {@link #wipeData(int)}.
9258      */
9259     @Deprecated
clearDeviceOwnerApp(String packageName)9260     public void clearDeviceOwnerApp(String packageName) {
9261         throwIfParentInstance("clearDeviceOwnerApp");
9262         if (mService != null) {
9263             try {
9264                 mService.clearDeviceOwner(packageName);
9265             } catch (RemoteException re) {
9266                 throw re.rethrowFromSystemServer();
9267             }
9268         }
9269     }
9270 
9271     /**
9272      * Returns the device owner package name, only if it's running on the calling user.
9273      *
9274      * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
9275      *
9276      * @hide
9277      */
9278     @SystemApi
9279     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwner()9280     public @Nullable String getDeviceOwner() {
9281         throwIfParentInstance("getDeviceOwner");
9282         final ComponentName name = getDeviceOwnerComponentOnCallingUser();
9283         return name != null ? name.getPackageName() : null;
9284     }
9285 
9286     private IpcDataCache<Void, Boolean> mHasDeviceOwnerCache =
9287             new IpcDataCache<>(sDpmCaches.child("hasDeviceOwner"),
9288                     (query) -> getService().hasDeviceOwner());
9289 
9290     /**
9291      * Called by the system to find out whether the device is managed by a Device Owner.
9292      *
9293      * @return whether the device is managed by a Device Owner.
9294      * @throws SecurityException if the caller is not the device owner, does not hold
9295      *         MANAGE_USERS or MANAGE_PROFILE_AND_DEVICE_OWNERS permissions and is not the system.
9296      *
9297      * @hide
9298      */
9299     @SystemApi
9300     @SuppressLint("RequiresPermission")
isDeviceManaged()9301     public boolean isDeviceManaged() {
9302         return mHasDeviceOwnerCache.query(null);
9303     }
9304 
9305     /**
9306      * Returns the device owner name.  Note this method *will* return the device owner
9307      * name when it's running on a different user.
9308      *
9309      * @hide
9310      */
9311     @SystemApi
9312     @RequiresPermission(anyOf = {
9313             android.Manifest.permission.MANAGE_USERS,
9314             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
9315     })
getDeviceOwnerNameOnAnyUser()9316     public String getDeviceOwnerNameOnAnyUser() {
9317         throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
9318         if (mService != null) {
9319             try {
9320                 return mService.getDeviceOwnerName();
9321             } catch (RemoteException re) {
9322                 throw re.rethrowFromSystemServer();
9323             }
9324         }
9325         return null;
9326     }
9327 
9328     /**
9329      * @hide
9330      * @deprecated Use #ACTION_SET_PROFILE_OWNER
9331      * Sets the given component as an active admin and registers the package as the profile
9332      * owner for this user. The package must already be installed and there shouldn't be
9333      * an existing profile owner registered for this user. Also, this method must be called
9334      * before the user setup has been completed.
9335      * <p>
9336      * This method can only be called by system apps that hold MANAGE_USERS permission and
9337      * MANAGE_DEVICE_ADMINS permission.
9338      * @param admin The component to register as an active admin and profile owner.
9339      * @param ownerName The user-visible name of the entity that is managing this user.
9340      * @return whether the admin was successfully registered as the profile owner.
9341      * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
9342      *         the user has already been set up.
9343      */
9344     @Deprecated
9345     @SystemApi
9346     @RequiresPermission(MANAGE_DEVICE_ADMINS)
setActiveProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName)9347     public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
9348             throws IllegalArgumentException {
9349         throwIfParentInstance("setActiveProfileOwner");
9350         if (mService != null) {
9351             try {
9352                 final int myUserId = myUserId();
9353                 mService.setActiveAdmin(admin, false, myUserId);
9354                 return mService.setProfileOwner(admin, myUserId);
9355             } catch (RemoteException re) {
9356                 throw re.rethrowFromSystemServer();
9357             }
9358         }
9359         return false;
9360     }
9361 
9362     /**
9363      * Clears the active profile owner. The caller must be the profile owner of this user, otherwise
9364      * a SecurityException will be thrown. This method is not available to managed profile owners.
9365      * <p>
9366      * While some policies previously set by the profile owner will be cleared by this method, it is
9367      * a best-effort process and some other policies will still remain in place after the profile
9368      * owner is cleared.
9369      *
9370      * @param admin The component to remove as the profile owner.
9371      * @throws SecurityException if {@code admin} is not an active profile owner, or the method is
9372      * being called from a managed profile.
9373      *
9374      * @deprecated This method is expected to be used for testing purposes only. The profile owner
9375      * will lose control of the user and its data after calling it. In order to protect any
9376      * sensitive data that remains on this user, it is advised that the profile owner deletes it
9377      * instead of calling this method. See {@link #wipeData(int)}.
9378      */
9379     @Deprecated
clearProfileOwner(@onNull ComponentName admin)9380     public void clearProfileOwner(@NonNull ComponentName admin) {
9381         throwIfParentInstance("clearProfileOwner");
9382         if (mService != null) {
9383             try {
9384                 mService.clearProfileOwner(admin);
9385             } catch (RemoteException re) {
9386                 throw re.rethrowFromSystemServer();
9387             }
9388         }
9389     }
9390 
9391     /**
9392      * @hide
9393      * Checks whether the user was already setup.
9394      */
hasUserSetupCompleted()9395     public boolean hasUserSetupCompleted() {
9396         if (mService != null) {
9397             try {
9398                 return mService.hasUserSetupCompleted();
9399             } catch (RemoteException re) {
9400                 throw re.rethrowFromSystemServer();
9401             }
9402         }
9403         return true;
9404     }
9405 
9406     /**
9407      * @hide
9408      * Sets the given component as the profile owner of the given user profile. The package must
9409      * already be installed. There must not already be a profile owner for this user.
9410      * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
9411      * this method.
9412      * Calling this after the setup phase of the specified user has completed is allowed only if:
9413      * - the caller is SYSTEM_UID.
9414      * - or the caller is the shell uid, and there are no accounts on the specified user.
9415      * @param admin the component name to be registered as profile owner.
9416      * @param userHandle the userId to set the profile owner for.
9417      * @return whether the component was successfully registered as the profile owner.
9418      * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
9419      * preconditions mentioned are not met.
9420      */
setProfileOwner(@onNull ComponentName admin, int userHandle)9421     public boolean setProfileOwner(@NonNull ComponentName admin, int userHandle)
9422             throws IllegalArgumentException {
9423         if (mService != null) {
9424             try {
9425                 return mService.setProfileOwner(admin, userHandle);
9426             } catch (RemoteException re) {
9427                 throw re.rethrowFromSystemServer();
9428             }
9429         }
9430         return false;
9431     }
9432 
9433     /**
9434      * Sets the device owner information to be shown on the lock screen.
9435      * <p>
9436      * Device owner information set using this method overrides any owner information manually set
9437      * by the user and prevents the user from further changing it.
9438      * <p>
9439      * If the device owner information is {@code null} or empty then the device owner info is
9440      * cleared and the user owner info is shown on the lock screen if it is set.
9441      * <p>
9442      * If the device owner information contains only whitespaces then the message on the lock screen
9443      * will be blank and the user will not be allowed to change it.
9444      * <p>
9445      * If the device owner information needs to be localized, it is the responsibility of the
9446      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9447      * and set a new version of this string accordingly.
9448      * <p>
9449      * May be called by the device owner or the profile owner of an organization-owned device.
9450      *
9451      * @param admin The name of the admin component to check.
9452      * @param info Device owner information which will be displayed instead of the user owner info.
9453      * @throws SecurityException if {@code admin} is not a device owner.
9454      */
setDeviceOwnerLockScreenInfo(@onNull ComponentName admin, CharSequence info)9455     public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
9456         throwIfParentInstance("setDeviceOwnerLockScreenInfo");
9457         if (mService != null) {
9458             try {
9459                 mService.setDeviceOwnerLockScreenInfo(admin, info);
9460             } catch (RemoteException re) {
9461                 throw re.rethrowFromSystemServer();
9462             }
9463         }
9464     }
9465 
9466     /**
9467      * @return The device owner information. If it is not set returns {@code null}.
9468      */
getDeviceOwnerLockScreenInfo()9469     public CharSequence getDeviceOwnerLockScreenInfo() {
9470         throwIfParentInstance("getDeviceOwnerLockScreenInfo");
9471         if (mService != null) {
9472             try {
9473                 return mService.getDeviceOwnerLockScreenInfo();
9474             } catch (RemoteException re) {
9475                 throw re.rethrowFromSystemServer();
9476             }
9477         }
9478         return null;
9479     }
9480 
9481     /**
9482      * Called by device or profile owners to suspend packages for this user. This function can be
9483      * called by a device owner, profile owner, or by a delegate given the
9484      * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}.
9485      * <p>
9486      * A suspended package will not be able to start activities. Its notifications will be hidden,
9487      * it will not show up in recents, will not be able to show toasts or dialogs or ring the
9488      * device.
9489      * <p>
9490      * The package must already be installed. If the package is uninstalled while suspended the
9491      * package will no longer be suspended. The admin can block this by using
9492      * {@link #setUninstallBlocked}.
9493      *
9494      * <p>Some apps cannot be suspended, such as device admins, the active launcher, the required
9495      * package installer, the required package uninstaller, the required package verifier, the
9496      * default dialer, and the permission controller.
9497      *
9498      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
9499      *              caller is not a device admin.
9500      * @param packageNames The package names to suspend or unsuspend.
9501      * @param suspended If set to {@code true} than the packages will be suspended, if set to
9502      *            {@code false} the packages will be unsuspended.
9503      * @return an array of package names for which the suspended status is not set as requested in
9504      *         this method.
9505      * @throws SecurityException if {@code admin} is not a device or profile owner.
9506      * @see #setDelegatedScopes
9507      * @see #DELEGATION_PACKAGE_ACCESS
9508      */
9509     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PACKAGE_STATE, conditional = true)
9510     @NonNull
setPackagesSuspended(@ullable ComponentName admin, @NonNull String[] packageNames, boolean suspended)9511     public String[] setPackagesSuspended(@Nullable ComponentName admin,
9512             @NonNull String[] packageNames, boolean suspended) {
9513         throwIfParentInstance("setPackagesSuspended");
9514         if (mService != null) {
9515             try {
9516                 return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames,
9517                         suspended);
9518             } catch (RemoteException re) {
9519                 throw re.rethrowFromSystemServer();
9520             }
9521         }
9522         return packageNames;
9523     }
9524 
9525     /**
9526      * Determine if a package is suspended. This function can be called by a device owner, profile
9527      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
9528      * {@link #setDelegatedScopes} or by holders of the permission
9529      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PACKAGE_STATE}.
9530      *
9531      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
9532      *              caller is not a device admin.
9533      * @param packageName The name of the package to retrieve the suspended status of.
9534      * @return {@code true} if the package is suspended or {@code false} if the package is not
9535      *         suspended, could not be found or an error occurred.
9536      * @throws SecurityException if {@code admin} is not a device or profile owner or has not been
9537      * granted the permission
9538      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PACKAGE_STATE}.
9539      * @throws NameNotFoundException if the package could not be found.
9540      * @see #setDelegatedScopes
9541      * @see #DELEGATION_PACKAGE_ACCESS
9542      */
9543     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PACKAGE_STATE, conditional = true)
isPackageSuspended(@ullable ComponentName admin, String packageName)9544     public boolean isPackageSuspended(@Nullable ComponentName admin, String packageName)
9545             throws NameNotFoundException {
9546         throwIfParentInstance("isPackageSuspended");
9547         if (mService != null) {
9548             try {
9549                 return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName);
9550             } catch (RemoteException e) {
9551                 throw e.rethrowFromSystemServer();
9552             } catch (IllegalArgumentException ex) {
9553                 Log.e(TAG, "IllegalArgumentException checking isPackageSuspended", ex);
9554                 throw new NameNotFoundException(packageName);
9555             }
9556         }
9557         return false;
9558     }
9559 
9560     /**
9561      * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
9562      * be used. Only the profile owner can call this.
9563      *
9564      * @see #isProfileOwnerApp
9565      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9566      * @throws SecurityException if {@code admin} is not a profile owner.
9567      */
setProfileEnabled(@onNull ComponentName admin)9568     public void setProfileEnabled(@NonNull ComponentName admin) {
9569         throwIfParentInstance("setProfileEnabled");
9570         if (mService != null) {
9571             try {
9572                 mService.setProfileEnabled(admin);
9573             } catch (RemoteException e) {
9574                 throw e.rethrowFromSystemServer();
9575             }
9576         }
9577     }
9578 
9579     /**
9580      * Sets the name of the profile. In the device owner case it sets the name of the user which it
9581      * is called from. Only a profile owner or device owner can call this. If this is never called
9582      * by the profile or device owner, the name will be set to default values.
9583      *
9584      * @see #isProfileOwnerApp
9585      * @see #isDeviceOwnerApp
9586      * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
9587      * @param profileName The name of the profile. If the name is longer than 200 characters
9588      *                    it will be truncated.
9589      * @throws SecurityException if {@code admin} is not a device or profile owner.
9590      */
setProfileName(@onNull ComponentName admin, String profileName)9591     public void setProfileName(@NonNull ComponentName admin, String profileName) {
9592         throwIfParentInstance("setProfileName");
9593         if (mService != null) {
9594             try {
9595                 mService.setProfileName(admin, profileName);
9596             } catch (RemoteException e) {
9597                 throw e.rethrowFromSystemServer();
9598             }
9599         }
9600     }
9601 
9602     /**
9603      * Used to determine if a particular package is registered as the profile owner for the
9604      * user. A profile owner is a special device admin that has additional privileges
9605      * within the profile.
9606      *
9607      * @param packageName The package name of the app to compare with the registered profile owner.
9608      * @return Whether or not the package is registered as the profile owner.
9609      */
isProfileOwnerApp(String packageName)9610     public boolean isProfileOwnerApp(String packageName) {
9611         throwIfParentInstance("isProfileOwnerApp");
9612         if (mService != null) {
9613             try {
9614                 ComponentName profileOwner = mService.getProfileOwnerAsUser(myUserId());
9615                 return profileOwner != null
9616                         && profileOwner.getPackageName().equals(packageName);
9617             } catch (RemoteException re) {
9618                 throw re.rethrowFromSystemServer();
9619             }
9620         }
9621         return false;
9622     }
9623 
9624     /**
9625      * @hide
9626      * @return the packageName of the owner of the given user profile or {@code null} if no profile
9627      * owner has been set for that user.
9628      * @throws IllegalArgumentException if the userId is invalid.
9629      */
9630     @SystemApi
getProfileOwner()9631     public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
9632         throwIfParentInstance("getProfileOwner");
9633         return getProfileOwnerAsUser(mContext.getUserId());
9634     }
9635 
9636     /**
9637      * @see #getProfileOwner()
9638      * @hide
9639      */
9640     @RequiresPermission(value = android.Manifest.permission.INTERACT_ACROSS_USERS,
9641             conditional = true)
getProfileOwnerAsUser(@onNull UserHandle user)9642     public @Nullable ComponentName getProfileOwnerAsUser(@NonNull UserHandle user) {
9643         if (mService != null) {
9644             try {
9645                 return mService.getProfileOwnerAsUser(user.getIdentifier());
9646             } catch (RemoteException re) {
9647                 throw re.rethrowFromSystemServer();
9648             }
9649         }
9650         return null;
9651     }
9652 
9653     /**
9654      * @hide
9655      */
9656     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getProfileOwnerAsUser(final int userId)9657     public @Nullable ComponentName getProfileOwnerAsUser(final int userId) {
9658         if (mService != null) {
9659             try {
9660                 return mService.getProfileOwnerAsUser(userId);
9661             } catch (RemoteException re) {
9662                 throw re.rethrowFromSystemServer();
9663             }
9664         }
9665         return null;
9666     }
9667 
9668     private final IpcDataCache<UserHandle, ComponentName>
9669             mGetProfileOwnerOrDeviceOwnerSupervisionComponentCache =
9670             new IpcDataCache<>(sDpmCaches.child("getProfileOwnerOrDeviceOwnerSupervisionComponent"),
9671                     (arg) -> getService().getProfileOwnerOrDeviceOwnerSupervisionComponent(arg));
9672 
9673     /**
9674      * Returns the configured supervision app if it exists and is the device owner or policy owner.
9675      * @hide
9676      */
getProfileOwnerOrDeviceOwnerSupervisionComponent( @onNull UserHandle user)9677     public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent(
9678             @NonNull UserHandle user) {
9679         if (mService != null) {
9680             return mGetProfileOwnerOrDeviceOwnerSupervisionComponentCache.query(user);
9681         }
9682         return null;
9683     }
9684 
9685     /**
9686      * Checks if the specified component is the supervision component.
9687      * @hide
9688      */
isSupervisionComponent(@onNull ComponentName who)9689     public boolean isSupervisionComponent(@NonNull ComponentName who) {
9690         if (mService != null) {
9691             try {
9692                 return getService().isSupervisionComponent(who);
9693             } catch (RemoteException re) {
9694                 throw re.rethrowFromSystemServer();
9695             }
9696         }
9697         return false;
9698     }
9699 
9700     /**
9701      * @hide
9702      * @return the human readable name of the organisation associated with this DPM or {@code null}
9703      *         if one is not set.
9704      * @throws IllegalArgumentException if the userId is invalid.
9705      */
getProfileOwnerName()9706     public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
9707         if (mService != null) {
9708             try {
9709                 return mService.getProfileOwnerName(mContext.getUserId());
9710             } catch (RemoteException re) {
9711                 throw re.rethrowFromSystemServer();
9712             }
9713         }
9714         return null;
9715     }
9716 
9717     /**
9718      * @hide
9719      * @param userId The user for whom to fetch the profile owner name, if any.
9720      * @return the human readable name of the organisation associated with this profile owner or
9721      *         null if one is not set.
9722      * @throws IllegalArgumentException if the userId is invalid.
9723      */
9724     @SystemApi
9725     @RequiresPermission(anyOf = {
9726             android.Manifest.permission.MANAGE_USERS,
9727             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
9728     })
getProfileOwnerNameAsUser(int userId)9729     public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
9730         throwIfParentInstance("getProfileOwnerNameAsUser");
9731         if (mService != null) {
9732             try {
9733                 return mService.getProfileOwnerName(userId);
9734             } catch (RemoteException re) {
9735                 throw re.rethrowFromSystemServer();
9736             }
9737         }
9738         return null;
9739     }
9740 
9741     private final IpcDataCache<Void, Boolean> mIsOrganizationOwnedDeviceWithManagedProfileCache =
9742             new IpcDataCache(sDpmCaches.child("isOrganizationOwnedDeviceWithManagedProfile"),
9743                     (query) -> getService().isOrganizationOwnedDeviceWithManagedProfile());
9744 
9745     /**
9746      * Apps can use this method to find out if the device was provisioned as
9747      * organization-owend device with a managed profile.
9748      *
9749      * This, together with checking whether the device has a device owner (by calling
9750      * {@link #isDeviceOwnerApp}), could be used to learn whether the device is owned by an
9751      * organization or an individual:
9752      * If this method returns true OR {@link #isDeviceOwnerApp} returns true (for any package),
9753      * then the device is owned by an organization. Otherwise, it's owned by an individual.
9754      *
9755      * @return {@code true} if the device was provisioned as organization-owned device,
9756      * {@code false} otherwise.
9757      */
isOrganizationOwnedDeviceWithManagedProfile()9758     public boolean isOrganizationOwnedDeviceWithManagedProfile() {
9759         throwIfParentInstance("isOrganizationOwnedDeviceWithManagedProfile");
9760         if (mService != null) {
9761             return mIsOrganizationOwnedDeviceWithManagedProfileCache.query(null);
9762         }
9763         return false;
9764     }
9765 
9766     /**
9767      * Returns whether the specified package can read the device identifiers.
9768      *
9769      * @param packageName The package name of the app to check for device identifier access.
9770      * @param pid The process id of the package to be checked.
9771      * @param uid The uid of the package to be checked.
9772      * @return whether the package can read the device identifiers.
9773      *
9774      * @hide
9775      */
hasDeviceIdentifierAccess(@onNull String packageName, int pid, int uid)9776     public boolean hasDeviceIdentifierAccess(@NonNull String packageName, int pid, int uid) {
9777         throwIfParentInstance("hasDeviceIdentifierAccess");
9778         if (packageName == null) {
9779             return false;
9780         }
9781         if (mService != null) {
9782             try {
9783                 return mService.checkDeviceIdentifierAccess(packageName, pid, uid);
9784             } catch (RemoteException re) {
9785                 throw re.rethrowFromSystemServer();
9786             }
9787         }
9788         return false;
9789     }
9790 
9791     /**
9792      * Called by a profile owner or device owner or holder of the permission
9793      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}. to set a default activity
9794      * that the system selects to handle intents that match the given {@link IntentFilter}.
9795      * This activity will remain the default intent handler even if the set of potential event
9796      * handlers for the intent filter changes and if the intent preferences are reset.
9797      * <p>
9798      * Note that the caller should still declare the activity in the manifest, the API just sets
9799      * the activity to be the default one to handle the given intent filter.
9800      * <p>
9801      * The default disambiguation mechanism takes over if the activity is not installed (anymore).
9802      * When the activity is (re)installed, it is automatically reset as default intent handler for
9803      * the filter.
9804      * <p>
9805      * The calling device admin must be a profile owner or device owner. If it is not, a security
9806      * exception will be thrown.
9807      * <p>
9808      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the persistent preferred
9809      * activity policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
9810      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
9811      * successfully set or not. This callback will contain:
9812      * <ul>
9813      * <li> The policy identifier
9814      * {@link DevicePolicyIdentifiers#PERSISTENT_PREFERRED_ACTIVITY_POLICY}
9815      * <li> The additional policy params bundle, which contains
9816      * {@link PolicyUpdateReceiver#EXTRA_INTENT_FILTER} the intent filter the policy applies to
9817      * <li> The {@link TargetUser} that this policy relates to
9818      * <li> The {@link PolicyUpdateResult}, which will be
9819      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
9820      * reason the policy failed to be set
9821      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
9822      * </ul>
9823      * If there has been a change to the policy,
9824      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
9825      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
9826      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
9827      * will contain the reason why the policy changed.
9828      *
9829      * <p>NOTE: Performs disk I/O and shouldn't be called on the main thread.
9830      *
9831      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
9832      *        caller is not a device admin.
9833      * @param filter The IntentFilter for which a default handler is added.
9834      * @param activity The Activity that is added as default intent handler.
9835      * @throws SecurityException if {@code admin} is not a device or profile owner or holder of the
9836      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}.
9837      */
9838     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true)
9839     @SupportsCoexistence
addPersistentPreferredActivity(@ullable ComponentName admin, IntentFilter filter, @NonNull ComponentName activity)9840     public void addPersistentPreferredActivity(@Nullable ComponentName admin, IntentFilter filter,
9841             @NonNull ComponentName activity) {
9842         throwIfParentInstance("addPersistentPreferredActivity");
9843         if (mService != null) {
9844             try {
9845                 mService.addPersistentPreferredActivity(admin, mContext.getPackageName(), filter,
9846                         activity);
9847             } catch (RemoteException e) {
9848                 throw e.rethrowFromSystemServer();
9849             }
9850         }
9851     }
9852 
9853     /**
9854      * Called by a profile owner or device owner or holder of the
9855      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK} to remove all
9856      * persistent intent handler preferences associated with the given package that were set by
9857      * {@link #addPersistentPreferredActivity}.
9858      * <p>
9859      * The calling device admin must be a profile owner. If it is not, a security exception will be
9860      * thrown.
9861      * <p>
9862      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the persistent preferred
9863      * activity policy has been cleared, {@link PolicyUpdateReceiver#onPolicySetResult(Context,
9864      * String, Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy
9865      * was successfully cleared or not. This callback will contain:
9866      * <ul>
9867      * <li> The policy identifier
9868      * {@link DevicePolicyIdentifiers#PERSISTENT_PREFERRED_ACTIVITY_POLICY}
9869      * <li> The additional policy params bundle, which contains
9870      * {@link PolicyUpdateReceiver#EXTRA_INTENT_FILTER} the intent filter the policy applies to
9871      * <li> The {@link TargetUser} that this policy relates to
9872      * <li> The {@link PolicyUpdateResult}, which will be
9873      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully cleared or the
9874      * reason the policy failed to be cleared
9875      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
9876      * </ul>
9877      * If there has been a change to the policy,
9878      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
9879      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
9880      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
9881      * will contain the reason why the policy changed.
9882      *
9883      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
9884      *              caller is not a device admin.
9885      * @param packageName The name of the package for which preferences are removed.
9886      * @throws SecurityException if {@code admin} is not a device or profile owner or holder of the
9887      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}.
9888      */
9889     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true)
clearPackagePersistentPreferredActivities(@ullable ComponentName admin, String packageName)9890     public void clearPackagePersistentPreferredActivities(@Nullable ComponentName admin,
9891             String packageName) {
9892         throwIfParentInstance("clearPackagePersistentPreferredActivities");
9893         if (mService != null) {
9894             try {
9895                 mService.clearPackagePersistentPreferredActivities(
9896                         admin,
9897                         mContext.getPackageName(),
9898                         packageName);
9899             } catch (RemoteException e) {
9900                 throw e.rethrowFromSystemServer();
9901             }
9902         }
9903     }
9904 
9905     /**
9906      * Must be called by a device owner or a profile owner of an organization-owned managed profile
9907      * to set the default SMS application.
9908      * <p>
9909      * This method can be called on the {@link DevicePolicyManager} instance, returned by
9910      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
9911      * of an organization-owned managed profile and the package must be a pre-installed system
9912      * package. If called on the parent instance, then the default SMS application is set on the
9913      * personal profile.
9914      * <p>
9915      * Starting from Android {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the profile
9916      * owner of an organization-owned managed profile can also call this method directly (not on the
9917      * parent profile instance) to set the default SMS application in the work profile. This is only
9918      * meaningful when work profile telephony is enabled by {@link #setManagedSubscriptionsPolicy}.
9919      *
9920      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
9921      *              caller is not a device admin.
9922      * @param packageName The name of the package to set as the default SMS application.
9923      * @throws SecurityException        if {@code admin} is not a device or profile owner or if
9924      *                                  called on the parent profile and the {@code admin} is not a
9925      *                                  profile owner of an organization-owned managed profile.
9926      * @throws IllegalArgumentException if called on the parent profile and the package
9927      *                                  provided is not a pre-installed system package.
9928      * @throws IllegalStateException while trying to set default sms app on the profile and
9929      *                             {@link ManagedSubscriptionsPolicy#TYPE_ALL_MANAGED_SUBSCRIPTIONS}
9930      *                             policy is not set.
9931      */
9932     @RequiresPermission(value = MANAGE_DEVICE_POLICY_DEFAULT_SMS, conditional = true)
setDefaultSmsApplication(@ullable ComponentName admin, @NonNull String packageName)9933     public void setDefaultSmsApplication(@Nullable ComponentName admin,
9934             @NonNull String packageName) {
9935         if (mService != null) {
9936             try {
9937                 mService.setDefaultSmsApplication(admin, mContext.getPackageName(), packageName,
9938                         mParentInstance);
9939             } catch (RemoteException e) {
9940                 throw e.rethrowFromSystemServer();
9941             }
9942         }
9943     }
9944 
9945     /**
9946      * Must be called by a device owner or a profile owner of an organization-owned managed profile
9947      * to set the default dialer application for the calling user.
9948      * <p>
9949      * When the profile owner of an organization-owned managed profile calls this method, it sets
9950      * the default dialer application in the work profile. This is only meaningful when work profile
9951      * telephony is enabled by {@link #setManagedSubscriptionsPolicy}.
9952      * <p>
9953      * If the device does not support telephony ({@link PackageManager#FEATURE_TELEPHONY}), calling
9954      * this method will do nothing.
9955      *
9956      * @param packageName The name of the package to set as the default dialer application.
9957      * @throws SecurityException        if {@code admin} is not a device or profile owner or a
9958      *                                  profile owner of an organization-owned managed profile.
9959      * @throws IllegalArgumentException if the package cannot be set as the default dialer, for
9960      *                                  example if the package is not installed or does not expose
9961      *                                  the expected activities or services that a dialer app is
9962      *                                  required to have.
9963      */
setDefaultDialerApplication(@onNull String packageName)9964     public void setDefaultDialerApplication(@NonNull String packageName) {
9965         throwIfParentInstance("setDefaultDialerApplication");
9966         if (mService != null) {
9967             try {
9968                 mService.setDefaultDialerApplication(packageName);
9969             } catch (RemoteException e) {
9970                 throw e.rethrowFromSystemServer();
9971             }
9972         }
9973     }
9974 
9975     /**
9976      * Called by a profile owner or device owner to grant permission to a package to manage
9977      * application restrictions for the calling user via {@link #setApplicationRestrictions} and
9978      * {@link #getApplicationRestrictions}.
9979      * <p>
9980      * This permission is persistent until it is later cleared by calling this method with a
9981      * {@code null} value or uninstalling the managing package.
9982      * <p>
9983      * The supplied application restriction managing package must be installed when calling this
9984      * API, otherwise an {@link NameNotFoundException} will be thrown.
9985      *
9986      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9987      * @param packageName The package name which will be given access to application restrictions
9988      *            APIs. If {@code null} is given the current package will be cleared.
9989      * @throws SecurityException if {@code admin} is not a device or profile owner.
9990      * @throws NameNotFoundException if {@code packageName} is not found
9991      *
9992      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
9993      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
9994      */
9995     @Deprecated
setApplicationRestrictionsManagingPackage(@onNull ComponentName admin, @Nullable String packageName)9996     public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
9997             @Nullable String packageName) throws NameNotFoundException {
9998         throwIfParentInstance("setApplicationRestrictionsManagingPackage");
9999         if (mService != null) {
10000             try {
10001                 if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
10002                     throw new NameNotFoundException(packageName);
10003                 }
10004             } catch (RemoteException e) {
10005                 throw e.rethrowFromSystemServer();
10006             }
10007         }
10008     }
10009 
10010     /**
10011      * Called by a profile owner or device owner to retrieve the application restrictions managing
10012      * package for the current user, or {@code null} if none is set. If there are multiple
10013      * delegates this function will return one of them.
10014      *
10015      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10016      * @return The package name allowed to manage application restrictions on the current user, or
10017      *         {@code null} if none is set.
10018      * @throws SecurityException if {@code admin} is not a device or profile owner.
10019      *
10020      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
10021      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
10022      */
10023     @Deprecated
10024     @Nullable
getApplicationRestrictionsManagingPackage( @onNull ComponentName admin)10025     public String getApplicationRestrictionsManagingPackage(
10026             @NonNull ComponentName admin) {
10027         throwIfParentInstance("getApplicationRestrictionsManagingPackage");
10028         if (mService != null) {
10029             try {
10030                 return mService.getApplicationRestrictionsManagingPackage(admin);
10031             } catch (RemoteException e) {
10032                 throw e.rethrowFromSystemServer();
10033             }
10034         }
10035         return null;
10036     }
10037 
10038     /**
10039      * Called by any application to find out whether it has been granted permission via
10040      * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
10041      * for the calling user.
10042      *
10043      * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
10044      * that method.
10045      *
10046      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes}
10047      * instead.
10048      */
10049     @Deprecated
isCallerApplicationRestrictionsManagingPackage()10050     public boolean isCallerApplicationRestrictionsManagingPackage() {
10051         throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
10052         if (mService != null) {
10053             try {
10054                 return mService.isCallerApplicationRestrictionsManagingPackage(
10055                         mContext.getPackageName());
10056             } catch (RemoteException e) {
10057                 throw e.rethrowFromSystemServer();
10058             }
10059         }
10060         return false;
10061     }
10062 
10063     /**
10064      * Sets the application restrictions for a given target application running in the calling user.
10065      * <p>
10066      * The caller must be a profile or device owner on that user, or the package allowed to manage
10067      * application restrictions via {@link #setDelegatedScopes} with the
10068      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
10069      * <p>
10070      * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
10071      * <ul>
10072      * <li>{@code boolean}
10073      * <li>{@code int}
10074      * <li>{@code String} or {@code String[]}
10075      * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
10076      * </ul>
10077      * <p>
10078      * If the restrictions are not available yet, but may be applied in the near future, the caller
10079      * can notify the target application of that by adding
10080      * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
10081      * <p>
10082      * The application restrictions are only made visible to the target application via
10083      * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
10084      * owner, and the application restrictions managing package via
10085      * {@link #getApplicationRestrictions}.
10086      *
10087      * <p>Starting from Android Version {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE},
10088      * multiple admins can set app restrictions for the same application, the target application can
10089      * get the list of app restrictions set by each admin via
10090      * {@link android.content.RestrictionsManager#getApplicationRestrictionsPerAdmin}.
10091      *
10092      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
10093      *
10094      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10095      *            {@code null} if called by the application restrictions managing package.
10096      * @param packageName The name of the package to update restricted settings for.
10097      * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
10098      *            set of active restrictions.
10099      * @throws SecurityException if {@code admin} is not a device or profile owner.
10100      * @see #setDelegatedScopes
10101      * @see #DELEGATION_APP_RESTRICTIONS
10102      * @see UserManager#KEY_RESTRICTIONS_PENDING
10103      */
10104     @WorkerThread
setApplicationRestrictions(@ullable ComponentName admin, String packageName, Bundle settings)10105     public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
10106             Bundle settings) {
10107         throwIfParentInstance("setApplicationRestrictions");
10108         if (mService != null) {
10109             try {
10110                 mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName,
10111                         settings);
10112             } catch (RemoteException e) {
10113                 throw e.rethrowFromSystemServer();
10114             }
10115         }
10116     }
10117 
10118     /**
10119      * Sets a list of configuration features to enable for a trust agent component. This is meant to
10120      * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
10121      * agents but those enabled by this function call. If flag
10122      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
10123      * <p>
10124      * For any specific trust agent, whether it is disabled or not depends on the aggregated state
10125      * of each admin's {@link #KEYGUARD_DISABLE_TRUST_AGENTS} setting and its trust agent
10126      * configuration as set by this function call. In particular: if any admin sets
10127      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and does not additionally set any
10128      * trust agent configuration, the trust agent is disabled completely. Otherwise, the trust agent
10129      * will receive the list of configurations from all admins who set
10130      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and aggregate the configurations to determine its
10131      * behavior. The exact meaning of aggregation is trust-agent-specific.
10132      * <p>
10133      * A calling device admin must have requested
10134      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
10135      * if not, a security exception will be thrown.
10136      * <p>
10137      * This method can be called on the {@link DevicePolicyManager} instance returned by
10138      * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
10139      * the parent profile.
10140      * <p>
10141      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, calling
10142      * this method has no effect - no trust agent configuration will be set.
10143      *
10144      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
10145      *              caller is not a device admin
10146      * @param target Component name of the agent to be configured.
10147      * @param configuration Trust-agent-specific feature configuration bundle. Please consult
10148      *        documentation of the specific trust agent to determine the interpretation of this
10149      *        bundle.
10150      * @throws SecurityException if {@code admin} is not an active administrator or does not use
10151      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
10152      */
10153     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
10154     @RequiresPermission(value = MANAGE_DEVICE_POLICY_KEYGUARD, conditional = true)
setTrustAgentConfiguration(@ullable ComponentName admin, @NonNull ComponentName target, PersistableBundle configuration)10155     public void setTrustAgentConfiguration(@Nullable ComponentName admin,
10156             @NonNull ComponentName target, PersistableBundle configuration) {
10157         if (mService != null) {
10158             try {
10159                 mService.setTrustAgentConfiguration(
10160                         admin, mContext.getPackageName(), target, configuration, mParentInstance);
10161             } catch (RemoteException e) {
10162                 throw e.rethrowFromSystemServer();
10163             }
10164         }
10165     }
10166 
10167     /**
10168      * Gets configuration for the given trust agent based on aggregating all calls to
10169      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
10170      * all device admins.
10171      * <p>
10172      * This method can be called on the {@link DevicePolicyManager} instance returned by
10173      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
10174      * on the parent profile.
10175      * <p>
10176      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, null is
10177      * always returned.
10178      *
10179      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
10180      * this function returns a list of configurations for all admins that declare
10181      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
10182      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
10183      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
10184      * for this {@param agent} or calls it with a null configuration, null is returned.
10185      * @param agent Which component to get enabled features for.
10186      * @return configuration for the given trust agent.
10187      */
10188     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent)10189     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
10190             @Nullable ComponentName admin, @NonNull ComponentName agent) {
10191         return getTrustAgentConfiguration(admin, agent, myUserId());
10192     }
10193 
10194     /** @hide per-user version */
10195     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
10196     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent, int userHandle)10197     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
10198             @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
10199         if (mService != null) {
10200             try {
10201                 return mService.getTrustAgentConfiguration(admin, agent, userHandle,
10202                         mParentInstance);
10203             } catch (RemoteException e) {
10204                 throw e.rethrowFromSystemServer();
10205             }
10206         }
10207         return new ArrayList<PersistableBundle>(); // empty list
10208     }
10209 
10210     /**
10211      * Called by a profile owner of a managed profile to set whether caller-Id information from the
10212      * managed profile will be shown in the parent profile, for incoming calls.
10213      * <p>
10214      * The calling device admin must be a profile owner. If it is not, a security exception will be
10215      * thrown.
10216      * <p>
10217      * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, calling this function
10218      * is similar to calling {@link #setManagedProfileCallerIdAccessPolicy(PackagePolicy)}
10219      * with a {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST} policy type when {@code disabled} is
10220      * false or a {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST} policy type when
10221      * {@code disabled} is true.
10222      *
10223      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10224      * @param disabled If true caller-Id information in the managed profile is not displayed.
10225      * @throws SecurityException if {@code admin} is not a profile owner.
10226      * @deprecated starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, use
10227      * {@link #setManagedProfileCallerIdAccessPolicy(PackagePolicy)} instead
10228      */
10229     @Deprecated
setCrossProfileCallerIdDisabled(@onNull ComponentName admin, boolean disabled)10230     public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
10231         throwIfParentInstance("setCrossProfileCallerIdDisabled");
10232         if (mService != null) {
10233             try {
10234                 mService.setCrossProfileCallerIdDisabled(admin, disabled);
10235             } catch (RemoteException e) {
10236                 throw e.rethrowFromSystemServer();
10237             }
10238         }
10239     }
10240 
10241     /**
10242      * Called by a profile owner of a managed profile to determine whether or not caller-Id
10243      * information has been disabled.
10244      * <p>
10245      * The calling device admin must be a profile owner. If it is not, a security exception will be
10246      * thrown.
10247      * <p>
10248      * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE},
10249      * this will return true when
10250      * {@link #setManagedProfileCallerIdAccessPolicy(PackagePolicy)}
10251      * has been set with a non-null policy whose policy type is NOT
10252      * {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST}
10253      *
10254      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10255      * @throws SecurityException if {@code admin} is not a profile owner.
10256      * @deprecated starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, use
10257      * {@link #getManagedProfileCallerIdAccessPolicy()} instead
10258      */
10259     @Deprecated
getCrossProfileCallerIdDisabled(@onNull ComponentName admin)10260     public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
10261         throwIfParentInstance("getCrossProfileCallerIdDisabled");
10262         if (mService != null) {
10263             try {
10264                 return mService.getCrossProfileCallerIdDisabled(admin);
10265             } catch (RemoteException e) {
10266                 throw e.rethrowFromSystemServer();
10267             }
10268         }
10269         return false;
10270     }
10271 
10272     /**
10273      * Called by the system to determine whether or not caller-Id information has been disabled.
10274      * <p>
10275      * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE},
10276      * this will return true when
10277      * {@link #setManagedProfileCallerIdAccessPolicy(PackagePolicy)}
10278      * has been set with a non-null policy whose policy type is NOT
10279      * {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST}
10280      *
10281      * @param userHandle The user for whom to check the caller-id permission
10282      * @deprecated use {@link #hasManagedProfileCallerIdAccess(UserHandle, String)} and provide the
10283      * package name requesting access
10284      * @hide
10285      */
10286     @Deprecated
getCrossProfileCallerIdDisabled(UserHandle userHandle)10287     public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
10288         if (mService != null) {
10289             try {
10290                 return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
10291             } catch (RemoteException e) {
10292                 throw e.rethrowFromSystemServer();
10293             }
10294         }
10295         return false;
10296     }
10297 
10298     /**
10299      * Called by a device owner or profile owner of a managed profile to set the credential manager
10300      * policy.
10301      *
10302      * <p>Affects APIs exposed by {@link android.credentials.CredentialManager}.
10303      *
10304      * <p>A {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST} policy type will limit the credential
10305      * providers that the user can use to the list of packages in the policy.
10306      *
10307      * <p>A {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST_AND_SYSTEM} policy type
10308      * allows access from the OEM default credential providers and the allowlist of credential
10309      * providers.
10310      *
10311      * <p>A {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST} policy type will block the credential
10312      * providers listed in the policy from being used by the user.
10313      *
10314      * @param policy the policy to set, setting this value to {@code null} will allow all packages
10315      * @throws SecurityException if caller is not a device owner or profile owner of a
10316      * managed profile
10317      */
setCredentialManagerPolicy(@ullable PackagePolicy policy)10318     public void setCredentialManagerPolicy(@Nullable PackagePolicy policy) {
10319         throwIfParentInstance("setCredentialManagerPolicy");
10320         if (mService != null) {
10321             try {
10322                 mService.setCredentialManagerPolicy(policy);
10323             } catch (RemoteException e) {
10324                 throw e.rethrowFromSystemServer();
10325             }
10326         }
10327     }
10328 
10329     /**
10330      * Called by a device owner or profile owner of a managed profile to retrieve the credential
10331      * manager policy.
10332      *
10333      * @throws SecurityException if caller is not a device owner or profile owner of a
10334      * managed profile.
10335      * @return the current credential manager policy if null then this policy has not been
10336      * configured.
10337      */
10338     @UserHandleAware(
10339             enabledSinceTargetSdkVersion = UPSIDE_DOWN_CAKE,
10340             requiresPermissionIfNotCaller = INTERACT_ACROSS_USERS)
getCredentialManagerPolicy()10341     public @Nullable PackagePolicy getCredentialManagerPolicy() {
10342         throwIfParentInstance("getCredentialManagerPolicy");
10343         if (mService != null) {
10344             try {
10345                 return mService.getCredentialManagerPolicy(myUserId());
10346             } catch (RemoteException e) {
10347                 throw e.rethrowFromSystemServer();
10348             }
10349         }
10350         return null;
10351     }
10352 
10353     /**
10354      * Called by a profile owner of a managed profile to set the packages that are allowed to
10355      * lookup contacts in the managed profile based on caller id information.
10356      * <p>
10357      * For example, the policy determines if a dialer app in the parent profile resolving
10358      * an incoming call can search the caller id data, such as phone number,
10359      * of managed contacts and return managed contacts that match.
10360      * <p>
10361      * The calling device admin must be a profile owner of a managed profile.
10362      * If it is not, a {@link SecurityException} will be thrown.
10363      * <p>
10364      * A {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST_AND_SYSTEM} policy type
10365      * allows access from the OEM default packages for the Sms, Dialer and Contact roles,
10366      * in addition to the packages specified in {@link PackagePolicy#getPackageNames()}
10367      *
10368      * @param policy the policy to set, setting this value to {@code null} will allow
10369      *               all packages
10370      * @throws SecurityException if caller is not a profile owner of a managed profile
10371      */
setManagedProfileCallerIdAccessPolicy(@ullable PackagePolicy policy)10372     public void setManagedProfileCallerIdAccessPolicy(@Nullable PackagePolicy policy) {
10373         throwIfParentInstance("setManagedProfileCallerIdAccessPolicy");
10374         if (mService != null) {
10375             try {
10376                 mService.setManagedProfileCallerIdAccessPolicy(policy);
10377             } catch (RemoteException e) {
10378                 throw e.rethrowFromSystemServer();
10379             }
10380         }
10381     }
10382 
10383     /**
10384      * Called by a profile owner of a managed profile to retrieve the caller id policy.
10385      * <p>
10386      * The calling device admin must be a profile owner of a managed profile.
10387      * If it is not, a {@link SecurityException} will be thrown.
10388      *
10389      * @throws SecurityException if caller is not a profile owner of a managed profile.
10390      * @return the current caller id policy
10391      */
getManagedProfileCallerIdAccessPolicy()10392     public @Nullable PackagePolicy getManagedProfileCallerIdAccessPolicy() {
10393         throwIfParentInstance("getManagedProfileCallerIdAccessPolicy");
10394         if (mService != null) {
10395             try {
10396                 return mService.getManagedProfileCallerIdAccessPolicy();
10397             } catch (RemoteException e) {
10398                 throw e.rethrowFromSystemServer();
10399             }
10400         }
10401         return null;
10402     }
10403 
10404     /**
10405      * Determine whether the given package is allowed to query the requested user to
10406      * populate caller id information
10407      *
10408      * @param userHandle The user for whom to check the contacts search permission
10409      * @param packageName the name of the package requesting access
10410      * @return true if package should be granted access, false otherwise
10411      * @hide
10412      */
10413     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
hasManagedProfileCallerIdAccess(@onNull UserHandle userHandle, @NonNull String packageName)10414     public boolean hasManagedProfileCallerIdAccess(@NonNull UserHandle userHandle,
10415             @NonNull String packageName) {
10416         if (mService == null) {
10417             return true;
10418         }
10419         try {
10420             return mService.hasManagedProfileCallerIdAccess(userHandle.getIdentifier(),
10421                     packageName);
10422         } catch (RemoteException e) {
10423             throw e.rethrowFromSystemServer();
10424         }
10425     }
10426 
10427     /**
10428      * Called by a profile owner of a managed profile to set the packages that are allowed
10429      * access to the managed profile contacts from the parent user.
10430      * <p>
10431      * For example, the system will enforce the provided policy and determine
10432      * if contacts in the managed profile are shown when queried by an application
10433      * in the parent user.
10434      * <p>
10435      * The calling device admin must be a profile owner of a managed profile.
10436      * If it is not, a {@link SecurityException} will be thrown.
10437      * <p>
10438      * A {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST_AND_SYSTEM} policy type
10439      * allows access from the OEM default packages for the Sms, Dialer and Contact roles,
10440      * in addition to the packages specified in {@link PackagePolicy#getPackageNames()}
10441      *
10442      * @param policy the policy to set, setting this value to {@code null} will allow
10443      *               all packages
10444      * @throws SecurityException if caller is not a profile owner of a managed profile
10445      */
setManagedProfileContactsAccessPolicy(@ullable PackagePolicy policy)10446     public void setManagedProfileContactsAccessPolicy(@Nullable PackagePolicy policy) {
10447         throwIfParentInstance("setManagedProfileContactsAccessPolicy");
10448         if (mService != null) {
10449             try {
10450                 mService.setManagedProfileContactsAccessPolicy(policy);
10451             } catch (RemoteException e) {
10452                 throw e.rethrowFromSystemServer();
10453             }
10454         }
10455     }
10456 
10457     /**
10458      * Called by a profile owner of a managed profile to determine the current policy applied
10459      * to managed profile contacts.
10460      * <p>
10461      * The calling device admin must be a profile owner of a managed profile.
10462      * If it is not, a {@link SecurityException} will be thrown.
10463      *
10464      * @throws SecurityException if caller is not a profile owner of a managed profile.
10465      * @return the current contacts search policy
10466      */
getManagedProfileContactsAccessPolicy()10467     public @Nullable PackagePolicy getManagedProfileContactsAccessPolicy() {
10468         throwIfParentInstance("getManagedProfileContactsAccessPolicy");
10469         if (mService == null) {
10470             return null;
10471         }
10472         try {
10473             return mService.getManagedProfileContactsAccessPolicy();
10474         } catch (RemoteException e) {
10475             throw e.rethrowFromSystemServer();
10476         }
10477     }
10478 
10479     /**
10480      * Determine whether requesting package has ability to access contacts of the requested user
10481      *
10482      * @param userHandle The user for whom to check the contacts search permission
10483      * @param packageName packageName requesting access to contact search
10484      * @return true when package is allowed access, false otherwise
10485      * @hide
10486      */
10487     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
hasManagedProfileContactsAccess(@onNull UserHandle userHandle, @NonNull String packageName)10488     public boolean hasManagedProfileContactsAccess(@NonNull UserHandle userHandle,
10489             @NonNull String packageName) {
10490         if (mService != null) {
10491             try {
10492                 return mService.hasManagedProfileContactsAccess(userHandle.getIdentifier(),
10493                         packageName);
10494             } catch (RemoteException e) {
10495                 throw e.rethrowFromSystemServer();
10496             }
10497         }
10498         return false;
10499     }
10500 
10501     /**
10502      * Called by a profile owner of a managed profile to set whether contacts search from the
10503      * managed profile will be shown in the parent profile, for incoming calls.
10504      * <p>
10505      * The calling device admin must be a profile owner. If it is not, a security exception will be
10506      * thrown.
10507      *
10508      * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, calling this function
10509      * is similar to calling {@link #setManagedProfileContactsAccessPolicy(PackagePolicy)} with a
10510      * {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST} policy type when {@code disabled} is false
10511      * or a {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST} policy type when {@code disabled}
10512      * is true.
10513      *
10514      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10515      * @param disabled If true contacts search in the managed profile is not displayed.
10516      * @throws SecurityException if {@code admin} is not a profile owner.
10517      *
10518      * @deprecated From {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} use
10519      * {@link #setManagedProfileContactsAccessPolicy(PackagePolicy)}
10520      */
10521     @Deprecated
setCrossProfileContactsSearchDisabled(@onNull ComponentName admin, boolean disabled)10522     public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
10523             boolean disabled) {
10524         throwIfParentInstance("setCrossProfileContactsSearchDisabled");
10525         if (mService != null) {
10526             try {
10527                 mService.setCrossProfileContactsSearchDisabled(admin, disabled);
10528             } catch (RemoteException e) {
10529                 throw e.rethrowFromSystemServer();
10530             }
10531         }
10532     }
10533 
10534     /**
10535      * Called by a profile owner of a managed profile to determine whether or not contacts search
10536      * has been disabled.
10537      * <p>
10538      * The calling device admin must be a profile owner. If it is not, a security exception will be
10539      * thrown.
10540      * <p>
10541      * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE},
10542      * this will return true when
10543      * {@link #setManagedProfileContactsAccessPolicy(PackagePolicy)}
10544      * has been set with a non-null policy whose policy type is NOT
10545      * {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST}
10546      *
10547      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10548      * @throws SecurityException if {@code admin} is not a profile owner.
10549      * @deprecated From {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} use
10550      * {@link #getManagedProfileContactsAccessPolicy()}
10551      */
10552     @Deprecated
getCrossProfileContactsSearchDisabled(@onNull ComponentName admin)10553     public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
10554         throwIfParentInstance("getCrossProfileContactsSearchDisabled");
10555         if (mService != null) {
10556             try {
10557                 return mService.getCrossProfileContactsSearchDisabled(admin);
10558             } catch (RemoteException e) {
10559                 throw e.rethrowFromSystemServer();
10560             }
10561         }
10562         return false;
10563     }
10564 
10565     /**
10566      * Determine whether or not contacts search has been disabled.
10567      * <p>
10568      * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE},
10569      * this will return true when
10570      * {@link #setManagedProfileContactsAccessPolicy(PackagePolicy)}
10571      * has been set with a non-null policy whose policy type is NOT
10572      * {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST}
10573      * @param userHandle The user for whom to check the contacts search permission
10574      * @deprecated use {@link #hasManagedProfileContactsAccess(UserHandle, String)} and provide the
10575      * package name requesting access
10576      * @hide
10577      */
10578     @Deprecated
getCrossProfileContactsSearchDisabled(@onNull UserHandle userHandle)10579     public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
10580         if (mService != null) {
10581             try {
10582                 return mService
10583                         .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
10584             } catch (RemoteException e) {
10585                 throw e.rethrowFromSystemServer();
10586             }
10587         }
10588         return false;
10589     }
10590 
10591     /**
10592      * Start Quick Contact on the managed profile for the user, if the policy allows.
10593      *
10594      * @hide
10595      */
startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long directoryId, Intent originalIntent)10596     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
10597             boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
10598         if (mService != null) {
10599             try {
10600                 mService.startManagedQuickContact(actualLookupKey, actualContactId,
10601                         isContactIdIgnored, directoryId, originalIntent);
10602             } catch (RemoteException e) {
10603                 throw e.rethrowFromSystemServer();
10604             }
10605         }
10606     }
10607 
10608     /**
10609      * Start Quick Contact on the managed profile for the user, if the policy allows.
10610      * @hide
10611      */
startManagedQuickContact(String actualLookupKey, long actualContactId, Intent originalIntent)10612     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
10613             Intent originalIntent) {
10614         startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
10615                 originalIntent);
10616     }
10617 
10618     /**
10619      * Called by a profile owner of a managed profile to set whether bluetooth devices can access
10620      * enterprise contacts.
10621      * <p>
10622      * The calling device admin must be a profile owner. If it is not, a security exception will be
10623      * thrown.
10624      * <p>
10625      * This API works on managed profile only.
10626      *
10627      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10628      * @param disabled If true, bluetooth devices cannot access enterprise contacts.
10629      * @throws SecurityException if {@code admin} is not a profile owner.
10630      */
setBluetoothContactSharingDisabled(@onNull ComponentName admin, boolean disabled)10631     public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
10632         throwIfParentInstance("setBluetoothContactSharingDisabled");
10633         if (mService != null) {
10634             try {
10635                 mService.setBluetoothContactSharingDisabled(admin, disabled);
10636             } catch (RemoteException e) {
10637                 throw e.rethrowFromSystemServer();
10638             }
10639         }
10640     }
10641 
10642     /**
10643      * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
10644      * cannot access enterprise contacts.
10645      * <p>
10646      * The calling device admin must be a profile owner. If it is not, a security exception will be
10647      * thrown.
10648      * <p>
10649      * This API works on managed profile only.
10650      *
10651      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10652      * @throws SecurityException if {@code admin} is not a profile owner.
10653      */
getBluetoothContactSharingDisabled(@onNull ComponentName admin)10654     public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
10655         throwIfParentInstance("getBluetoothContactSharingDisabled");
10656         if (mService != null) {
10657             try {
10658                 return mService.getBluetoothContactSharingDisabled(admin);
10659             } catch (RemoteException e) {
10660                 throw e.rethrowFromSystemServer();
10661             }
10662         }
10663         return true;
10664     }
10665 
10666     /**
10667      * Determine whether or not Bluetooth devices cannot access contacts.
10668      * <p>
10669      * This API works on managed profile UserHandle only.
10670      *
10671      * @param userHandle The user for whom to check the caller-id permission
10672      * @hide
10673      */
10674     @SystemApi
10675     @RequiresPermission(permission.INTERACT_ACROSS_USERS)
getBluetoothContactSharingDisabled(@onNull UserHandle userHandle)10676     public boolean getBluetoothContactSharingDisabled(@NonNull UserHandle userHandle) {
10677         if (mService != null) {
10678             try {
10679                 return mService.getBluetoothContactSharingDisabledForUser(userHandle
10680                         .getIdentifier());
10681             } catch (RemoteException e) {
10682                 throw e.rethrowFromSystemServer();
10683             }
10684         }
10685         return true;
10686     }
10687 
10688     /**
10689      * Called by the profile owner of a managed profile so that some intents sent in the managed
10690      * profile can also be resolved in the parent, or vice versa. Only activity intents are
10691      * supported.
10692      *
10693      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10694      * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
10695      *            other profile
10696      * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
10697      *            {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
10698      * @throws SecurityException if {@code admin} is not a device or profile owner.
10699      */
10700     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PROFILE_INTERACTION, conditional = true)
addCrossProfileIntentFilter(@ullable ComponentName admin, IntentFilter filter, int flags)10701     public void addCrossProfileIntentFilter(@Nullable ComponentName admin, IntentFilter filter,
10702             int flags) {
10703         throwIfParentInstance("addCrossProfileIntentFilter");
10704         if (mService != null) {
10705             try {
10706                 mService.addCrossProfileIntentFilter(admin, mContext.getPackageName(), filter,
10707                         flags);
10708             } catch (RemoteException e) {
10709                 throw e.rethrowFromSystemServer();
10710             }
10711         }
10712     }
10713 
10714     /**
10715      * Called by a profile owner of a managed profile to remove the cross-profile intent filters
10716      * that go from the managed profile to the parent, or from the parent to the managed profile.
10717      * Only removes those that have been set by the profile owner.
10718      * <p>
10719      * <em>Note</em>: A list of default cross profile intent filters are set up by the system when
10720      * the profile is created, some of them ensure the proper functioning of the profile, while
10721      * others enable sharing of data from the parent to the managed profile for user convenience.
10722      * These default intent filters are not cleared when this API is called. If the default cross
10723      * profile data sharing is not desired, they can be disabled with
10724      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE}.
10725      *
10726      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10727      * @throws SecurityException if {@code admin} is not a profile owner.
10728      */
10729     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PROFILE_INTERACTION, conditional = true)
clearCrossProfileIntentFilters(@ullable ComponentName admin)10730     public void clearCrossProfileIntentFilters(@Nullable ComponentName admin) {
10731         throwIfParentInstance("clearCrossProfileIntentFilters");
10732         if (mService != null) {
10733             try {
10734                 mService.clearCrossProfileIntentFilters(admin, mContext.getPackageName());
10735             } catch (RemoteException e) {
10736                 throw e.rethrowFromSystemServer();
10737             }
10738         }
10739     }
10740 
10741     /**
10742      * Called by a profile or device owner to set the permitted
10743      * {@link android.accessibilityservice.AccessibilityService}. When set by
10744      * a device owner or profile owner the restriction applies to all profiles of the user the
10745      * device owner or profile owner is an admin for. By default, the user can use any accessibility
10746      * service. When zero or more packages have been added, accessibility services that are not in
10747      * the list and not part of the system can not be enabled by the user.
10748      * <p>
10749      * Calling with a {@code null} value for the list disables the restriction so that all services
10750      * can be used, calling with an empty list only allows the built-in system services. Any
10751      * non-system accessibility service that's currently enabled must be included in the list.
10752      * <p>
10753      * System accessibility services are always available to the user and this method can't
10754      * disable them.
10755      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10756      * @param packageNames List of accessibility service package names.
10757      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
10758      *         contain every enabled non-system accessibility service.
10759      * @throws SecurityException if {@code admin} is not a device or profile owner.
10760      */
setPermittedAccessibilityServices(@onNull ComponentName admin, List<String> packageNames)10761     public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
10762             List<String> packageNames) {
10763         throwIfParentInstance("setPermittedAccessibilityServices");
10764         if (mService != null) {
10765             try {
10766                 return mService.setPermittedAccessibilityServices(admin, packageNames);
10767             } catch (RemoteException e) {
10768                 throw e.rethrowFromSystemServer();
10769             }
10770         }
10771         return false;
10772     }
10773 
10774     /**
10775      * Returns the list of permitted accessibility services set by this device or profile owner.
10776      * <p>
10777      * An empty list means no accessibility services except system services are allowed.
10778      * {@code null} means all accessibility services are allowed.
10779      *
10780      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10781      * @return List of accessiblity service package names.
10782      * @throws SecurityException if {@code admin} is not a device or profile owner.
10783      */
getPermittedAccessibilityServices(@onNull ComponentName admin)10784     public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
10785         throwIfParentInstance("getPermittedAccessibilityServices");
10786         if (mService != null) {
10787             try {
10788                 return mService.getPermittedAccessibilityServices(admin);
10789             } catch (RemoteException e) {
10790                 throw e.rethrowFromSystemServer();
10791             }
10792         }
10793         return null;
10794     }
10795 
10796     /**
10797      * Called by the system to check if a specific accessibility service is disabled by admin.
10798      *
10799      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10800      * @param packageName Accessibility service package name that needs to be checked.
10801      * @param userHandle user id the admin is running as.
10802      * @return true if the accessibility service is permitted, otherwise false.
10803      *
10804      * @hide
10805      */
isAccessibilityServicePermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)10806     public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
10807             @NonNull String packageName, int userHandle) {
10808         if (mService != null) {
10809             try {
10810                 return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
10811                         userHandle);
10812             } catch (RemoteException e) {
10813                 throw e.rethrowFromSystemServer();
10814             }
10815         }
10816         return false;
10817     }
10818 
10819     /**
10820      * Returns the list of accessibility services permitted by the device or profiles
10821      * owners of this user.
10822      *
10823      * <p>{@code null} means all accessibility services are allowed, if a non-null list is returned
10824      * it will contain the intersection of the permitted lists for any device or profile
10825      * owners that apply to this user. It will also include any system accessibility services.
10826      *
10827      * @param userId which user to check for.
10828      * @return List of accessiblity service package names.
10829      * @hide
10830      */
10831      @SystemApi
10832      @RequiresPermission(anyOf = {
10833              android.Manifest.permission.MANAGE_USERS,
10834              android.Manifest.permission.QUERY_ADMIN_POLICY})
getPermittedAccessibilityServices(int userId)10835      public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
10836         throwIfParentInstance("getPermittedAccessibilityServices");
10837         if (mService != null) {
10838             try {
10839                 return mService.getPermittedAccessibilityServicesForUser(userId);
10840             } catch (RemoteException e) {
10841                 throw e.rethrowFromSystemServer();
10842             }
10843         }
10844         return null;
10845      }
10846 
10847     /**
10848      * Called by a profile or device owner or holder of the
10849      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_INPUT_METHODS} permission to set
10850      * the permitted input methods services for this user. By default, the user can use any input
10851      * method.
10852      * <p>
10853      * This method can be called on the {@link DevicePolicyManager} instance,
10854      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
10855      * a profile owner of an organization-owned device.
10856      * <p>
10857      * If called on the parent instance:
10858      * <ul>
10859      *    <li>The permitted input methods will be applied on the personal profile</li>
10860      *    <li>Can only permit all input methods (calling this method with a {@code null} package
10861      *    list) or only permit system input methods (calling this method with an empty package
10862      *    list). This is to prevent the caller from learning which packages are installed on
10863      *    the personal side</li>
10864      * </ul>
10865      * <p>
10866      * When zero or more packages have been added, input method that are not in the list and not
10867      * part of the system can not be enabled by the user. This method will fail if it is called for
10868      * a admin that is not for the foreground user or a profile of the foreground user. Any
10869      * non-system input method service that's currently enabled must be included in the list.
10870      * <p>
10871      * Calling with a null value for the list disables the restriction so that all input methods can
10872      * be used, calling with an empty list disables all but the system's own input methods.
10873      * <p>
10874      * System input methods are always available to the user - this method can't modify this.
10875      *
10876      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
10877      *              caller is not a device admin
10878      * @param packageNames List of input method package names.
10879      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
10880      *        contain every enabled non-system input method service.
10881      * @throws SecurityException if {@code admin} is not a device or profile owner and does not
10882      *                              hold the {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_INPUT_METHODS}
10883      *                              permission, or if called on the parent profile and the
10884      *                              {@code admin} is not a profile owner of an organization-owned
10885      *                              managed profile.
10886      * @throws IllegalArgumentException if called on the parent profile, the {@code admin} is a
10887      *                           profile owner of an organization-owned managed profile and the
10888      *                           list of permitted input method package names is not null or empty.
10889      */
10890     @SupportsCoexistence
10891     @RequiresPermission(value = MANAGE_DEVICE_POLICY_INPUT_METHODS, conditional = true)
setPermittedInputMethods( @ullable ComponentName admin, List<String> packageNames)10892     public boolean setPermittedInputMethods(
10893             @Nullable ComponentName admin, List<String> packageNames) {
10894         if (mService != null) {
10895             try {
10896                 return mService.setPermittedInputMethods(
10897                         admin, mContext.getPackageName(), packageNames, mParentInstance);
10898             } catch (RemoteException e) {
10899                 throw e.rethrowFromSystemServer();
10900             }
10901         }
10902         return false;
10903     }
10904 
10905 
10906     /**
10907      * Returns the list of permitted input methods set by this device or profile owner.
10908      * <p>
10909      * This method can be called on the {@link DevicePolicyManager} instance,
10910      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
10911      * a profile owner of an organization-owned managed profile. If called on the parent instance,
10912      * then the returned list of permitted input methods are those which are applied on the
10913      * personal profile.
10914      * <p>
10915      * An empty list means no input methods except system input methods are allowed. Null means all
10916      * input methods are allowed.
10917      *
10918      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
10919      *              caller is not a device admin
10920      * @return List of input method package names.
10921      * @throws SecurityException if {@code admin} is not a device, profile owner or if called on
10922      *                           the parent profile and the {@code admin} is not a profile owner
10923      *                           of an organization-owned managed profile.
10924      */
10925     @RequiresPermission(value = MANAGE_DEVICE_POLICY_INPUT_METHODS, conditional = true)
getPermittedInputMethods(@ullable ComponentName admin)10926     public @Nullable List<String> getPermittedInputMethods(@Nullable ComponentName admin) {
10927         if (mService != null) {
10928             try {
10929                 return mService.getPermittedInputMethods(admin, mContext.getPackageName(), mParentInstance);
10930             } catch (RemoteException e) {
10931                 throw e.rethrowFromSystemServer();
10932             }
10933         }
10934         return null;
10935     }
10936 
10937     /**
10938      * Called by the system to check if a specific input method is disabled by admin.
10939      * <p>
10940      * This method can be called on the {@link DevicePolicyManager} instance,
10941      * returned by {@link #getParentProfileInstance(ComponentName)}. If called on the parent
10942      * instance, this method will check whether the given input method is permitted on
10943      * the personal profile.
10944      *
10945      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10946      * @param packageName Input method package name that needs to be checked.
10947      * @param userHandle user id the admin is running as.
10948      * @return true if the input method is permitted, otherwise false.
10949      *
10950      * @hide
10951      */
isInputMethodPermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)10952     public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
10953             @NonNull String packageName, int userHandle) {
10954         if (mService != null) {
10955             try {
10956                 return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle,
10957                         mParentInstance);
10958             } catch (RemoteException e) {
10959                 throw e.rethrowFromSystemServer();
10960             }
10961         }
10962         return false;
10963     }
10964 
10965     /**
10966      * Returns the list of input methods permitted by the device or profiles owners.
10967      *
10968      * <p>On {@link android.os.Build.VERSION_CODES#Q} and later devices, this method returns the
10969      * result for the calling user.</p>
10970      *
10971      * <p>On Android P and prior devices, this method returns the result for the current user.</p>
10972      *
10973      * <p>Null means all input methods are allowed, if a non-null list is returned
10974      * it will contain the intersection of the permitted lists for any device or profile
10975      * owners that apply to this user. It will also include any system input methods.
10976      *
10977      * @return List of input method package names.
10978      * @hide
10979      *
10980      * @see #setPermittedAccessibilityServices(ComponentName, List)
10981      */
10982     @SystemApi
10983     @RequiresPermission(anyOf = {
10984             android.Manifest.permission.MANAGE_USERS,
10985             android.Manifest.permission.QUERY_ADMIN_POLICY})
getPermittedInputMethodsForCurrentUser()10986     public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
10987         throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
10988         if (mService != null) {
10989             try {
10990                 return mService.getPermittedInputMethodsAsUser(UserHandle.myUserId());
10991             } catch (RemoteException e) {
10992                 throw e.rethrowFromSystemServer();
10993             }
10994         }
10995         return null;
10996     }
10997 
10998     /**
10999      * Returns the list of input methods permitted.
11000      *
11001      * <p>{@code null} means all input methods are allowed, if a non-null list is returned
11002      * it will contain the intersection of the permitted lists for any device or profile
11003      * owners that apply to this user. It will also include any system input methods.
11004      *
11005      * @return List of input method package names.
11006      * @hide
11007      *
11008      * @see #setPermittedAccessibilityServices(ComponentName, List)
11009      */
11010     @UserHandleAware
11011     @RequiresPermission(allOf = {
11012             INTERACT_ACROSS_USERS_FULL,
11013             android.Manifest.permission.MANAGE_USERS
11014             }, conditional = true)
getPermittedInputMethods()11015     public @Nullable List<String> getPermittedInputMethods() {
11016         throwIfParentInstance("getPermittedInputMethods");
11017         if (mService != null) {
11018             try {
11019                 return mService.getPermittedInputMethodsAsUser(myUserId());
11020             } catch (RemoteException e) {
11021                 throw e.rethrowFromSystemServer();
11022             }
11023         }
11024         return null;
11025     }
11026 
11027     /**
11028      * Called by a profile owner of a managed profile to set the packages that are allowed to use
11029      * a {@link android.service.notification.NotificationListenerService} in the primary user to
11030      * see notifications from the managed profile. By default all packages are permitted by this
11031      * policy. When zero or more packages have been added, notification listeners installed on the
11032      * primary user that are not in the list and are not part of the system won't receive events
11033      * for managed profile notifications.
11034      * <p>
11035      * Calling with a {@code null} value for the list disables the restriction so that all
11036      * notification listener services be used. Calling with an empty list disables all but the
11037      * system's own notification listeners. System notification listener services are always
11038      * available to the user.
11039      * <p>
11040      * If a device or profile owner want to stop notification listeners in their user from seeing
11041      * that user's notifications they should prevent that service from running instead (e.g. via
11042      * {@link #setApplicationHidden(ComponentName, String, boolean)})
11043      *
11044      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11045      * @param packageList List of package names to allowlist
11046      * @return true if setting the restriction succeeded. It will fail if called outside a managed
11047      * profile
11048      * @throws SecurityException if {@code admin} is not a profile owner.
11049      *
11050      * @see android.service.notification.NotificationListenerService
11051      */
setPermittedCrossProfileNotificationListeners( @onNull ComponentName admin, @Nullable List<String> packageList)11052     public boolean setPermittedCrossProfileNotificationListeners(
11053             @NonNull ComponentName admin, @Nullable List<String> packageList) {
11054         throwIfParentInstance("setPermittedCrossProfileNotificationListeners");
11055         if (mService != null) {
11056             try {
11057                 return mService.setPermittedCrossProfileNotificationListeners(admin, packageList);
11058             } catch (RemoteException e) {
11059                 throw e.rethrowFromSystemServer();
11060             }
11061         }
11062         return false;
11063     }
11064 
11065     /**
11066      * Returns the list of packages installed on the primary user that allowed to use a
11067      * {@link android.service.notification.NotificationListenerService} to receive
11068      * notifications from this managed profile, as set by the profile owner.
11069      * <p>
11070      * An empty list means no notification listener services except system ones are allowed.
11071      * A {@code null} return value indicates that all notification listeners are allowed.
11072      */
getPermittedCrossProfileNotificationListeners( @onNull ComponentName admin)11073     public @Nullable List<String> getPermittedCrossProfileNotificationListeners(
11074             @NonNull ComponentName admin) {
11075         throwIfParentInstance("getPermittedCrossProfileNotificationListeners");
11076         if (mService != null) {
11077             try {
11078                 return mService.getPermittedCrossProfileNotificationListeners(admin);
11079             } catch (RemoteException e) {
11080                 throw e.rethrowFromSystemServer();
11081             }
11082         }
11083         return null;
11084     }
11085 
11086     /**
11087      * Returns true if {@code NotificationListenerServices} from the given package are allowed to
11088      * receive events for notifications from the given user id. Can only be called by the system uid
11089      *
11090      * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List)
11091      *
11092      * @hide
11093      */
isNotificationListenerServicePermitted( @onNull String packageName, @UserIdInt int userId)11094     public boolean isNotificationListenerServicePermitted(
11095             @NonNull String packageName, @UserIdInt int userId) {
11096         if (mService != null) {
11097             try {
11098                 return mService.isNotificationListenerServicePermitted(packageName, userId);
11099             } catch (RemoteException e) {
11100                 throw e.rethrowFromSystemServer();
11101             }
11102         }
11103         return true;
11104     }
11105 
11106     /**
11107      * Get the list of apps to keep around as APKs even if no user has currently installed it. This
11108      * function can be called by a device owner or by a delegate given the
11109      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
11110      * <p>
11111      * Please note that packages returned in this method are not automatically pre-cached.
11112      *
11113      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
11114      *            {@code null} if the caller is a keep uninstalled packages delegate.
11115      * @return List of package names to keep cached.
11116      * @see #setDelegatedScopes
11117      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
11118      */
getKeepUninstalledPackages(@ullable ComponentName admin)11119     public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) {
11120         throwIfParentInstance("getKeepUninstalledPackages");
11121         if (mService != null) {
11122             try {
11123                 return mService.getKeepUninstalledPackages(admin, mContext.getPackageName());
11124             } catch (RemoteException e) {
11125                 throw e.rethrowFromSystemServer();
11126             }
11127         }
11128         return null;
11129     }
11130 
11131     /**
11132      * Set a list of apps to keep around as APKs even if no user has currently installed it. This
11133      * function can be called by a device owner or by a delegate given the
11134      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
11135      *
11136      * <p>Please note that setting this policy does not imply that specified apps will be
11137      * automatically pre-cached.</p>
11138      *
11139      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
11140      *            {@code null} if the caller is a keep uninstalled packages delegate.
11141      * @param packageNames List of package names to keep cached.
11142      * @throws SecurityException if {@code admin} is not a device owner.
11143      * @see #setDelegatedScopes
11144      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
11145      */
setKeepUninstalledPackages(@ullable ComponentName admin, @NonNull List<String> packageNames)11146     public void setKeepUninstalledPackages(@Nullable ComponentName admin,
11147             @NonNull List<String> packageNames) {
11148         throwIfParentInstance("setKeepUninstalledPackages");
11149         if (mService != null) {
11150             try {
11151                 mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames);
11152             } catch (RemoteException e) {
11153                 throw e.rethrowFromSystemServer();
11154             }
11155         }
11156     }
11157 
11158     /**
11159       * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
11160       */
11161     public static final int SKIP_SETUP_WIZARD = 0x0001;
11162 
11163     /**
11164      * Flag used by {@link #createAndManageUser} to specify that the user should be created
11165      * ephemeral. Ephemeral users will be removed after switching to another user or rebooting the
11166      * device.
11167      */
11168     public static final int MAKE_USER_EPHEMERAL = 0x0002;
11169 
11170     /**
11171      * Flag used by {@link #createAndManageUser} to specify that the user should be created as a
11172      * demo user.
11173      * @hide
11174      */
11175     public static final int MAKE_USER_DEMO = 0x0004;
11176 
11177     /**
11178      * Flag used by {@link #createAndManageUser} to specify that the newly created user should skip
11179      * the disabling of system apps during provisioning.
11180      */
11181     public static final int LEAVE_ALL_SYSTEM_APPS_ENABLED = 0x0010;
11182 
11183     /**
11184      * @hide
11185      */
11186     @IntDef(flag = true, prefix = { "SKIP_", "MAKE_USER_", "START_", "LEAVE_" }, value = {
11187             SKIP_SETUP_WIZARD,
11188             MAKE_USER_EPHEMERAL,
11189             MAKE_USER_DEMO,
11190             LEAVE_ALL_SYSTEM_APPS_ENABLED
11191     })
11192     @Retention(RetentionPolicy.SOURCE)
11193     public @interface CreateAndManageUserFlags {}
11194 
11195     /**
11196      * Called by a device owner to create a user with the specified name and a given component of
11197      * the calling package as profile owner. The UserHandle returned by this method should not be
11198      * persisted as user handles are recycled as users are removed and created. If you need to
11199      * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
11200      * user will not be started in the background.
11201      * <p>
11202      * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
11203      * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
11204      * be registered as an active admin on the new user. The profile owner package will be installed
11205      * on the new user.
11206      * <p>
11207      * If the adminExtras are not null, they will be stored on the device until the user is started
11208      * for the first time. Then the extras will be passed to the admin when onEnable is called.
11209      * <p>From {@link android.os.Build.VERSION_CODES#P} onwards, if targeting
11210      * {@link android.os.Build.VERSION_CODES#P}, throws {@link UserOperationException} instead of
11211      * returning {@code null} on failure.
11212      *
11213      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11214      * @param name The user's name.
11215      * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
11216      *            same package as admin, otherwise no user is created and an
11217      *            IllegalArgumentException is thrown.
11218      * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
11219      *            user.
11220      * @param flags {@link #SKIP_SETUP_WIZARD}, {@link #MAKE_USER_EPHEMERAL} and
11221      *        {@link #LEAVE_ALL_SYSTEM_APPS_ENABLED} are supported.
11222      * @see UserHandle
11223      * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
11224      *         user could not be created.
11225      * @throws SecurityException if {@code admin} is not a device owner.
11226      * @throws UserOperationException if the user could not be created and the calling app is
11227      * targeting {@link android.os.Build.VERSION_CODES#P} and running on
11228      * {@link android.os.Build.VERSION_CODES#P}.
11229      */
createAndManageUser(@onNull ComponentName admin, @NonNull String name, @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras, @CreateAndManageUserFlags int flags)11230     public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
11231             @NonNull String name,
11232             @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
11233             @CreateAndManageUserFlags int flags) {
11234         throwIfParentInstance("createAndManageUser");
11235         try {
11236             return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
11237         } catch (ServiceSpecificException e) {
11238             throw new UserOperationException(e.getMessage(), e.errorCode);
11239         } catch (RemoteException re) {
11240             throw re.rethrowFromSystemServer();
11241         }
11242     }
11243 
11244     /**
11245      * Called by a device owner to remove a user/profile and all associated data. The primary user
11246      * can not be removed.
11247      *
11248      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11249      * @param userHandle the user to remove.
11250      * @return {@code true} if the user was removed, {@code false} otherwise.
11251      * @throws SecurityException if {@code admin} is not a device owner.
11252      */
removeUser(@onNull ComponentName admin, @NonNull UserHandle userHandle)11253     public boolean removeUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) {
11254         throwIfParentInstance("removeUser");
11255         try {
11256             return mService.removeUser(admin, userHandle);
11257         } catch (RemoteException re) {
11258             throw re.rethrowFromSystemServer();
11259         }
11260     }
11261 
11262     /**
11263      * Called by a device owner to switch the specified secondary user to the foreground.
11264      *
11265      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11266      * @param userHandle the user to switch to; null will switch to primary.
11267      * @return {@code true} if the switch was successful, {@code false} otherwise.
11268      * @throws SecurityException if {@code admin} is not a device owner.
11269      * @see Intent#ACTION_USER_FOREGROUND
11270      * @see #getSecondaryUsers(ComponentName)
11271      */
switchUser(@onNull ComponentName admin, @Nullable UserHandle userHandle)11272     public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
11273         throwIfParentInstance("switchUser");
11274         try {
11275             return mService.switchUser(admin, userHandle);
11276         } catch (RemoteException re) {
11277             throw re.rethrowFromSystemServer();
11278         }
11279     }
11280 
11281     /**
11282      * Called by a device owner to start the specified secondary user in background.
11283      *
11284      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11285      * @param userHandle the user to be started in background.
11286      * @return one of the following result codes:
11287      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
11288      * {@link UserManager#USER_OPERATION_SUCCESS},
11289      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
11290      * {@link UserManager#USER_OPERATION_ERROR_MAX_RUNNING_USERS},
11291      * @throws SecurityException if {@code admin} is not a device owner.
11292      * @see #getSecondaryUsers(ComponentName)
11293      */
startUserInBackground( @onNull ComponentName admin, @NonNull UserHandle userHandle)11294     public @UserOperationResult int startUserInBackground(
11295             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
11296         throwIfParentInstance("startUserInBackground");
11297         try {
11298             return mService.startUserInBackground(admin, userHandle);
11299         } catch (RemoteException re) {
11300             throw re.rethrowFromSystemServer();
11301         }
11302     }
11303 
11304     /**
11305      * Called by a device owner to stop the specified secondary user.
11306      *
11307      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11308      * @param userHandle the user to be stopped.
11309      * @return one of the following result codes:
11310      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
11311      * {@link UserManager#USER_OPERATION_SUCCESS},
11312      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
11313      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
11314      * @throws SecurityException if {@code admin} is not a device owner.
11315      * @see #getSecondaryUsers(ComponentName)
11316      */
stopUser( @onNull ComponentName admin, @NonNull UserHandle userHandle)11317     public @UserOperationResult int stopUser(
11318             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
11319         throwIfParentInstance("stopUser");
11320         try {
11321             return mService.stopUser(admin, userHandle);
11322         } catch (RemoteException re) {
11323             throw re.rethrowFromSystemServer();
11324         }
11325     }
11326 
11327     /**
11328      * Called by a profile owner of secondary user that is affiliated with the device to stop the
11329      * calling user and switch back to primary user (when the user was
11330      * {@link #switchUser(ComponentName, UserHandle)} switched to) or stop the user (when it was
11331      * {@link #startUserInBackground(ComponentName, UserHandle) started in background}.
11332      *
11333      * <p>Notice that on devices running with
11334      * {@link UserManager#isHeadlessSystemUserMode() headless system user mode}, there is no primary
11335      * user, so it switches back to the user that was in the foreground before the first call to
11336      * {@link #switchUser(ComponentName, UserHandle)} (or fails with
11337      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN} if that method was not called prior to this
11338      * call).
11339      *
11340      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11341      * @return one of the following result codes:
11342      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
11343      * {@link UserManager#USER_OPERATION_SUCCESS},
11344      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
11345      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
11346      * @throws SecurityException if {@code admin} is not a profile owner affiliated with the device.
11347      * @see #getSecondaryUsers(ComponentName)
11348      */
logoutUser(@onNull ComponentName admin)11349     public @UserOperationResult int logoutUser(@NonNull ComponentName admin) {
11350         throwIfParentInstance("logoutUser");
11351         try {
11352             return mService.logoutUser(admin);
11353         } catch (RemoteException re) {
11354             throw re.rethrowFromSystemServer();
11355         }
11356     }
11357 
11358     /**
11359      * Called by a profile owner of an organization-owned device to specify {@link
11360      * ManagedSubscriptionsPolicy}
11361      *
11362      * <p>Managed subscriptions policy controls how SIMs would be associated with the
11363      * managed profile. For example a policy of type
11364      * {@link ManagedSubscriptionsPolicy#TYPE_ALL_MANAGED_SUBSCRIPTIONS} assigns all
11365      * SIM-based subscriptions to the managed profile. In this case OEM default
11366      * dialer and messages app are automatically installed in the managed profile
11367      * and all incoming and outgoing calls and text messages are handled by them.
11368      * <p>This API can only be called during device setup.
11369      *
11370      * @param policy {@link ManagedSubscriptionsPolicy} policy, passing null for this resets the
11371      *               policy to be the default.
11372      * @throws SecurityException     if the caller is not a profile owner on an organization-owned
11373      *                               managed profile.
11374      * @throws IllegalStateException if called after the device setup has been completed.
11375      * @throws UnsupportedOperationException if managed subscriptions policy is not explicitly
11376      *         enabled by the device policy management role holder during device setup.
11377      * @see ManagedSubscriptionsPolicy
11378      */
setManagedSubscriptionsPolicy(@ullable ManagedSubscriptionsPolicy policy)11379     public void setManagedSubscriptionsPolicy(@Nullable ManagedSubscriptionsPolicy policy) {
11380         throwIfParentInstance("setManagedSubscriptionsPolicy");
11381         try {
11382             mService.setManagedSubscriptionsPolicy(policy);
11383         } catch (RemoteException re) {
11384             throw re.rethrowFromSystemServer();
11385         }
11386     }
11387 
11388     /**
11389      * Returns the current {@link ManagedSubscriptionsPolicy}.
11390      * If the policy has not been set, it will return a default policy of Type {@link
11391      * ManagedSubscriptionsPolicy#TYPE_ALL_PERSONAL_SUBSCRIPTIONS}.
11392      *
11393      * @see #setManagedSubscriptionsPolicy(ManagedSubscriptionsPolicy)
11394      */
11395     @NonNull
getManagedSubscriptionsPolicy()11396     public ManagedSubscriptionsPolicy getManagedSubscriptionsPolicy() {
11397         throwIfParentInstance("getManagedSubscriptionsPolicy");
11398         try {
11399             return mService.getManagedSubscriptionsPolicy();
11400         } catch (RemoteException re) {
11401             throw re.rethrowFromSystemServer();
11402         }
11403     }
11404 
11405     /**
11406      * Similar to {@link #logoutUser(ComponentName)}, except:
11407      *
11408      * <ul>
11409      *   <li>Called by system (like Settings), not admin.
11410      *   <li>It logs out the current user, not the caller.
11411      * </ul>
11412      *
11413      * @hide
11414      */
11415     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
11416             android.Manifest.permission.INTERACT_ACROSS_USERS})
11417     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
logoutUser()11418     public @UserOperationResult int logoutUser() {
11419         // TODO(b/214336184): add CTS test
11420         try {
11421             return mService.logoutUserInternal();
11422         } catch (RemoteException re) {
11423             throw re.rethrowFromSystemServer();
11424         }
11425     }
11426 
11427     /**
11428      * Gets the user a {@link #logoutUser(ComponentName)} call would switch to,
11429      * or {@code null} if the current user is not in a session (i.e., if it was not
11430      * {@link #switchUser(ComponentName, UserHandle) switched} or
11431      * {@link #startUserInBackground(ComponentName, UserHandle) started in background} by the
11432      * device admin.
11433      *
11434      * @hide
11435      */
11436     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
11437             android.Manifest.permission.INTERACT_ACROSS_USERS})
11438     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
getLogoutUser()11439     public @Nullable UserHandle getLogoutUser() {
11440         // TODO(b/214336184): add CTS test
11441         try {
11442             int userId = mService.getLogoutUserId();
11443             return userId == UserHandle.USER_NULL ? null : UserHandle.of(userId);
11444         } catch (RemoteException re) {
11445             throw re.rethrowFromSystemServer();
11446         }
11447     }
11448 
11449     /**
11450      * Called by a device owner to list all secondary users on the device. Managed profiles are not
11451      * considered as secondary users.
11452      * <p> Used for various user management APIs, including {@link #switchUser}, {@link #removeUser}
11453      * and {@link #stopUser}.
11454      *
11455      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11456      * @return list of other {@link UserHandle}s on the device.
11457      * @throws SecurityException if {@code admin} is not a device owner.
11458      * @see #removeUser(ComponentName, UserHandle)
11459      * @see #switchUser(ComponentName, UserHandle)
11460      * @see #startUserInBackground(ComponentName, UserHandle)
11461      * @see #stopUser(ComponentName, UserHandle)
11462      */
getSecondaryUsers(@onNull ComponentName admin)11463     public List<UserHandle> getSecondaryUsers(@NonNull ComponentName admin) {
11464         throwIfParentInstance("getSecondaryUsers");
11465         try {
11466             return mService.getSecondaryUsers(admin);
11467         } catch (RemoteException re) {
11468             throw re.rethrowFromSystemServer();
11469         }
11470     }
11471 
11472     /**
11473      * Checks if the profile owner is running in an ephemeral user.
11474      *
11475      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11476      * @return whether the profile owner is running in an ephemeral user.
11477      */
isEphemeralUser(@onNull ComponentName admin)11478     public boolean isEphemeralUser(@NonNull ComponentName admin) {
11479         throwIfParentInstance("isEphemeralUser");
11480         try {
11481             return mService.isEphemeralUser(admin);
11482         } catch (RemoteException re) {
11483             throw re.rethrowFromSystemServer();
11484         }
11485     }
11486 
11487     /**
11488      * Retrieves the application restrictions for a given target application running in the calling
11489      * user.
11490      * <p>
11491      * The caller must be a profile or device owner on that user, or the package allowed to manage
11492      * application restrictions via {@link #setDelegatedScopes} with the
11493      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
11494      *
11495      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
11496      *
11497      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
11498      *            {@code null} if called by the application restrictions managing package.
11499      * @param packageName The name of the package to fetch restricted settings of.
11500      * @return {@link Bundle} of settings corresponding to what was set last time
11501      *         {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
11502      *         {@link Bundle} if no restrictions have been set.
11503      * @throws SecurityException if {@code admin} is not a device or profile owner.
11504      * @see #setDelegatedScopes
11505      * @see #DELEGATION_APP_RESTRICTIONS
11506      */
11507     @WorkerThread
getApplicationRestrictions( @ullable ComponentName admin, String packageName)11508     public @NonNull Bundle getApplicationRestrictions(
11509             @Nullable ComponentName admin, String packageName) {
11510         throwIfParentInstance("getApplicationRestrictions");
11511         if (mService != null) {
11512             try {
11513                 return mService.getApplicationRestrictions(admin, mContext.getPackageName(),
11514                         packageName);
11515             } catch (RemoteException e) {
11516                 throw e.rethrowFromSystemServer();
11517             }
11518         }
11519         return null;
11520     }
11521 
11522     /**
11523      * Called by a profile owner, device owner or a holder of any permission that is associated with
11524      * a user restriction to set a user restriction specified by the key.
11525      * <p>
11526      * The calling device admin must be a profile owner, device owner or holder of any permission
11527      * that is associated with a user restriction; if it is not, a security
11528      * exception will be thrown.
11529      * <p>
11530      * The profile owner of an organization-owned managed profile may invoke this method on
11531      * the {@link DevicePolicyManager} instance it obtained from
11532      * {@link #getParentProfileInstance(ComponentName)}, for enforcing device-wide restrictions.
11533      * <p>
11534      * See the constants in {@link android.os.UserManager} for the list of restrictions that can
11535      * be enforced device-wide. These constants will also state in their documentation which
11536      * permission is required to manage the restriction using this API.
11537      *
11538      * <p>For callers targeting Android {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or
11539      * above, calling this API will result in applying the restriction locally on the calling user,
11540      * or locally on the parent profile if called from the
11541      * {@link DevicePolicyManager} instance obtained from
11542      * {@link #getParentProfileInstance(ComponentName)}. To set a restriction globally, call
11543      * {@link #addUserRestrictionGlobally} instead.
11544      *
11545      * <p>
11546      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the user restriction
11547      * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
11548      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
11549      * successfully set or not. This callback will contain:
11550      * <ul>
11551      * <li> The policy identifier returned from
11552      * {@link DevicePolicyIdentifiers#getIdentifierForUserRestriction(String)}
11553      * <li> The {@link TargetUser} that this policy relates to
11554      * <li> The {@link PolicyUpdateResult}, which will be
11555      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
11556      * reason the policy failed to be set
11557      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
11558      * </ul>
11559      * If there has been a change to the policy,
11560      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
11561      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
11562      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
11563      * will contain the reason why the policy changed.
11564      *
11565      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11566      * @param key   The key of the restriction.
11567      * @throws SecurityException if {@code admin} is not a device or profile owner and if the caller
11568      * has not been granted the permission to set the given user restriction.
11569      */
addUserRestriction(@onNull ComponentName admin, @UserManager.UserRestrictionKey String key)11570     public void addUserRestriction(@NonNull ComponentName admin,
11571             @UserManager.UserRestrictionKey String key) {
11572         if (mService != null) {
11573             try {
11574                 mService.setUserRestriction(
11575                         admin, mContext.getPackageName(), key, true, mParentInstance);
11576             } catch (RemoteException e) {
11577                 throw e.rethrowFromSystemServer();
11578             }
11579         }
11580     }
11581 
11582     /**
11583      * Called by a profile owner, device owner or a holder of any permission that is associated with
11584      *  a user restriction to set a user restriction specified by the provided {@code key} globally
11585      *  on all users. To clear the restriction use {@link #clearUserRestriction}.
11586      *
11587      * <p>For a given user, a restriction will be set if it was applied globally or locally by any
11588      * admin.
11589      *
11590      * <p> The calling device admin must be a profile owner, device owner or or a holder of any
11591      * permission that is associated with a user restriction; if it is not, a security
11592      * exception will be thrown.
11593      *
11594      * <p> See the constants in {@link android.os.UserManager} for the list of restrictions that can
11595      * be enforced device-wide. These constants will also state in their documentation which
11596      * permission is required to manage the restriction using this API.
11597      * <p>
11598      * After the user restriction policy has been set,
11599      * {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, Bundle, TargetUser,
11600      * PolicyUpdateResult)} will notify the admin on whether the policy was successfully set or not.
11601      * This callback will contain:
11602      * <ul>
11603      * <li> The policy identifier returned from
11604      * {@link DevicePolicyIdentifiers#getIdentifierForUserRestriction(String)}
11605      * <li> The {@link TargetUser} that this policy relates to
11606      * <li> The {@link PolicyUpdateResult}, which will be
11607      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
11608      * reason the policy failed to be set
11609      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
11610      * </ul>
11611      * If there has been a change to the policy,
11612      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
11613      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
11614      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
11615      * will contain the reason why the policy changed.
11616      *
11617      * @param key The key of the restriction.
11618      * @throws SecurityException if {@code admin} is not a device or profile owner and if the
11619      * caller has not been granted the permission to set the given user restriction.
11620      * @throws IllegalStateException if caller is not targeting Android
11621      * {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or above.
11622      */
addUserRestrictionGlobally(@onNull @serManager.UserRestrictionKey String key)11623     public void addUserRestrictionGlobally(@NonNull @UserManager.UserRestrictionKey String key) {
11624         throwIfParentInstance("addUserRestrictionGlobally");
11625         if (mService != null) {
11626             try {
11627                 mService.setUserRestrictionGlobally(mContext.getPackageName(), key);
11628             } catch (RemoteException e) {
11629                 throw e.rethrowFromSystemServer();
11630             }
11631         }
11632     }
11633 
11634     /**
11635      * Called by a profile owner, device owner or a holder of any permission that is associated with
11636      * a user restriction to clear a user restriction specified by the key.
11637      * <p>
11638      * The calling device admin must be a profile or device owner; if it is not, a security
11639      * exception will be thrown.
11640      * <p>
11641      * The profile owner of an organization-owned managed profile may invoke this method on
11642      * the {@link DevicePolicyManager} instance it obtained from
11643      * {@link #getParentProfileInstance(ComponentName)}, for clearing device-wide restrictions.
11644      * <p>
11645      * See the constants in {@link android.os.UserManager} for the list of restrictions. These
11646      * constants state in their documentation which permission is required to manage the restriction
11647      * using this API.
11648      *
11649      * <p>For callers targeting Android {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or
11650      * above, calling this API will result in clearing any local and global restriction with the
11651      * specified key that was previously set by the caller.
11652      *
11653      * <p>
11654      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the user restriction
11655      * policy has been cleared, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
11656      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
11657      * successfully cleared or not. This callback will contain:
11658      * <ul>
11659      * <li> The policy identifier returned from
11660      * {@link DevicePolicyIdentifiers#getIdentifierForUserRestriction(String)}
11661      * <li> The {@link TargetUser} that this policy relates to
11662      * <li> The {@link PolicyUpdateResult}, which will be
11663      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully cleared or the
11664      * reason the policy failed to be cleared
11665      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
11666      * </ul>
11667      * If there has been a change to the policy,
11668      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
11669      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
11670      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
11671      * will contain the reason why the policy changed.
11672      *
11673      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11674      * @param key   The key of the restriction.
11675      * @throws SecurityException if {@code admin} is not a device or profile owner  and if the
11676      *  caller has not been granted the permission to set the given user restriction.
11677      */
clearUserRestriction(@onNull ComponentName admin, @UserManager.UserRestrictionKey String key)11678     public void clearUserRestriction(@NonNull ComponentName admin,
11679             @UserManager.UserRestrictionKey String key) {
11680         if (mService != null) {
11681             try {
11682                 mService.setUserRestriction(
11683                         admin, mContext.getPackageName(), key, false, mParentInstance);
11684             } catch (RemoteException e) {
11685                 throw e.rethrowFromSystemServer();
11686             }
11687         }
11688     }
11689 
11690     /**
11691      * Called by an admin to get user restrictions set by themselves with
11692      * {@link #addUserRestriction(ComponentName, String)}.
11693      * <p>
11694      * The target user may have more restrictions set by the system or other admin.
11695      * To get all the user restrictions currently set, use
11696      * {@link UserManager#getUserRestrictions()}.
11697      * <p>
11698      * The profile owner of an organization-owned managed profile may invoke this method on
11699      * the {@link DevicePolicyManager} instance it obtained from
11700      * {@link #getParentProfileInstance(ComponentName)}, for retrieving device-wide restrictions
11701      * it previously set with {@link #addUserRestriction(ComponentName, String)}.
11702      *
11703      * <p>For callers targeting Android {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or
11704      * above, this API will return the local restrictions set on the calling user, or on the parent
11705      * profile if called from the {@link DevicePolicyManager} instance obtained from
11706      * {@link #getParentProfileInstance(ComponentName)}. To get global restrictions set by admin,
11707      * call {@link #getUserRestrictionsGlobally()} instead.
11708      *
11709      * <p>Note that this is different that the returned restrictions for callers targeting pre
11710      * Android {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, were this API returns
11711      * all local/global restrictions set by the admin on the calling user using
11712      * {@link #addUserRestriction(ComponentName, String)} or the parent user if called on the
11713      * {@link DevicePolicyManager} instance it obtained from {@link #getParentProfileInstance}.
11714      *
11715      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11716      * @return a {@link Bundle} whose keys are the user restrictions, and the values a
11717      * {@code boolean} indicating whether the restriction is set.
11718      * @throws SecurityException if {@code admin} is not a device or profile owner.
11719      */
getUserRestrictions(@onNull ComponentName admin)11720     public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
11721         Bundle ret = null;
11722         if (mService != null) {
11723             try {
11724                 ret = mService.getUserRestrictions(
11725                         admin, mContext.getPackageName(), mParentInstance);
11726             } catch (RemoteException e) {
11727                 throw e.rethrowFromSystemServer();
11728             }
11729         }
11730         return ret == null ? new Bundle() : ret;
11731     }
11732 
11733     /**
11734      * Called by a profile or device owner to get global user restrictions set with
11735      * {@link #addUserRestrictionGlobally(String)}.
11736      * <p>
11737      * To get all the user restrictions currently set for a certain user, use
11738      * {@link UserManager#getUserRestrictions()}.
11739      * @return a {@link Bundle} whose keys are the user restrictions, and the values a
11740      * {@code boolean} indicating whether the restriction is set.
11741      * @throws SecurityException if {@code admin} is not a device or profile owner.
11742      * @throws IllegalStateException if caller is not targeting Android
11743      * {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or above.
11744      */
getUserRestrictionsGlobally()11745     public @NonNull Bundle getUserRestrictionsGlobally() {
11746         throwIfParentInstance("createAdminSupportIntent");
11747         Bundle ret = null;
11748         if (mService != null) {
11749             try {
11750                 ret = mService.getUserRestrictionsGlobally(mContext.getPackageName());
11751             } catch (RemoteException e) {
11752                 throw e.rethrowFromSystemServer();
11753             }
11754         }
11755         return ret == null ? new Bundle() : ret;
11756     }
11757 
11758     /**
11759      * Called by any app to display a support dialog when a feature was disabled by an admin.
11760      * This returns an intent that can be used with {@link Context#startActivity(Intent)} to
11761      * display the dialog. It will tell the user that the feature indicated by {@code restriction}
11762      * was disabled by an admin, and include a link for more information. The default content of
11763      * the dialog can be changed by the restricting admin via
11764      * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not
11765      * set (i.e. the feature is available), then the return value will be {@code null}.
11766      * @param restriction Indicates for which feature the dialog should be displayed. Can be a
11767      *            user restriction from {@link UserManager}, e.g.
11768      *            {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants
11769      *            {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
11770      * @return Intent An intent to be used to start the dialog-activity if the restriction is
11771      *            set by an admin, or null if the restriction does not exist or no admin set it.
11772      */
createAdminSupportIntent(@onNull String restriction)11773     public Intent createAdminSupportIntent(@NonNull String restriction) {
11774         throwIfParentInstance("createAdminSupportIntent");
11775         Intent result = null;
11776         if (mService != null) {
11777             try {
11778                 result = mService.createAdminSupportIntent(restriction);
11779                 if (result != null) {
11780                     result.prepareToEnterProcess(LOCAL_FLAG_FROM_SYSTEM,
11781                             mContext.getAttributionSource());
11782                 }
11783             } catch (RemoteException e) {
11784                 throw e.rethrowFromSystemServer();
11785             }
11786         }
11787         return result;
11788     }
11789 
11790     /**
11791      * @param userId      The user for whom to retrieve information.
11792      * @param restriction The restriction enforced by admin. It could be any user restriction or
11793      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and
11794      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}.
11795      * @return Details of admin and user which enforced the restriction for the userId. If
11796      * restriction is null, profile owner for the user or device owner info is returned.
11797      * @hide
11798      */
getEnforcingAdminAndUserDetails(int userId, @Nullable String restriction)11799     public @Nullable Bundle getEnforcingAdminAndUserDetails(int userId,
11800             @Nullable String restriction) {
11801         if (mService != null) {
11802             try {
11803                 return mService.getEnforcingAdminAndUserDetails(userId, restriction);
11804             } catch (RemoteException e) {
11805                 throw e.rethrowFromSystemServer();
11806             }
11807         }
11808         return null;
11809     }
11810 
11811     /**
11812      * Returns the list of {@link EnforcingAdmin}s who have set this restriction.
11813      *
11814      * <p>Note that for {@link #POLICY_SUSPEND_PACKAGES} it returns the PO or DO to keep the
11815      * behavior the same as before the bug fix for b/192245204.
11816      *
11817      * <p>This API is only callable by the system UID
11818      *
11819      * @param userId      The user for whom to retrieve the information.
11820      * @param restriction The restriction enforced by admins. It could be any user restriction or
11821      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and
11822      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}.
11823      *
11824      * @hide
11825      */
getEnforcingAdminsForRestriction(int userId, @NonNull String restriction)11826     public @NonNull Set<EnforcingAdmin> getEnforcingAdminsForRestriction(int userId,
11827             @NonNull String restriction) {
11828         if (mService != null) {
11829             try {
11830                 return new HashSet<>(mService.getEnforcingAdminsForRestriction(
11831                         userId, restriction));
11832             } catch (RemoteException e) {
11833                 throw e.rethrowFromSystemServer();
11834             }
11835         }
11836         return null;
11837     }
11838 
11839     /**
11840      * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and
11841      * actual package file remain. This function can be called by a device owner, profile owner, or
11842      * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
11843      * {@link #setDelegatedScopes}.
11844      * <p>
11845      * This method can be called on the {@link DevicePolicyManager} instance, returned by
11846      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
11847      * of an organization-owned managed profile and the package must be a system package. If called
11848      * on the parent instance, then the package is hidden or unhidden in the personal profile.
11849      * <p>
11850      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the application hidden
11851      * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
11852      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
11853      * successfully set or not. This callback will contain:
11854      * <ul>
11855      * <li> The policy identifier
11856      * {@link DevicePolicyIdentifiers#APPLICATION_HIDDEN_POLICY}
11857      * <li> The additional policy params bundle, which contains
11858      * {@link PolicyUpdateReceiver#EXTRA_PACKAGE_NAME} the package name the policy applies to
11859      * <li> The {@link TargetUser} that this policy relates to
11860      * <li> The {@link PolicyUpdateResult}, which will be
11861      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
11862      * reason the policy failed to be set
11863      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
11864      * </ul>
11865      * If there has been a change to the policy,
11866      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
11867      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
11868      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
11869      * will contain the reason why the policy changed.
11870      *
11871      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
11872      *            {@code null} if the caller is not a device admin.
11873      * @param packageName The name of the package to hide or unhide.
11874      * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
11875      *            unhidden.
11876      * @return boolean Whether the hidden setting of the package was successfully updated.
11877      * @throws SecurityException if {@code admin} is not a device or profile owner or if called on
11878      *            the parent profile and the {@code admin} is not a profile owner of an
11879      *            organization-owned managed profile.
11880      * @throws IllegalArgumentException if called on the parent profile and the package provided
11881      *            is not a system package.
11882      * @see #setDelegatedScopes
11883      * @see #DELEGATION_PACKAGE_ACCESS
11884      */
11885     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PACKAGE_STATE, conditional = true)
setApplicationHidden(@ullable ComponentName admin, String packageName, boolean hidden)11886     public boolean setApplicationHidden(@Nullable ComponentName admin, String packageName,
11887             boolean hidden) {
11888         if (mService != null) {
11889             try {
11890                 return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName,
11891                         hidden, mParentInstance);
11892             } catch (RemoteException e) {
11893                 throw e.rethrowFromSystemServer();
11894             }
11895         }
11896         return false;
11897     }
11898 
11899     /**
11900      * Determine if a package is hidden. This function can be called by a device owner, profile
11901      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
11902      * {@link #setDelegatedScopes}.
11903      * <p>
11904      * This method can be called on the {@link DevicePolicyManager} instance, returned by
11905      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
11906      * of an organization-owned managed profile and the package must be a system package. If called
11907      * on the parent instance, this will determine whether the package is hidden or unhidden in the
11908      * personal profile.
11909      * <p>
11910      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the returned policy will be the
11911      * current resolved policy rather than the policy set by the calling admin.
11912      *
11913      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
11914      *            {@code null} if the caller is not a device admin.
11915      * @param packageName The name of the package to retrieve the hidden status of.
11916      * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
11917      * @throws SecurityException if {@code admin} is not a device or profile owner or if called on
11918      *            the parent profile and the {@code admin} is not a profile owner of an
11919      *            organization-owned managed profile.
11920      * @throws IllegalArgumentException if called on the parent profile and the package provided
11921      *            is not a system package.
11922      * @see #setDelegatedScopes
11923      * @see #DELEGATION_PACKAGE_ACCESS
11924      */
11925     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PACKAGE_STATE, conditional = true)
isApplicationHidden(@ullable ComponentName admin, String packageName)11926     public boolean isApplicationHidden(@Nullable ComponentName admin, String packageName) {
11927         if (mService != null) {
11928             try {
11929                 return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName,
11930                         mParentInstance);
11931             } catch (RemoteException e) {
11932                 throw e.rethrowFromSystemServer();
11933             }
11934         }
11935         return false;
11936     }
11937 
11938     /**
11939      * Re-enable a system app that was disabled by default when the user was initialized. This
11940      * function can be called by a device owner, profile owner, or by a delegate given the
11941      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
11942      *
11943      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
11944      *            {@code null} if the caller is an enable system app delegate.
11945      * @param packageName The package to be re-enabled in the calling profile.
11946      * @throws SecurityException if {@code admin} is not a device or profile owner.
11947      * @see #setDelegatedScopes
11948      * @see #DELEGATION_PACKAGE_ACCESS
11949      */
enableSystemApp(@onNull ComponentName admin, String packageName)11950     public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
11951         throwIfParentInstance("enableSystemApp");
11952         if (mService != null) {
11953             try {
11954                 mService.enableSystemApp(admin, mContext.getPackageName(), packageName);
11955             } catch (RemoteException e) {
11956                 throw e.rethrowFromSystemServer();
11957             }
11958         }
11959     }
11960 
11961     /**
11962      * Re-enable system apps by intent that were disabled by default when the user was initialized.
11963      * This function can be called by a device owner, profile owner, or by a delegate given the
11964      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
11965      *
11966      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
11967      *            {@code null} if the caller is an enable system app delegate.
11968      * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
11969      *            intent will be re-enabled in the calling profile.
11970      * @return int The number of activities that matched the intent and were installed.
11971      * @throws SecurityException if {@code admin} is not a device or profile owner.
11972      * @see #setDelegatedScopes
11973      * @see #DELEGATION_PACKAGE_ACCESS
11974      */
enableSystemApp(@onNull ComponentName admin, Intent intent)11975     public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
11976         throwIfParentInstance("enableSystemApp");
11977         if (mService != null) {
11978             try {
11979                 return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent);
11980             } catch (RemoteException e) {
11981                 throw e.rethrowFromSystemServer();
11982             }
11983         }
11984         return 0;
11985     }
11986 
11987     /**
11988      * Install an existing package that has been installed in another user, or has been kept after
11989      * removal via {@link #setKeepUninstalledPackages}.
11990      * This function can be called by a device owner, profile owner or a delegate given
11991      * the {@link #DELEGATION_INSTALL_EXISTING_PACKAGE} scope via {@link #setDelegatedScopes}.
11992      * When called in a secondary user or managed profile, the user/profile must be affiliated with
11993      * the device. See {@link #isAffiliatedUser}.
11994      *
11995      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11996      * @param packageName The package to be installed in the calling profile.
11997      * @return {@code true} if the app is installed; {@code false} otherwise.
11998      * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
11999      * an affiliated user or profile.
12000      * @see #setKeepUninstalledPackages
12001      * @see #setDelegatedScopes
12002      * @see #isAffiliatedUser
12003      * @see #DELEGATION_PACKAGE_ACCESS
12004      */
installExistingPackage(@onNull ComponentName admin, String packageName)12005     public boolean installExistingPackage(@NonNull ComponentName admin, String packageName) {
12006         throwIfParentInstance("installExistingPackage");
12007         if (mService != null) {
12008             try {
12009                 return mService.installExistingPackage(admin, mContext.getPackageName(),
12010                         packageName);
12011             } catch (RemoteException e) {
12012                 throw e.rethrowFromSystemServer();
12013             }
12014         }
12015         return false;
12016     }
12017 
12018     /**
12019      * Called by a device owner or profile owner to disable account management for a specific type
12020      * of account.
12021      * <p>
12022      * The calling device admin must be a device owner or profile owner. If it is not, a security
12023      * exception will be thrown.
12024      * <p>
12025      * When account management is disabled for an account type, adding or removing an account of
12026      * that type will not be possible.
12027      * <p>
12028      * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
12029      * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
12030      * management for a specific type is disabled.
12031      * <p>
12032      * This method may be called on the {@code DevicePolicyManager} instance returned from
12033      * {@link #getParentProfileInstance(ComponentName)} by the profile owner on an
12034      * organization-owned device, to restrict accounts that may not be managed on the primary
12035      * profile.
12036      * <p>
12037      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the account management
12038      * disabled policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
12039      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
12040      * successfully set or not. This callback will contain:
12041      * <ul>
12042      * <li> The policy identifier
12043      * {@link DevicePolicyIdentifiers#ACCOUNT_MANAGEMENT_DISABLED_POLICY}
12044      * <li> The additional policy params bundle, which contains
12045      * {@link PolicyUpdateReceiver#EXTRA_ACCOUNT_TYPE} the account type the policy applies to
12046      * <li> The {@link TargetUser} that this policy relates to
12047      * <li> The {@link PolicyUpdateResult}, which will be
12048      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
12049      * reason the policy failed to be set
12050      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
12051      * </ul>
12052      * If there has been a change to the policy,
12053      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
12054      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
12055      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
12056      * will contain the reason why the policy changed.
12057      *
12058      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12059      *              caller is not a device admin.
12060      * @param accountType For which account management is disabled or enabled.
12061      * @param disabled The boolean indicating that account management will be disabled (true) or
12062      *            enabled (false).
12063      * @throws SecurityException if {@code admin} is not a device or profile owner.
12064      */
12065     @RequiresPermission(value = MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT, conditional = true)
setAccountManagementDisabled(@ullable ComponentName admin, String accountType, boolean disabled)12066     public void setAccountManagementDisabled(@Nullable ComponentName admin, String accountType,
12067             boolean disabled) {
12068         if (mService != null) {
12069             try {
12070                 mService.setAccountManagementDisabled(admin, mContext.getPackageName(), accountType,
12071                         disabled, mParentInstance);
12072             } catch (RemoteException e) {
12073                 throw e.rethrowFromSystemServer();
12074             }
12075         }
12076     }
12077 
12078     /**
12079      * Gets the array of accounts for which account management is disabled by the profile owner
12080      * or device owner.
12081      *
12082      * <p> Account management can be disabled/enabled by calling
12083      * {@link #setAccountManagementDisabled}.
12084      * <p>
12085      * This method may be called on the {@code DevicePolicyManager} instance returned from
12086      * {@link #getParentProfileInstance(ComponentName)}. Note that only a profile owner on
12087      * an organization-owned device can affect account types on the parent profile instance.
12088      *
12089      * @return a list of account types for which account management has been disabled.
12090      *
12091      * @see #setAccountManagementDisabled
12092      */
getAccountTypesWithManagementDisabled()12093     public @Nullable String[] getAccountTypesWithManagementDisabled() {
12094         return getAccountTypesWithManagementDisabledAsUser(myUserId(), mParentInstance);
12095     }
12096 
12097     /**
12098      * @see #getAccountTypesWithManagementDisabled()
12099      * Note that calling this method on the parent profile instance will return the same
12100      * value as calling it on the main {@code DevicePolicyManager} instance.
12101      * @hide
12102      */
12103     @RequiresPermission(value = MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT, conditional = true)
getAccountTypesWithManagementDisabledAsUser(int userId)12104     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
12105         return getAccountTypesWithManagementDisabledAsUser(userId, false);
12106     }
12107 
12108     /**
12109      * @see #getAccountTypesWithManagementDisabled()
12110      * @hide
12111      */
getAccountTypesWithManagementDisabledAsUser( int userId, boolean parentInstance)12112     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(
12113             int userId, boolean parentInstance) {
12114         if (mService != null) {
12115             try {
12116                 return mService.getAccountTypesWithManagementDisabledAsUser(userId,
12117                         mContext.getPackageName(), parentInstance);
12118             } catch (RemoteException e) {
12119                 throw e.rethrowFromSystemServer();
12120             }
12121         }
12122 
12123         return null;
12124     }
12125 
12126     /**
12127      * Called by device owner or profile owner to set whether a secondary lockscreen needs to be
12128      * shown.
12129      *
12130      * <p>The secondary lockscreen will by displayed after the primary keyguard security screen
12131      * requirements are met. To provide the lockscreen content the DO/PO will need to provide a
12132      * service handling the {@link #ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE} intent action,
12133      * extending the {@link DevicePolicyKeyguardService} class.
12134      *
12135      * <p>Relevant interactions on the secondary lockscreen should be communicated back to the
12136      * keyguard via {@link IKeyguardCallback}, such as when the screen is ready to be dismissed.
12137      *
12138      * <p>This API, and associated APIs, can only be called by the default supervision app when it
12139      * is set as the device owner or profile owner.
12140      *
12141      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12142      * @param enabled Whether or not the lockscreen needs to be shown.
12143      * @throws SecurityException if {@code admin} is not a device or profile owner.
12144      * @see #isSecondaryLockscreenEnabled
12145      * @hide
12146      **/
12147     @SystemApi
setSecondaryLockscreenEnabled(@onNull ComponentName admin, boolean enabled)12148     public void setSecondaryLockscreenEnabled(@NonNull ComponentName admin, boolean enabled) {
12149         throwIfParentInstance("setSecondaryLockscreenEnabled");
12150         if (mService != null) {
12151             try {
12152                 mService.setSecondaryLockscreenEnabled(admin, enabled);
12153             } catch (RemoteException e) {
12154                 throw e.rethrowFromSystemServer();
12155             }
12156         }
12157     }
12158 
12159     /**
12160      * Returns whether the secondary lock screen needs to be shown.
12161      * @see #setSecondaryLockscreenEnabled
12162      * @hide
12163      */
12164     @SystemApi
isSecondaryLockscreenEnabled(@onNull UserHandle userHandle)12165     public boolean isSecondaryLockscreenEnabled(@NonNull UserHandle userHandle) {
12166         throwIfParentInstance("isSecondaryLockscreenEnabled");
12167         if (mService != null) {
12168             try {
12169                 return mService.isSecondaryLockscreenEnabled(userHandle);
12170             } catch (RemoteException e) {
12171                 throw e.rethrowFromSystemServer();
12172             }
12173         }
12174         return false;
12175     }
12176 
12177     /**
12178      * Sets which packages may enter lock task mode.
12179      * <p>
12180      * Any packages that share uid with an allowed package will also be allowed to activate lock
12181      * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
12182      * package list results in locked tasks belonging to those packages to be finished.
12183      * <p>
12184      * This function can only be called by the device owner, a profile owner of an affiliated user
12185      * or profile, or the profile owner when no device owner is set or holders of the permission
12186      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}. See
12187      * {@link #isAffiliatedUser}.
12188      * Any package set via this method will be cleared if the user becomes unaffiliated.
12189      * <p>
12190      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the lock task policy has
12191      * been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, Bundle, TargetUser,
12192      * PolicyUpdateResult)} will notify the admin on whether the policy was successfully set or not.
12193      * This callback will contain:
12194      * <ul>
12195      * <li> The policy identifier {@link DevicePolicyIdentifiers#LOCK_TASK_POLICY}
12196      * <li> The {@link TargetUser} that this policy relates to
12197      * <li> The {@link PolicyUpdateResult}, which will be
12198      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
12199      * reason the policy failed to be set
12200      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
12201      * </ul>
12202      * If there has been a change to the policy,
12203      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
12204      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
12205      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
12206      * will contain the reason why the policy changed.
12207      * <p>
12208      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, lock task features and lock task
12209      * packages are bundled as one policy. A failure to apply one will result in a failure to apply
12210      * the other.
12211      *
12212      * @param packages The list of packages allowed to enter lock task mode
12213      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12214      *               caller is not a device admin.
12215      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
12216      * affiliated user or profile, or the profile owner when no device owner is set or holder of the
12217      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}.
12218      * @see #isAffiliatedUser
12219      * @see Activity#startLockTask()
12220      * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
12221      * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
12222      * @see UserManager#DISALLOW_CREATE_WINDOWS
12223      */
12224     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true)
12225     @SupportsCoexistence
setLockTaskPackages(@ullable ComponentName admin, @NonNull String[] packages)12226     public void setLockTaskPackages(@Nullable ComponentName admin, @NonNull String[] packages)
12227             throws SecurityException {
12228         throwIfParentInstance("setLockTaskPackages");
12229         if (mService != null) {
12230             try {
12231                 mService.setLockTaskPackages(admin, mContext.getPackageName(),  packages);
12232             } catch (RemoteException e) {
12233                 throw e.rethrowFromSystemServer();
12234             }
12235         }
12236     }
12237 
12238     /**
12239      * Returns the list of packages allowed to start the lock task mode.
12240      * <p>
12241      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the returned policy will be the
12242      * current resolved policy rather than the policy set by the calling admin.
12243      *
12244      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12245      *              caller is not a device admin.
12246      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
12247      * affiliated user or profile, or the profile owner when no device owner is set or holder of the
12248      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}.
12249      * @see #isAffiliatedUser
12250      * @see #setLockTaskPackages
12251      */
12252     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true)
getLockTaskPackages(@ullable ComponentName admin)12253     public @NonNull String[] getLockTaskPackages(@Nullable ComponentName admin) {
12254         throwIfParentInstance("getLockTaskPackages");
12255         if (mService != null) {
12256             try {
12257                 return mService.getLockTaskPackages(admin, mContext.getPackageName());
12258             } catch (RemoteException e) {
12259                 throw e.rethrowFromSystemServer();
12260             }
12261         }
12262         return new String[0];
12263     }
12264 
12265     /**
12266      * This function lets the caller know whether the given component is allowed to start the
12267      * lock task mode.
12268      * @param pkg The package to check
12269      */
isLockTaskPermitted(String pkg)12270     public boolean isLockTaskPermitted(String pkg) {
12271         throwIfParentInstance("isLockTaskPermitted");
12272         if (mService != null) {
12273             try {
12274                 return mService.isLockTaskPermitted(pkg);
12275             } catch (RemoteException e) {
12276                 throw e.rethrowFromSystemServer();
12277             }
12278         }
12279         return false;
12280     }
12281 
12282     /**
12283      * Sets which system features are enabled when the device runs in lock task mode. This method
12284      * doesn't affect the features when lock task mode is inactive. Any system features not included
12285      * in {@code flags} are implicitly disabled when calling this method. By default, only
12286      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS} is enabled; all the other features are disabled. To
12287      * disable the global actions dialog, call this method omitting
12288      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}.
12289      *
12290      * <p>This method can only be called by the device owner, a profile owner of an affiliated
12291      * user or profile, or the profile owner when no device owner is set or holders of the
12292      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}. See
12293      * {@link #isAffiliatedUser}.
12294      * Any features set using this method are cleared if the user becomes unaffiliated.
12295      * <p>
12296      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the lock task features
12297      * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, Bundle,
12298      * TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
12299      * successfully set or not. This callback will contain:
12300      * <ul>
12301      * <li> The policy identifier {@link DevicePolicyIdentifiers#LOCK_TASK_POLICY}
12302      * <li> The {@link TargetUser} that this policy relates to
12303      * <li> The {@link PolicyUpdateResult}, which will be
12304      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
12305      * reason the policy failed to be set
12306      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
12307      * </ul>
12308      * If there has been a change to the policy,
12309      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
12310      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
12311      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
12312      * will contain the reason why the policy changed.
12313      * <p>
12314      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, lock task features and lock task
12315      * packages are bundled as one policy. A failure to apply one will result in a failure to apply
12316      * the other.
12317      *
12318      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12319      *               caller is not a device admin.
12320      * @param flags The system features enabled during lock task mode.
12321      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
12322      * affiliated user or profile, or the profile owner when no device owner is set or holder of the
12323      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}.
12324      * @see #isAffiliatedUser
12325      **/
12326     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true)
12327     @SupportsCoexistence
setLockTaskFeatures(@ullable ComponentName admin, @LockTaskFeature int flags)12328     public void setLockTaskFeatures(@Nullable ComponentName admin, @LockTaskFeature int flags) {
12329         throwIfParentInstance("setLockTaskFeatures");
12330         if (mService != null) {
12331             try {
12332                 mService.setLockTaskFeatures(admin, mContext.getPackageName(), flags);
12333             } catch (RemoteException e) {
12334                 throw e.rethrowFromSystemServer();
12335             }
12336         }
12337     }
12338 
12339     /**
12340      * Gets which system features are enabled for LockTask mode.
12341      * <p>
12342      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the returned policy will be the
12343      * current resolved policy rather than the policy set by the calling admin.
12344      *
12345      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12346      *               caller is not a device admin.
12347      * @return bitfield of flags. See {@link #setLockTaskFeatures(ComponentName, int)} for a list.
12348      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
12349      * affiliated user or profile, or the profile owner when no device owner is set or holder of the
12350      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}.
12351      * @see #isAffiliatedUser
12352      * @see #setLockTaskFeatures
12353      */
12354     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true)
getLockTaskFeatures(@ullable ComponentName admin)12355     public @LockTaskFeature int getLockTaskFeatures(@Nullable ComponentName admin) {
12356         throwIfParentInstance("getLockTaskFeatures");
12357         if (mService != null) {
12358             try {
12359                 return mService.getLockTaskFeatures(admin, mContext.getPackageName());
12360             } catch (RemoteException e) {
12361                 throw e.rethrowFromSystemServer();
12362             }
12363         }
12364         return 0;
12365     }
12366 
12367     /**
12368      * Sets whether preferential network service is enabled.
12369      * For example, an organization can have a deal/agreement with a carrier that all of
12370      * the work data from its employees’ devices will be sent via a network service dedicated
12371      * for enterprise use.
12372      *
12373      * An example of a supported preferential network service is the Enterprise
12374      * slice on 5G networks. For devices on 4G networks, the profile owner needs to additionally
12375      * configure enterprise APN to set up data call for the preferential network service.
12376      * These APNs can be added using {@link #addOverrideApn}.
12377      *
12378      * By default, preferential network service is disabled on the work profile and
12379      * fully managed devices, on supported carriers and devices.
12380      * Admins can explicitly enable it with this API.
12381      *
12382      * <p> This method enables preferential network service with a default configuration.
12383      * To fine-tune the configuration, use {@link #setPreferentialNetworkServiceConfigs) instead.
12384      * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
12385      * this method can be called by the profile owner of a managed profile.
12386      * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
12387      * This method can be called by the profile owner of a managed profile
12388      * or device owner.
12389      *
12390      * @param enabled whether preferential network service should be enabled.
12391      * @throws SecurityException if the caller is not the profile owner or device owner.
12392      **/
setPreferentialNetworkServiceEnabled(boolean enabled)12393     public void setPreferentialNetworkServiceEnabled(boolean enabled) {
12394         throwIfParentInstance("setPreferentialNetworkServiceEnabled");
12395         PreferentialNetworkServiceConfig.Builder configBuilder =
12396                 new PreferentialNetworkServiceConfig.Builder();
12397         configBuilder.setEnabled(enabled);
12398         if (enabled) {
12399             configBuilder.setNetworkId(NET_ENTERPRISE_ID_1);
12400         }
12401         setPreferentialNetworkServiceConfigs(List.of(configBuilder.build()));
12402     }
12403 
12404     /**
12405      * Indicates whether preferential network service is enabled.
12406      *
12407      * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
12408      * This method can be called by the profile owner of a managed profile.
12409      * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
12410      * This method can be called by the profile owner of a managed profile
12411      * or device owner.
12412      *
12413      * @return whether preferential network service is enabled.
12414      * @throws SecurityException if the caller is not the profile owner or device owner.
12415      */
isPreferentialNetworkServiceEnabled()12416     public boolean isPreferentialNetworkServiceEnabled() {
12417         throwIfParentInstance("isPreferentialNetworkServiceEnabled");
12418         return getPreferentialNetworkServiceConfigs().stream().anyMatch(c -> c.isEnabled());
12419     }
12420 
12421     /**
12422      * Sets preferential network configurations.
12423      * {@see PreferentialNetworkServiceConfig}
12424      *
12425      * An example of a supported preferential network service is the Enterprise
12426      * slice on 5G networks. For devices on 4G networks, the profile owner needs to additionally
12427      * configure enterprise APN to set up data call for the preferential network service.
12428      * These APNs can be added using {@link #addOverrideApn}.
12429      *
12430      * By default, preferential network service is disabled on the work profile and fully managed
12431      * devices, on supported carriers and devices. Admins can explicitly enable it with this API.
12432      * If admin wants to have multiple enterprise slices,
12433      * it can be configured by passing list of {@link PreferentialNetworkServiceConfig} objects.
12434      *
12435      * @param preferentialNetworkServiceConfigs list of preferential network configurations.
12436      * @throws SecurityException if the caller is not the profile owner or device owner.
12437      **/
setPreferentialNetworkServiceConfigs( @onNull List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs)12438     public void setPreferentialNetworkServiceConfigs(
12439             @NonNull List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs) {
12440         throwIfParentInstance("setPreferentialNetworkServiceConfigs");
12441         if (mService == null) {
12442             return;
12443         }
12444         try {
12445             mService.setPreferentialNetworkServiceConfigs(preferentialNetworkServiceConfigs);
12446         } catch (RemoteException e) {
12447             throw e.rethrowFromSystemServer();
12448         }
12449     }
12450 
12451     /**
12452      * Get preferential network configuration
12453      * {@see PreferentialNetworkServiceConfig}
12454      *
12455      * @return preferential network configuration.
12456      * @throws SecurityException if the caller is not the profile owner or device owner.
12457      */
getPreferentialNetworkServiceConfigs()12458     public @NonNull List<PreferentialNetworkServiceConfig> getPreferentialNetworkServiceConfigs() {
12459         throwIfParentInstance("getPreferentialNetworkServiceConfigs");
12460         if (mService == null) {
12461             return List.of(PreferentialNetworkServiceConfig.DEFAULT);
12462         }
12463         try {
12464             return mService.getPreferentialNetworkServiceConfigs();
12465         } catch (RemoteException e) {
12466             throw e.rethrowFromSystemServer();
12467         }
12468     }
12469 
12470     /**
12471      * This method is mostly deprecated.
12472      * Most of the settings that still have an effect have dedicated setter methods or user
12473      * restrictions. See individual settings for details.
12474      * <p>
12475      * Called by device owner to update {@link android.provider.Settings.Global} settings.
12476      * Validation that the value of the setting is in the correct form for the setting type should
12477      * be performed by the caller.
12478      * <p>
12479      * The settings that can be updated with this method are:
12480      * <ul>
12481      * <li>{@link android.provider.Settings.Global#ADB_ENABLED} : use
12482      * {@link UserManager#DISALLOW_DEBUGGING_FEATURES} instead to restrict users from enabling
12483      * debugging features and this setting to turn adb on.</li>
12484      * <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
12485      * <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only
12486      * available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
12487      * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
12488      * <li>{@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This
12489      * setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
12490      * </ul>
12491      * <p>
12492      * The following settings used to be supported, but can be controlled in other ways:
12493      * <ul>
12494      * <li>{@link android.provider.Settings.Global#AUTO_TIME} : Use {@link #setAutoTimeEnabled} and
12495      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} instead.</li>
12496      * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE} : Use
12497      * {@link #setAutoTimeZoneEnabled} and {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
12498      * instead.</li>
12499      * <li>{@link android.provider.Settings.Global#DATA_ROAMING} : Use
12500      * {@link UserManager#DISALLOW_DATA_ROAMING} instead.</li>
12501      * </ul>
12502      * <p>
12503      * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
12504      * <ul>
12505      * <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use
12506      * {@link android.bluetooth.BluetoothAdapter#enable()} and
12507      * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
12508      * <li>{@link android.provider.Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
12509      * <li>{@link android.provider.Settings.Global#MODE_RINGER}. Use
12510      * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
12511      * <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li>
12512      * <li>{@link android.provider.Settings.Global#WIFI_ON}. Use
12513      * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
12514      * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}. No longer has effect.</li>
12515      * </ul>
12516      *
12517      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12518      * @param setting The name of the setting to update.
12519      * @param value The value to update the setting to.
12520      * @throws SecurityException if {@code admin} is not a device owner.
12521      */
setGlobalSetting(@onNull ComponentName admin, String setting, String value)12522     public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
12523         throwIfParentInstance("setGlobalSetting");
12524         if (mService != null) {
12525             try {
12526                 mService.setGlobalSetting(admin, setting, value);
12527             } catch (RemoteException e) {
12528                 throw e.rethrowFromSystemServer();
12529             }
12530         }
12531     }
12532 
12533     /** @hide */
12534     @StringDef({
12535             Settings.System.SCREEN_BRIGHTNESS_MODE,
12536             Settings.System.SCREEN_BRIGHTNESS,
12537             Settings.System.SCREEN_BRIGHTNESS_FLOAT,
12538             Settings.System.SCREEN_OFF_TIMEOUT
12539     })
12540     @Retention(RetentionPolicy.SOURCE)
12541     public @interface SystemSettingsWhitelist {}
12542 
12543     /**
12544      * Called by a device or profile owner to update {@link android.provider.Settings.System}
12545      * settings. Validation that the value of the setting is in the correct form for the setting
12546      * type should be performed by the caller.
12547      * <p>
12548      * The settings that can be updated by a device owner or profile owner of secondary user with
12549      * this method are:
12550      * <ul>
12551      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS}</li>
12552      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS_MODE}</li>
12553      * <li>{@link android.provider.Settings.System#SCREEN_OFF_TIMEOUT}</li>
12554      * </ul>
12555      * <p>
12556      *
12557      * @see android.provider.Settings.System#SCREEN_OFF_TIMEOUT
12558      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12559      * @param setting The name of the setting to update.
12560      * @param value The value to update the setting to.
12561      * @throws SecurityException if {@code admin} is not a device or profile owner.
12562      */
setSystemSetting(@onNull ComponentName admin, @NonNull @SystemSettingsWhitelist String setting, String value)12563     public void setSystemSetting(@NonNull ComponentName admin,
12564             @NonNull @SystemSettingsWhitelist String setting, String value) {
12565         throwIfParentInstance("setSystemSetting");
12566         if (mService != null) {
12567             try {
12568                 mService.setSystemSetting(admin, setting, value);
12569             } catch (RemoteException e) {
12570                 throw e.rethrowFromSystemServer();
12571             }
12572         }
12573     }
12574 
12575     /**
12576      * Called by a device owner or a profile owner of an organization-owned managed profile to
12577      * control whether the user can change networks configured by the admin. When this lockdown is
12578      * enabled, the user can still configure and connect to other Wi-Fi networks, or use other Wi-Fi
12579      * capabilities such as tethering.
12580      * <p>
12581      * WiFi network configuration lockdown is controlled by a global settings
12582      * {@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN} and calling
12583      * this API effectively modifies the global settings. Previously device owners can also
12584      * control this directly via {@link #setGlobalSetting} but they are recommended to switch
12585      * to this API.
12586      *
12587      * @param admin             admin Which {@link DeviceAdminReceiver} this request is associated
12588      *                          with. Null if the caller is not a device admin.
12589      * @param lockdown Whether the admin configured networks should be unmodifiable by the
12590      *                          user.
12591      * @throws SecurityException if caller is not a device owner or a profile owner of an
12592      *                           organization-owned managed profile.
12593      */
12594     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true)
setConfiguredNetworksLockdownState( @ullable ComponentName admin, boolean lockdown)12595     public void setConfiguredNetworksLockdownState(
12596             @Nullable ComponentName admin, boolean lockdown) {
12597         throwIfParentInstance("setConfiguredNetworksLockdownState");
12598         if (mService != null) {
12599             try {
12600                 mService.setConfiguredNetworksLockdownState(
12601                         admin, mContext.getPackageName(), lockdown);
12602             } catch (RemoteException e) {
12603                 throw e.rethrowFromSystemServer();
12604             }
12605         }
12606     }
12607 
12608     /**
12609      * Called by a device owner or a profile owner of an organization-owned managed profile to
12610      * determine whether the user is prevented from modifying networks configured by the admin.
12611      *
12612      * @param admin             admin Which {@link DeviceAdminReceiver} this request is associated
12613      *                          with.
12614      * @throws SecurityException if caller is not a device owner or a profile owner of an
12615      *                           organization-owned managed profile.
12616      */
12617     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true)
hasLockdownAdminConfiguredNetworks(@ullable ComponentName admin)12618     public boolean hasLockdownAdminConfiguredNetworks(@Nullable ComponentName admin) {
12619         throwIfParentInstance("hasLockdownAdminConfiguredNetworks");
12620         if (mService != null) {
12621             try {
12622                 return mService.hasLockdownAdminConfiguredNetworks(admin);
12623             } catch (RemoteException e) {
12624                 throw e.rethrowFromSystemServer();
12625             }
12626         }
12627         return false;
12628     }
12629 
12630     /**
12631      * Called by a device owner or a profile owner of an organization-owned managed
12632      * profile to set the system wall clock time. This only takes effect if called when
12633      * {@link android.provider.Settings.Global#AUTO_TIME} is 0, otherwise {@code false}
12634      * will be returned.
12635      *
12636      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12637      *               caller is not a device admin.
12638      * @param millis time in milliseconds since the Epoch
12639      * @return {@code true} if set time succeeded, {@code false} otherwise.
12640      * @throws SecurityException if {@code admin} is not a device owner or a profile owner
12641      * of an organization-owned managed profile.
12642      */
12643     @RequiresPermission(value = SET_TIME, conditional = true)
setTime(@ullable ComponentName admin, long millis)12644     public boolean setTime(@Nullable ComponentName admin, long millis) {
12645         throwIfParentInstance("setTime");
12646         if (mService != null) {
12647             try {
12648                 return mService.setTime(admin, mContext.getPackageName(), millis);
12649             } catch (RemoteException e) {
12650                 throw e.rethrowFromSystemServer();
12651             }
12652         }
12653         return false;
12654     }
12655 
12656     /**
12657      * Called by a device owner or a profile owner of an organization-owned managed
12658      * profile to set the system's persistent default time zone. This only takes
12659      * effect if called when {@link android.provider.Settings.Global#AUTO_TIME_ZONE}
12660      * is 0, otherwise {@code false} will be returned.
12661      *
12662      * @see android.app.AlarmManager#setTimeZone(String)
12663      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12664      *               caller is not a device admin.
12665      * @param timeZone one of the Olson ids from the list returned by
12666      *     {@link java.util.TimeZone#getAvailableIDs}
12667      * @return {@code true} if set timezone succeeded, {@code false} otherwise.
12668      * @throws SecurityException if {@code admin} is not a device owner or a profile owner
12669      * of an organization-owned managed profile.
12670      */
12671     @RequiresPermission(value = SET_TIME_ZONE, conditional = true)
setTimeZone(@ullable ComponentName admin, String timeZone)12672     public boolean setTimeZone(@Nullable ComponentName admin, String timeZone) {
12673         throwIfParentInstance("setTimeZone");
12674         if (mService != null) {
12675             try {
12676                 return mService.setTimeZone(admin, mContext.getPackageName(), timeZone);
12677             } catch (RemoteException e) {
12678                 throw e.rethrowFromSystemServer();
12679             }
12680         }
12681         return false;
12682     }
12683 
12684     /**
12685      * Called by device owners to set the user's global location setting.
12686      *
12687      *
12688      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
12689      * @param locationEnabled whether location should be enabled or disabled. <b>Note: </b> on
12690      * {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, calls to
12691      * disable will be ignored.
12692      * @throws SecurityException if {@code admin} is not a device owner.
12693      */
setLocationEnabled(@onNull ComponentName admin, boolean locationEnabled)12694     public void setLocationEnabled(@NonNull ComponentName admin, boolean locationEnabled) {
12695         throwIfParentInstance("setLocationEnabled");
12696         if (mService != null) {
12697             try {
12698                 mService.setLocationEnabled(admin, locationEnabled);
12699             } catch (RemoteException e) {
12700                 throw e.rethrowFromSystemServer();
12701             }
12702         }
12703     }
12704 
12705     /**
12706      * This method is mostly deprecated.
12707      * Most of the settings that still have an effect have dedicated setter methods
12708      * (e.g. {@link #setLocationEnabled}) or user restrictions.
12709      * <p>
12710      *
12711      * Called by profile or device owners to update {@link android.provider.Settings.Secure}
12712      * settings. Validation that the value of the setting is in the correct form for the setting
12713      * type should be performed by the caller.
12714      * <p>
12715      * The settings that can be updated by a profile or device owner with this method are:
12716      * <ul>
12717      * <li>{@link android.provider.Settings.Secure#DEFAULT_INPUT_METHOD}</li>
12718      * <li>{@link android.provider.Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
12719      * </ul>
12720      * <p>
12721      * A device owner can additionally update the following settings:
12722      * <ul>
12723      * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}, but see note below.</li>
12724      * </ul>
12725      *
12726      * <strong>Note: Starting from Android O, apps should no longer call this method with the
12727      * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is
12728      * deprecated. Instead, device owners or profile owners should use the restriction
12729      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}.
12730      * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method
12731      * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS},
12732      * an {@link UnsupportedOperationException} is thrown.
12733      *
12734      * Starting from Android Q, the device and profile owner can also call
12735      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY} to restrict unknown sources for
12736      * all users.
12737      * </strong>
12738      *
12739      * <strong>Note: Starting from Android R, apps should no longer call this method with the
12740      * setting {@link android.provider.Settings.Secure#LOCATION_MODE}, which is deprecated. Instead,
12741      * device owners should call {@link #setLocationEnabled(ComponentName, boolean)}. This will be
12742      * enforced for all apps targeting Android R or above.
12743      * </strong>
12744      *
12745      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12746      * @param setting The name of the setting to update.
12747      * @param value The value to update the setting to.
12748      * @throws SecurityException if {@code admin} is not a device or profile owner.
12749      */
setSecureSetting(@onNull ComponentName admin, String setting, String value)12750     public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
12751         throwIfParentInstance("setSecureSetting");
12752 
12753         if (mService != null) {
12754             try {
12755                 mService.setSecureSetting(admin, setting, value);
12756             } catch (RemoteException e) {
12757                 throw e.rethrowFromSystemServer();
12758             }
12759         }
12760     }
12761 
12762     /**
12763      * Designates a specific service component as the provider for making permission requests of a
12764      * local or remote administrator of the user.
12765      * <p/>
12766      * Only a device owner or profile owner can designate the restrictions provider.
12767      *
12768      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12769      * @param provider The component name of the service that implements
12770      *            {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
12771      *            provider previously assigned.
12772      * @throws SecurityException if {@code admin} is not a device or profile owner.
12773      */
setRestrictionsProvider(@onNull ComponentName admin, @Nullable ComponentName provider)12774     public void setRestrictionsProvider(@NonNull ComponentName admin,
12775             @Nullable ComponentName provider) {
12776         throwIfParentInstance("setRestrictionsProvider");
12777         if (mService != null) {
12778             try {
12779                 mService.setRestrictionsProvider(admin, provider);
12780             } catch (RemoteException re) {
12781                 throw re.rethrowFromSystemServer();
12782             }
12783         }
12784     }
12785 
12786     /**
12787      * Called by profile or device owners to set the global volume mute on or off.
12788      * This has no effect when set on a managed profile.
12789      *
12790      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12791      * @param on {@code true} to mute global volume, {@code false} to turn mute off.
12792      * @throws SecurityException if {@code admin} is not a device or profile owner.
12793      */
setMasterVolumeMuted(@onNull ComponentName admin, boolean on)12794     public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
12795         throwIfParentInstance("setMasterVolumeMuted");
12796         if (mService != null) {
12797             try {
12798                 mService.setMasterVolumeMuted(admin, on);
12799             } catch (RemoteException re) {
12800                 throw re.rethrowFromSystemServer();
12801             }
12802         }
12803     }
12804 
12805     /**
12806      * Called by profile or device owners to check whether the global volume mute is on or off.
12807      *
12808      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12809      * @return {@code true} if global volume is muted, {@code false} if it's not.
12810      * @throws SecurityException if {@code admin} is not a device or profile owner.
12811      */
isMasterVolumeMuted(@onNull ComponentName admin)12812     public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
12813         throwIfParentInstance("isMasterVolumeMuted");
12814         if (mService != null) {
12815             try {
12816                 return mService.isMasterVolumeMuted(admin);
12817             } catch (RemoteException re) {
12818                 throw re.rethrowFromSystemServer();
12819             }
12820         }
12821         return false;
12822     }
12823 
12824     /**
12825      * Change whether a user can uninstall a package. This function can be called by a device owner,
12826      * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via
12827      * {@link #setDelegatedScopes} or holders of the permission
12828      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL}.
12829      * <p>
12830      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the set uninstall blocked
12831      * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
12832      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
12833      * successfully set or not. This callback will contain:
12834      * <ul>
12835      * <li> The policy identifier
12836      * {@link DevicePolicyIdentifiers#PACKAGE_UNINSTALL_BLOCKED_POLICY}
12837      * <li> The additional policy params bundle, which contains
12838      * {@link PolicyUpdateReceiver#EXTRA_PACKAGE_NAME} the package name the policy applies to
12839      * <li> The {@link TargetUser} that this policy relates to
12840      * <li> The {@link PolicyUpdateResult}, which will be
12841      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
12842      * reason the policy failed to be set
12843      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
12844      * </ul>
12845      * If there has been a change to the policy,
12846      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
12847      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
12848      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
12849      * will contain the reason why the policy changed.
12850      *
12851      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12852      *               caller is not a device admin.
12853      * @param packageName package to change.
12854      * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
12855      * @throws SecurityException if {@code admin} is not a device or profile owner or holder of the
12856      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL}.
12857      * @see #setDelegatedScopes
12858      * @see #DELEGATION_BLOCK_UNINSTALL
12859      */
12860     @RequiresPermission(value = MANAGE_DEVICE_POLICY_APPS_CONTROL, conditional = true)
12861     @SupportsCoexistence
setUninstallBlocked(@ullable ComponentName admin, String packageName, boolean uninstallBlocked)12862     public void setUninstallBlocked(@Nullable ComponentName admin, String packageName,
12863             boolean uninstallBlocked) {
12864         throwIfParentInstance("setUninstallBlocked");
12865         if (mService != null) {
12866             try {
12867                 mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName,
12868                     uninstallBlocked);
12869             } catch (RemoteException re) {
12870                 throw re.rethrowFromSystemServer();
12871             }
12872         }
12873     }
12874 
12875     /**
12876      * Check whether the user has been blocked by device policy from uninstalling a package.
12877      * Requires the caller to be the profile owner if checking a specific admin's policy.
12878      * <p>
12879      * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
12880      * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
12881      * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
12882      * will cause a NullPointerException to be raised.
12883      * <p>
12884      * <strong>Note:</strong> If your app targets Android 11 (API level 30) or higher,
12885      * this method returns a filtered result. Learn more about how to
12886      * <a href="/training/basics/intents/package-visibility">manage package visibility</a>.
12887      * <p>
12888      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the returned policy will be the
12889      * current resolved policy rather than the policy set by the calling admin.
12890      *
12891      * @param admin The name of the admin component whose blocking policy will be checked, or
12892      *            {@code null} to check whether any admin has blocked the uninstallation. Starting
12893      *              from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} admin will be
12894      *              ignored and assumed {@code null}.
12895      * @param packageName package to check.
12896      * @return true if uninstallation is blocked and the given package is visible to you, false
12897      *         otherwise if uninstallation isn't blocked or the given package isn't visible to you.
12898      * @throws SecurityException if {@code admin} is not a device or profile owner.
12899      */
isUninstallBlocked(@ullable ComponentName admin, String packageName)12900     public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
12901         throwIfParentInstance("isUninstallBlocked");
12902         if (mService != null) {
12903             try {
12904                 return mService.isUninstallBlocked(packageName);
12905             } catch (RemoteException re) {
12906                 throw re.rethrowFromSystemServer();
12907             }
12908         }
12909         return false;
12910     }
12911 
12912     /**
12913      * Called by the profile owner of a managed profile or a holder of the permission
12914      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION} to enable
12915      * widget providers from a given package to be available in the parent profile. As a result the
12916      * user will be able to add widgets from the allowlisted package running under the profile to a
12917      * widget host which runs under the parent profile, for example the home screen. Note that a
12918      * package may have zero or more provider components, where each component provides a different
12919      * widget type.
12920      * <p>
12921      * <strong>Note:</strong> By default no widget provider package is allowlisted.
12922      *
12923      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12924      *              caller is not a device admin.
12925      * @param packageName The package from which widget providers are allowlisted.
12926      * @return Whether the package was added.
12927      * @throws SecurityException if {@code admin} is not a profile owner and not a holder of the
12928      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION}.
12929      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
12930      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
12931      */
12932     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PROFILE_INTERACTION, conditional = true)
addCrossProfileWidgetProvider(@ullable ComponentName admin, String packageName)12933     public boolean addCrossProfileWidgetProvider(@Nullable ComponentName admin,
12934             String packageName) {
12935         throwIfParentInstance("addCrossProfileWidgetProvider");
12936         if (mService != null) {
12937             try {
12938                 return mService.addCrossProfileWidgetProvider(admin,
12939                         mContext.getPackageName(), packageName);
12940             } catch (RemoteException re) {
12941                 throw re.rethrowFromSystemServer();
12942             }
12943         }
12944         return false;
12945     }
12946 
12947     /**
12948      * Called by the profile owner of a managed profile or a holder of the permission
12949      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION} to disable
12950      * widget providers from a given package to be available in the parent profile. For this method
12951      * to take effect the package should have been added via
12952      * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
12953      * <p>
12954      * <strong>Note:</strong> By default no widget provider package is allowlisted.
12955      *
12956      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12957      *              caller is not a device admin.
12958      * @param packageName The package from which widget providers are no longer allowlisted.
12959      * @return Whether the package was removed.
12960      * @throws SecurityException if {@code admin} is not a profile owner and not a holder of the
12961      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION}.
12962      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
12963      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
12964      */
12965     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PROFILE_INTERACTION, conditional = true)
removeCrossProfileWidgetProvider(@ullable ComponentName admin, String packageName)12966     public boolean removeCrossProfileWidgetProvider(@Nullable ComponentName admin,
12967             String packageName) {
12968         throwIfParentInstance("removeCrossProfileWidgetProvider");
12969         if (mService != null) {
12970             try {
12971                 return mService.removeCrossProfileWidgetProvider(admin, mContext.getPackageName(),
12972                         packageName);
12973             } catch (RemoteException re) {
12974                 throw re.rethrowFromSystemServer();
12975             }
12976         }
12977         return false;
12978     }
12979 
12980     /**
12981      * Called by the profile owner of a managed profile or a holder of the permission
12982      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION} to query
12983      * providers from which packages are available in the parent profile.
12984      *
12985      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12986      *              caller is not a device admin.
12987      * @return The allowlisted package list.
12988      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
12989      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
12990      * @throws SecurityException if {@code admin} is not a profile owner and not a holder of the
12991      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION}.
12992      */
12993     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PROFILE_INTERACTION, conditional = true)
getCrossProfileWidgetProviders(@ullable ComponentName admin)12994     public @NonNull List<String> getCrossProfileWidgetProviders(@Nullable ComponentName admin) {
12995         throwIfParentInstance("getCrossProfileWidgetProviders");
12996         if (mService != null) {
12997             try {
12998                 List<String> providers = mService.getCrossProfileWidgetProviders(admin,
12999                         mContext.getPackageName());
13000                 if (providers != null) {
13001                     return providers;
13002                 }
13003             } catch (RemoteException re) {
13004                 throw re.rethrowFromSystemServer();
13005             }
13006         }
13007         return Collections.emptyList();
13008     }
13009 
13010     /**
13011      * Called by profile or device owners to set the user's photo.
13012      *
13013      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13014      * @param icon the bitmap to set as the photo.
13015      * @throws SecurityException if {@code admin} is not a device or profile owner.
13016      */
setUserIcon(@onNull ComponentName admin, Bitmap icon)13017     public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
13018         throwIfParentInstance("setUserIcon");
13019         try {
13020             mService.setUserIcon(admin, icon);
13021         } catch (RemoteException re) {
13022             throw re.rethrowFromSystemServer();
13023         }
13024     }
13025 
13026     /**
13027      * Called by device owners or profile owners of an organization-owned managed profile to to set
13028      * a local system update policy. When a new policy is set,
13029      * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcast.
13030      * <p>
13031      * If the supplied system update policy has freeze periods set but the freeze periods do not
13032      * meet 90-day maximum length or 60-day minimum separation requirement set out in
13033      * {@link SystemUpdatePolicy#setFreezePeriods},
13034      * {@link SystemUpdatePolicy.ValidationFailedException} will the thrown. Note that the system
13035      * keeps a record of freeze periods the device experienced previously, and combines them with
13036      * the new freeze periods to be set when checking the maximum freeze length and minimum freeze
13037      * separation constraints. As a result, freeze periods that passed validation during
13038      * {@link SystemUpdatePolicy#setFreezePeriods} might fail the additional checks here due to
13039      * the freeze period history. If this is causing issues during development,
13040      * {@code adb shell dpm clear-freeze-period-record} can be used to clear the record.
13041      *
13042      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
13043      *            components in the package can set system update policies and the most
13044      *            recent policy takes effect. This should be null if the caller is not a device
13045      *              admin.
13046      * @param policy the new policy, or {@code null} to clear the current policy.
13047      * @throws SecurityException if {@code admin} is not a device owner or a profile owner of an
13048      *      organization-owned managed profile, or the caller is not permitted to set this policy
13049      * @throws IllegalArgumentException if the policy type or maintenance window is not valid.
13050      * @throws SystemUpdatePolicy.ValidationFailedException if the policy's freeze period does not
13051      *             meet the requirement.
13052      * @see SystemUpdatePolicy
13053      * @see SystemUpdatePolicy#setFreezePeriods(List)
13054      */
13055     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SYSTEM_UPDATES, conditional = true)
setSystemUpdatePolicy(@onNull ComponentName admin, SystemUpdatePolicy policy)13056     public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
13057         throwIfParentInstance("setSystemUpdatePolicy");
13058         if (mService != null) {
13059             try {
13060                 mService.setSystemUpdatePolicy(admin, mContext.getPackageName(), policy);
13061             } catch (RemoteException re) {
13062                 throw re.rethrowFromSystemServer();
13063             }
13064         }
13065     }
13066 
13067     /**
13068      * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
13069      *
13070      * @return The current policy object, or {@code null} if no policy is set.
13071      */
getSystemUpdatePolicy()13072     public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
13073         throwIfParentInstance("getSystemUpdatePolicy");
13074         if (mService != null) {
13075             try {
13076                 return mService.getSystemUpdatePolicy();
13077             } catch (RemoteException re) {
13078                 throw re.rethrowFromSystemServer();
13079             }
13080         }
13081         return null;
13082     }
13083 
13084     /**
13085      * Reset record of previous system update freeze period the device went through.
13086      * @hide
13087      */
13088     @TestApi
13089     @RequiresPermission(android.Manifest.permission.CLEAR_FREEZE_PERIOD)
clearSystemUpdatePolicyFreezePeriodRecord()13090     public void clearSystemUpdatePolicyFreezePeriodRecord() {
13091         throwIfParentInstance("clearSystemUpdatePolicyFreezePeriodRecord");
13092         if (mService == null) {
13093             return;
13094         }
13095         try {
13096             mService.clearSystemUpdatePolicyFreezePeriodRecord();
13097         } catch (RemoteException re) {
13098             throw re.rethrowFromSystemServer();
13099         }
13100     }
13101 
13102     /**
13103      * Called by a device owner or profile owner of secondary users that is affiliated with the
13104      * device to disable the keyguard altogether.
13105      * <p>
13106      * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
13107      * type. However, this call has no effect if a password, pin or pattern is currently set. If a
13108      * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
13109      * disabled.
13110      *
13111      * <p>
13112      * As of {@link android.os.Build.VERSION_CODES#P}, this call also dismisses the
13113      * keyguard if it is currently shown.
13114      *
13115      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13116      * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
13117      * @return {@code false} if attempting to disable the keyguard while a lock password was in
13118      *         place. {@code true} otherwise.
13119      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
13120      * secondary user that is affiliated with the device.
13121      * @see #isAffiliatedUser
13122      * @see #getSecondaryUsers
13123      */
setKeyguardDisabled(@onNull ComponentName admin, boolean disabled)13124     public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
13125         throwIfParentInstance("setKeyguardDisabled");
13126         try {
13127             return mService.setKeyguardDisabled(admin, disabled);
13128         } catch (RemoteException re) {
13129             throw re.rethrowFromSystemServer();
13130         }
13131     }
13132 
13133     /**
13134      * Called by device owner or profile owner of secondary users that is affiliated with the
13135      * device to disable the status bar. Disabling the status bar blocks notifications and quick
13136      * settings.
13137      * <p>
13138      * <strong>Note:</strong> This method has no effect for LockTask mode. The behavior of the
13139      * status bar in LockTask mode can be configured with
13140      * {@link #setLockTaskFeatures(ComponentName, int)}. Calls to this method when the device is in
13141      * LockTask mode will be registered, but will only take effect when the device leaves LockTask
13142      * mode.
13143      *
13144      * <p>This policy does not have any effect while on the lock screen, where the status bar will
13145      * not be disabled. Using LockTask instead of this method is recommended.
13146      *
13147      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
13148      *              caller is not a device admin.
13149      * @param disabled {@code true} disables the status bar, {@code false} reenables it.
13150      * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
13151      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
13152      * secondary user that is affiliated with the device.
13153      * @see #isAffiliatedUser
13154      * @see #getSecondaryUsers
13155      */
13156     @RequiresPermission(value = MANAGE_DEVICE_POLICY_STATUS_BAR, conditional = true)
setStatusBarDisabled(@ullable ComponentName admin, boolean disabled)13157     public boolean setStatusBarDisabled(@Nullable ComponentName admin, boolean disabled) {
13158         throwIfParentInstance("setStatusBarDisabled");
13159         try {
13160             return mService.setStatusBarDisabled(admin, mContext.getPackageName(), disabled);
13161         } catch (RemoteException re) {
13162             throw re.rethrowFromSystemServer();
13163         }
13164     }
13165 
13166     /**
13167      * Returns whether the status bar is disabled/enabled, see {@link #setStatusBarDisabled}.
13168      *
13169      * <p>Callable by device owner or profile owner of secondary users that is affiliated with the
13170      * device owner.
13171      *
13172      * <p>This policy has no effect in LockTask mode. The behavior of the
13173      * status bar in LockTask mode can be configured with
13174      * {@link #setLockTaskFeatures(ComponentName, int)}.
13175      *
13176      * <p>This policy also does not have any effect while on the lock screen, where the status bar
13177      * will not be disabled.
13178      *
13179      * @throws SecurityException if the caller is not the device owner, or a profile owner of
13180      * secondary user that is affiliated with the device.
13181      * @see #isAffiliatedUser
13182      * @see #getSecondaryUsers
13183      */
isStatusBarDisabled()13184     public boolean isStatusBarDisabled() {
13185         throwIfParentInstance("isStatusBarDisabled");
13186         try {
13187             return mService.isStatusBarDisabled(mContext.getPackageName());
13188         } catch (RemoteException re) {
13189             throw re.rethrowFromSystemServer();
13190         }
13191     }
13192 
13193     /**
13194      * Called by the system update service to notify device and profile owners of pending system
13195      * updates.
13196      *
13197      * This method should only be used when it is unknown whether the pending system
13198      * update is a security patch. Otherwise, use
13199      * {@link #notifyPendingSystemUpdate(long, boolean)}.
13200      *
13201      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
13202      *         indicating when the current pending update was first available. {@code -1} if no
13203      *         update is available.
13204      * @see #notifyPendingSystemUpdate(long, boolean)
13205      * @hide
13206      */
13207     @SystemApi
13208     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime)13209     public void notifyPendingSystemUpdate(long updateReceivedTime) {
13210         throwIfParentInstance("notifyPendingSystemUpdate");
13211         if (mService != null) {
13212             try {
13213                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime));
13214             } catch (RemoteException re) {
13215                 throw re.rethrowFromSystemServer();
13216             }
13217         }
13218     }
13219 
13220     /**
13221      * Called by the system update service to notify device and profile owners of pending system
13222      * updates.
13223      *
13224      * This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
13225      * when it is known whether the pending system update is a security patch.
13226      *
13227      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
13228      *         indicating when the current pending update was first available. {@code -1} if no
13229      *         update is available.
13230      * @param isSecurityPatch {@code true} if this system update is purely a security patch;
13231      *         {@code false} if not.
13232      * @see #notifyPendingSystemUpdate(long)
13233      * @hide
13234      */
13235     @SystemApi
13236     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch)13237     public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) {
13238         throwIfParentInstance("notifyPendingSystemUpdate");
13239         if (mService != null) {
13240             try {
13241                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime,
13242                         isSecurityPatch));
13243             } catch (RemoteException re) {
13244                 throw re.rethrowFromSystemServer();
13245             }
13246         }
13247     }
13248 
13249     /**
13250      * Called by device or profile owners to get information about a pending system update.
13251      *
13252      * @param admin Which profile or device owner this request is associated with.
13253      * @return Information about a pending system update or {@code null} if no update pending.
13254      * @throws SecurityException if {@code admin} is not a device or profile owner.
13255      * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long)
13256      */
getPendingSystemUpdate(@onNull ComponentName admin)13257     public @Nullable SystemUpdateInfo getPendingSystemUpdate(@NonNull ComponentName admin) {
13258         throwIfParentInstance("getPendingSystemUpdate");
13259         try {
13260             return mService.getPendingSystemUpdate(admin);
13261         } catch (RemoteException re) {
13262             throw re.rethrowFromSystemServer();
13263         }
13264     }
13265 
13266     /**
13267      * Set the default response for future runtime permission requests by applications. This
13268      * function can be called by a device owner, profile owner, or by a delegate given the
13269      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
13270      * The policy can allow for normal operation which prompts the user to grant a permission, or
13271      * can allow automatic granting or denying of runtime permission requests by an application.
13272      * This also applies to new permissions declared by app updates. When a permission is denied or
13273      * granted this way, the effect is equivalent to setting the permission * grant state via
13274      * {@link #setPermissionGrantState}.
13275      * <p/>
13276      * As this policy only acts on runtime permission requests, it only applies to applications
13277      * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
13278      *
13279      * <p>
13280      * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, an auto-grant
13281      * policy will not apply to certain sensors-related permissions on some configurations.
13282      * See {@link #setPermissionGrantState(ComponentName, String, String, int)} for the list of
13283      * permissions affected, and the behavior change for managed profiles and fully-managed
13284      * devices.
13285      *
13286      * @param admin Which profile or device owner this request is associated with.
13287      * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
13288      *            {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
13289      * @throws SecurityException if {@code admin} is not a device or profile owner.
13290      * @see #setPermissionGrantState
13291      * @see #setDelegatedScopes
13292      * @see #DELEGATION_PERMISSION_GRANT
13293      */
setPermissionPolicy(@onNull ComponentName admin, int policy)13294     public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
13295         throwIfParentInstance("setPermissionPolicy");
13296         try {
13297             mService.setPermissionPolicy(admin, mContext.getPackageName(), policy);
13298         } catch (RemoteException re) {
13299             throw re.rethrowFromSystemServer();
13300         }
13301     }
13302 
13303     /**
13304      * Returns the current runtime permission policy set by the device or profile owner. The
13305      * default is {@link #PERMISSION_POLICY_PROMPT}.
13306      *
13307      * @param admin Which profile or device owner this request is associated with.
13308      * @return the current policy for future permission requests.
13309      */
getPermissionPolicy(ComponentName admin)13310     public int getPermissionPolicy(ComponentName admin) {
13311         throwIfParentInstance("getPermissionPolicy");
13312         try {
13313             return mService.getPermissionPolicy(admin);
13314         } catch (RemoteException re) {
13315             throw re.rethrowFromSystemServer();
13316         }
13317     }
13318 
13319     /**
13320      * Sets the grant state of a runtime permission for a specific application. The state can be
13321      * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
13322      * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
13323      * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
13324      * the permission is granted and the user cannot manage it through the UI. This method can only
13325      * be called by a profile owner, device owner, or a delegate given the
13326      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
13327      * <p/>
13328      * Note that user cannot manage other permissions in the affected group through the UI
13329      * either and their granted state will be kept as the current value. Thus, it's recommended that
13330      * you set the grant state of all the permissions in the affected group.
13331      * <p/>
13332      * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
13333      * the permission. It retains the previous grant, if any.
13334      * <p/>
13335      * Device admins with a {@code targetSdkVersion} &lt; {@link android.os.Build.VERSION_CODES#Q}
13336      * cannot grant and revoke permissions for applications built with a {@code targetSdkVersion}
13337      * &lt; {@link android.os.Build.VERSION_CODES#M}.
13338      * <p/>
13339      * Admins with a {@code targetSdkVersion} &ge; {@link android.os.Build.VERSION_CODES#Q} can
13340      * grant and revoke permissions of all apps. Similar to the user revoking a permission from a
13341      * application built with a {@code targetSdkVersion} &lt;
13342      * {@link android.os.Build.VERSION_CODES#M} the app-op matching the permission is set to
13343      * {@link android.app.AppOpsManager#MODE_IGNORED}, but the permission stays granted.
13344      * <p>
13345      * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, control over
13346      * the following, sensors-related, permissions is restricted:
13347      * <ul>
13348      *    <li>Manifest.permission.ACCESS_FINE_LOCATION</li>
13349      *    <li>Manifest.permission.ACCESS_BACKGROUND_LOCATION</li>
13350      *    <li>Manifest.permission.ACCESS_COARSE_LOCATION</li>
13351      *    <li>Manifest.permission.CAMERA</li>
13352      *    <li>Manifest.permission.RECORD_AUDIO</li>
13353      *    <li>Manifest.permission.RECORD_BACKGROUND_AUDIO</li>
13354      *    <li>Manifest.permission.ACTIVITY_RECOGNITION</li>
13355      *    <li>Manifest.permission.BODY_SENSORS</li>
13356      * </ul>
13357      * <p>
13358      * A profile owner may not grant these permissions (i.e. call this method with any of the
13359      * permissions listed above and {@code grantState} of {@code #PERMISSION_GRANT_STATE_GRANTED}),
13360      * but may deny them.
13361      * <p>
13362      * A device owner, by default, may continue granting these permissions. However, for increased
13363      * user control, the admin may opt out of controlling grants for these permissions by including
13364      * {@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT} in the provisioning parameters.
13365      * In that case the device owner's control will be limited do denying these permissions.
13366      * <p>
13367      * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, control over
13368      * the following permissions are restricted for managed profile owners:
13369      * <ul>
13370      *    <li>Manifest.permission.READ_SMS</li>
13371      * </ul>
13372      * <p>
13373      * A managed profile owner may not grant these permissions (i.e. call this method with any of
13374      * the permissions listed above and {@code grantState} of
13375      * {@code #PERMISSION_GRANT_STATE_GRANTED}), but may deny them.
13376      * <p>
13377      * Attempts by the admin to grant these permissions, when the admin is restricted from doing
13378      * so, will be silently ignored (no exception will be thrown).
13379      *
13380      * Control over the following permissions are restricted for managed profile owners:
13381      * <ul>
13382      *  <li>Manifest.permission.READ_SMS</li>
13383      * </ul>
13384      * <p>
13385      * A managed profile owner may not grant these permissions (i.e. call this method with any of
13386      * the permissions listed above and {@code grantState} of
13387      * {@code #PERMISSION_GRANT_STATE_GRANTED}), but may deny them.
13388      *
13389      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
13390      *               caller is not a device admin.
13391      * @param packageName The application to grant or revoke a permission to.
13392      * @param permission The permission to grant or revoke.
13393      * @param grantState The permission grant state which is one of
13394      *            {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
13395      *            {@link #PERMISSION_GRANT_STATE_GRANTED},
13396      * @return whether the permission was successfully granted or revoked.
13397      * @throws SecurityException if {@code admin} is not a device or profile owner.
13398      * @see #PERMISSION_GRANT_STATE_DENIED
13399      * @see #PERMISSION_GRANT_STATE_DEFAULT
13400      * @see #PERMISSION_GRANT_STATE_GRANTED
13401      * @see #setDelegatedScopes
13402      * @see #DELEGATION_PERMISSION_GRANT
13403      */
13404     @RequiresPermission(value = MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS, conditional = true)
13405     @SupportsCoexistence
setPermissionGrantState(@ullable ComponentName admin, @NonNull String packageName, @NonNull String permission, @PermissionGrantState int grantState)13406     public boolean setPermissionGrantState(@Nullable ComponentName admin,
13407             @NonNull String packageName, @NonNull String permission,
13408             @PermissionGrantState int grantState) {
13409         throwIfParentInstance("setPermissionGrantState");
13410         try {
13411             CompletableFuture<Boolean> result = new CompletableFuture<>();
13412 
13413             mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName,
13414                     permission, grantState, new RemoteCallback((b) -> result.complete(b != null)));
13415 
13416             // Timeout
13417             BackgroundThread.getHandler().sendMessageDelayed(
13418                     obtainMessage(CompletableFuture::complete, result, false),
13419                     20_000);
13420 
13421             return result.get();
13422         } catch (RemoteException re) {
13423             throw re.rethrowFromSystemServer();
13424         } catch (InterruptedException | ExecutionException e) {
13425             throw new RuntimeException(e);
13426         }
13427     }
13428 
13429     /**
13430      * Returns the current grant state of a runtime permission for a specific application. This
13431      * function can be called by a device owner, profile owner, or by a delegate given the
13432      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
13433      *
13434      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
13435      *               caller is not a device admin.
13436      * @param packageName The application to check the grant state for.
13437      * @param permission The permission to check for.
13438      * @return the current grant state specified by device policy. If admins have not set a grant
13439      *         has not set a grant state, the return value is
13440      *         {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
13441      *         permission is currently granted for the package.
13442      *         <p/>
13443      *         If a grant state was set by the profile or device owner, then the return value will
13444      *         be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
13445      *         {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
13446      *         currently denied or granted.
13447      * @throws SecurityException if {@code admin} is not a device or profile owner.
13448      * @see #setPermissionGrantState(ComponentName, String, String, int)
13449      * @see PackageManager#checkPermission(String, String)
13450      * @see #setDelegatedScopes
13451      * @see #DELEGATION_PERMISSION_GRANT
13452      */
13453     @RequiresPermission(value = MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS, conditional = true)
getPermissionGrantState(@ullable ComponentName admin, @NonNull String packageName, @NonNull String permission)13454     public @PermissionGrantState int getPermissionGrantState(@Nullable ComponentName admin,
13455             @NonNull String packageName, @NonNull String permission) {
13456         throwIfParentInstance("getPermissionGrantState");
13457         try {
13458             return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName,
13459                     permission);
13460         } catch (RemoteException re) {
13461             throw re.rethrowFromSystemServer();
13462         }
13463     }
13464 
13465     /**
13466      * Returns whether it is possible for the caller to initiate provisioning of a managed profile
13467      * or device, setting itself as the device or profile owner.
13468      *
13469      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
13470      * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
13471      * @return whether provisioning a managed profile or device is possible.
13472      * @throws IllegalArgumentException if the supplied action is not valid.
13473      */
isProvisioningAllowed(@onNull String action)13474     public boolean isProvisioningAllowed(@NonNull String action) {
13475         throwIfParentInstance("isProvisioningAllowed");
13476         try {
13477             return mService.isProvisioningAllowed(action, mContext.getPackageName());
13478         } catch (RemoteException re) {
13479             throw re.rethrowFromSystemServer();
13480         }
13481     }
13482 
13483     /**
13484      * Checks whether it is possible to initiate provisioning a managed device,
13485      * profile or user, setting the given package as owner.
13486      *
13487      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
13488      *        {@link #ACTION_PROVISION_MANAGED_PROFILE}
13489      * @param packageName The package of the component that would be set as device, user, or profile
13490      *        owner.
13491      * @return An int constant value indicating whether provisioning is allowed.
13492      * @hide
13493      */
13494     @SystemApi
13495     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
13496     @ProvisioningPrecondition
checkProvisioningPrecondition( @onNull String action, @NonNull String packageName)13497     public int checkProvisioningPrecondition(
13498             @NonNull String action, @NonNull String packageName) {
13499         try {
13500             return mService.checkProvisioningPrecondition(action, packageName);
13501         } catch (RemoteException re) {
13502             throw re.rethrowFromSystemServer();
13503         }
13504     }
13505 
13506     /**
13507      * Return if this user is a managed profile of another user. An admin can become the profile
13508      * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
13509      * user with {@link #createAndManageUser}
13510      * @param admin Which profile owner this request is associated with.
13511      * @return if this user is a managed profile of another user.
13512      */
isManagedProfile(@onNull ComponentName admin)13513     public boolean isManagedProfile(@NonNull ComponentName admin) {
13514         throwIfParentInstance("isManagedProfile");
13515         try {
13516             return mService.isManagedProfile(admin);
13517         } catch (RemoteException re) {
13518             throw re.rethrowFromSystemServer();
13519         }
13520     }
13521 
13522     /**
13523      * Called by a device owner or profile owner on organization-owned device to get the MAC
13524      * address of the Wi-Fi device.
13525      *
13526      * NOTE: The MAC address returned here should only be used for inventory management and is
13527      * not likely to be the MAC address used by the device to connect to Wi-Fi networks: MAC
13528      * addresses used for scanning and connecting to Wi-Fi networks are randomized by default.
13529      * To get the randomized MAC address used, call
13530      * {@link android.net.wifi.WifiConfiguration#getRandomizedMacAddress}.
13531      *
13532      * @param admin Which admin this request is associated with. Null if the caller is not a device
13533      *              admin
13534      * @return the MAC address of the Wi-Fi device, or null when the information is not available.
13535      *         (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
13536      *         <p>
13537      *         The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
13538      * @throws SecurityException if {@code admin} is not permitted to get wifi mac addresses
13539      */
13540 //    @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true)
getWifiMacAddress(@ullable ComponentName admin)13541     public @Nullable String getWifiMacAddress(@Nullable ComponentName admin) {
13542         throwIfParentInstance("getWifiMacAddress");
13543         try {
13544             return mService.getWifiMacAddress(admin, mContext.getPackageName());
13545         } catch (RemoteException re) {
13546             throw re.rethrowFromSystemServer();
13547         }
13548     }
13549 
13550     /**
13551      * Called by device owner to reboot the device. If there is an ongoing call on the device,
13552      * throws an {@link IllegalStateException}.
13553      * @param admin Which device owner the request is associated with.
13554      * @throws IllegalStateException if device has an ongoing call.
13555      * @throws SecurityException if {@code admin} is not a device owner.
13556      * @see TelephonyManager#CALL_STATE_IDLE
13557      */
reboot(@onNull ComponentName admin)13558     public void reboot(@NonNull ComponentName admin) {
13559         throwIfParentInstance("reboot");
13560         try {
13561             mService.reboot(admin);
13562         } catch (RemoteException re) {
13563             throw re.rethrowFromSystemServer();
13564         }
13565     }
13566 
13567     /**
13568      * Called by a device admin to set the short support message. This will be displayed to the user
13569      * in settings screens where functionality has been disabled by the admin. The message should be
13570      * limited to a short statement such as "This setting is disabled by your administrator. Contact
13571      * someone@example.com for support." If the message is longer than 200 characters it may be
13572      * truncated.
13573      * <p>
13574      * If the short support message needs to be localized, it is the responsibility of the
13575      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
13576      * and set a new version of this string accordingly.
13577      *
13578      * @see #setLongSupportMessage
13579      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
13580      *               caller is not a device admin.
13581      * @param message Short message to be displayed to the user in settings or null to clear the
13582      *            existing message.
13583      * @throws SecurityException if {@code admin} is not an active administrator.
13584      */
13585     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE, conditional = true)
setShortSupportMessage(@ullable ComponentName admin, @Nullable CharSequence message)13586     public void setShortSupportMessage(@Nullable ComponentName admin,
13587             @Nullable CharSequence message) {
13588         throwIfParentInstance("setShortSupportMessage");
13589         if (mService != null) {
13590             try {
13591                 mService.setShortSupportMessage(admin, mContext.getPackageName(), message);
13592             } catch (RemoteException e) {
13593                 throw e.rethrowFromSystemServer();
13594             }
13595         }
13596     }
13597 
13598     /**
13599      * Called by a device admin or holder of the permission
13600      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE} to get the short
13601      * support message.
13602      *
13603      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
13604      *               caller is not a device admin.
13605      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
13606      *         null if no message has been set.
13607      * @throws SecurityException if {@code admin} is not an active administrator and not a holder of
13608      * the permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE}..
13609      */
13610     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE, conditional = true)
getShortSupportMessage(@ullable ComponentName admin)13611     public CharSequence getShortSupportMessage(@Nullable ComponentName admin) {
13612         throwIfParentInstance("getShortSupportMessage");
13613         if (mService != null) {
13614             try {
13615                 return mService.getShortSupportMessage(admin, mContext.getPackageName());
13616             } catch (RemoteException e) {
13617                 throw e.rethrowFromSystemServer();
13618             }
13619         }
13620         return null;
13621     }
13622 
13623     /**
13624      * Called by a device admin to set the long support message. This will be displayed to the user
13625      * in the device administrators settings screen. If the message is longer than 20000 characters
13626      * it may be truncated.
13627      * <p>
13628      * If the long support message needs to be localized, it is the responsibility of the
13629      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
13630      * and set a new version of this string accordingly.
13631      *
13632      * @see #setShortSupportMessage
13633      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13634      * @param message Long message to be displayed to the user in settings or null to clear the
13635      *            existing message.
13636      * @throws SecurityException if {@code admin} is not an active administrator.
13637      */
setLongSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)13638     public void setLongSupportMessage(@NonNull ComponentName admin,
13639             @Nullable CharSequence message) {
13640         throwIfParentInstance("setLongSupportMessage");
13641         if (mService != null) {
13642             try {
13643                 mService.setLongSupportMessage(admin, message);
13644             } catch (RemoteException e) {
13645                 throw e.rethrowFromSystemServer();
13646             }
13647         }
13648     }
13649 
13650     /**
13651      * Called by a device admin to get the long support message.
13652      *
13653      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13654      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
13655      *         null if no message has been set.
13656      * @throws SecurityException if {@code admin} is not an active administrator.
13657      */
getLongSupportMessage(@onNull ComponentName admin)13658     public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
13659         throwIfParentInstance("getLongSupportMessage");
13660         if (mService != null) {
13661             try {
13662                 return mService.getLongSupportMessage(admin);
13663             } catch (RemoteException e) {
13664                 throw e.rethrowFromSystemServer();
13665             }
13666         }
13667         return null;
13668     }
13669 
13670     /**
13671      * Called by the system to get the short support message.
13672      *
13673      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13674      * @param userHandle user id the admin is running as.
13675      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
13676      *
13677      * @hide
13678      */
getShortSupportMessageForUser(@onNull ComponentName admin, int userHandle)13679     public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
13680             int userHandle) {
13681         if (mService != null) {
13682             try {
13683                 return mService.getShortSupportMessageForUser(admin, userHandle);
13684             } catch (RemoteException e) {
13685                 throw e.rethrowFromSystemServer();
13686             }
13687         }
13688         return null;
13689     }
13690 
13691 
13692     /**
13693      * Called by the system to get the long support message.
13694      *
13695      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13696      * @param userHandle user id the admin is running as.
13697      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
13698      *
13699      * @hide
13700      */
getLongSupportMessageForUser( @onNull ComponentName admin, int userHandle)13701     public @Nullable CharSequence getLongSupportMessageForUser(
13702             @NonNull ComponentName admin, int userHandle) {
13703         if (mService != null) {
13704             try {
13705                 return mService.getLongSupportMessageForUser(admin, userHandle);
13706             } catch (RemoteException e) {
13707                 throw e.rethrowFromSystemServer();
13708             }
13709         }
13710         return null;
13711     }
13712 
13713     /**
13714      * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
13715      * whose calls act on the parent profile.
13716      *
13717      * <p>The following methods are supported for the parent instance, all other methods will
13718      * throw a SecurityException when called on the parent instance:
13719      * <ul>
13720      * <li>{@link #getPasswordQuality}</li>
13721      * <li>{@link #setPasswordQuality}</li>
13722      * <li>{@link #getPasswordMinimumLength}</li>
13723      * <li>{@link #setPasswordMinimumLength}</li>
13724      * <li>{@link #getPasswordMinimumUpperCase}</li>
13725      * <li>{@link #setPasswordMinimumUpperCase}</li>
13726      * <li>{@link #getPasswordMinimumLowerCase}</li>
13727      * <li>{@link #setPasswordMinimumLowerCase}</li>
13728      * <li>{@link #getPasswordMinimumLetters}</li>
13729      * <li>{@link #setPasswordMinimumLetters}</li>
13730      * <li>{@link #getPasswordMinimumNumeric}</li>
13731      * <li>{@link #setPasswordMinimumNumeric}</li>
13732      * <li>{@link #getPasswordMinimumSymbols}</li>
13733      * <li>{@link #setPasswordMinimumSymbols}</li>
13734      * <li>{@link #getPasswordMinimumNonLetter}</li>
13735      * <li>{@link #setPasswordMinimumNonLetter}</li>
13736      * <li>{@link #getPasswordHistoryLength}</li>
13737      * <li>{@link #setPasswordHistoryLength}</li>
13738      * <li>{@link #getPasswordExpirationTimeout}</li>
13739      * <li>{@link #setPasswordExpirationTimeout}</li>
13740      * <li>{@link #getPasswordExpiration}</li>
13741      * <li>{@link #getPasswordMaximumLength}</li>
13742      * <li>{@link #isActivePasswordSufficient}</li>
13743      * <li>{@link #getCurrentFailedPasswordAttempts}</li>
13744      * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
13745      * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
13746      * <li>{@link #getMaximumTimeToLock}</li>
13747      * <li>{@link #setMaximumTimeToLock}</li>
13748      * <li>{@link #lockNow}</li>
13749      * <li>{@link #getKeyguardDisabledFeatures}</li>
13750      * <li>{@link #setKeyguardDisabledFeatures}</li>
13751      * <li>{@link #getTrustAgentConfiguration}</li>
13752      * <li>{@link #setTrustAgentConfiguration}</li>
13753      * <li>{@link #getRequiredStrongAuthTimeout}</li>
13754      * <li>{@link #setRequiredStrongAuthTimeout}</li>
13755      * <li>{@link #getAccountTypesWithManagementDisabled}</li>
13756      * <li>{@link #setRequiredPasswordComplexity(int)} </li>
13757      * <li>{@link #getRequiredPasswordComplexity()}</li>
13758      * </ul>
13759      * <p>
13760      * The following methods are supported for the parent instance but can only be called by the
13761      * profile owner of a managed profile that was created during the device provisioning flow:
13762      * <ul>
13763      * <li>{@link #getPasswordComplexity}</li>
13764      * <li>{@link #setCameraDisabled}</li>
13765      * <li>{@link #getCameraDisabled}</li>
13766      * <li>{@link #setAccountManagementDisabled(ComponentName, String, boolean)}</li>
13767      * <li>{@link #setPermittedInputMethods}</li>
13768      * <li>{@link #getPermittedInputMethods}</li>
13769      * </ul>
13770      *
13771      * <p>The following methods can be called by the profile owner of a managed profile
13772      * on an organization-owned device:
13773      * <ul>
13774      * <li>{@link #wipeData}</li>
13775      * </ul>
13776      *
13777      * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
13778      * @throws SecurityException if {@code admin} is not a profile owner.
13779      */
getParentProfileInstance(@onNull ComponentName admin)13780     public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
13781         throwIfParentInstance("getParentProfileInstance");
13782         try {
13783             if (!mService.isManagedProfile(admin)) {
13784                 throw new SecurityException("The current user does not have a parent profile.");
13785             }
13786             return new DevicePolicyManager(mContext, mService, true);
13787         } catch (RemoteException e) {
13788             throw e.rethrowFromSystemServer();
13789         }
13790     }
13791 
13792     /**
13793      * Called by device owner or a profile owner of an organization-owned managed profile to
13794      * control the security logging feature.
13795      *
13796      * <p> Security logs contain various information intended for security auditing purposes.
13797      * When security logging is enabled by any app other than the device owner, certain security
13798      * logs are not visible (for example personal app launch events) or they will be redacted
13799      * (for example, details of the physical volume mount events).
13800      * Please see {@link SecurityEvent} for details.
13801      *
13802      * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there
13803      * are unaffiliated secondary users or profiles on the device, regardless of whether the
13804      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
13805      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
13806      * new users as soon as possible after provisioning via {@link #setAffiliationIds}. Non device
13807      * owners are not subject to this restriction since all
13808      * privacy-sensitive events happening outside the managed profile would have been redacted
13809      * already.
13810      *
13811      * @param admin Which device admin this request is associated with, or {@code null}
13812      *              if called by a delegated app.
13813      * @param enabled whether security logging should be enabled or not.
13814      * @throws SecurityException if the caller is not permitted to control security logging.
13815      * @see #setAffiliationIds
13816      * @see #retrieveSecurityLogs
13817      */
13818     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SECURITY_LOGGING, conditional = true)
setSecurityLoggingEnabled(@ullable ComponentName admin, boolean enabled)13819     public void setSecurityLoggingEnabled(@Nullable ComponentName admin, boolean enabled) {
13820         throwIfParentInstance("setSecurityLoggingEnabled");
13821         try {
13822             mService.setSecurityLoggingEnabled(admin, mContext.getPackageName(), enabled);
13823         } catch (RemoteException re) {
13824             throw re.rethrowFromSystemServer();
13825         }
13826     }
13827 
13828     /**
13829      * Return whether security logging is enabled or not by the admin.
13830      *
13831      * <p>Can only be called by the device owner or a profile owner of an organization-owned
13832      * managed profile, otherwise a {@link SecurityException} will be thrown.
13833      *
13834      * @param admin Which device admin this request is associated with. Null if the caller is not
13835      *              a device admin
13836      * @return {@code true} if security logging is enabled, {@code false} otherwise.
13837      * @throws SecurityException if the caller is not allowed to control security logging.
13838      */
13839     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SECURITY_LOGGING, conditional = true)
isSecurityLoggingEnabled(@ullable ComponentName admin)13840     public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) {
13841         throwIfParentInstance("isSecurityLoggingEnabled");
13842         try {
13843             return mService.isSecurityLoggingEnabled(admin, mContext.getPackageName());
13844         } catch (RemoteException re) {
13845             throw re.rethrowFromSystemServer();
13846         }
13847     }
13848 
13849     /**
13850      * Called by device owner or profile owner of an organization-owned managed profile to retrieve
13851      * all new security logging entries since the last call to this API after device boots.
13852      *
13853      * <p> Access to the logs is rate limited and it will only return new logs after the admin has
13854      * been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
13855      *
13856      * <p> When called by a device owner, if there is any other user or profile on the device,
13857      * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown.
13858      * See {@link #isAffiliatedUser}.
13859      *
13860      * @param admin Which device admin this request is associated with, or {@code null}
13861      *              if called by a delegated app.
13862      * @return the new batch of security logs which is a list of {@link SecurityEvent},
13863      * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
13864      * @throws SecurityException if the caller is not allowed to access security logging,
13865      * or there is at least one profile or secondary user that is not affiliated with the device.
13866      * @see #isAffiliatedUser
13867      * @see DeviceAdminReceiver#onSecurityLogsAvailable
13868      */
13869     @SuppressLint("NullableCollection")
13870     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SECURITY_LOGGING, conditional = true)
retrieveSecurityLogs(@ullable ComponentName admin)13871     public @Nullable List<SecurityEvent> retrieveSecurityLogs(@Nullable ComponentName admin) {
13872         throwIfParentInstance("retrieveSecurityLogs");
13873         try {
13874             ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(
13875                     admin, mContext.getPackageName());
13876             if (list != null) {
13877                 return list.getList();
13878             } else {
13879                 // Rate limit exceeded.
13880                 return null;
13881             }
13882         } catch (RemoteException re) {
13883             throw re.rethrowFromSystemServer();
13884         }
13885     }
13886 
13887     /**
13888      * Makes all accumulated network logs available to DPC in a new batch.
13889      * If throttled, returns time to wait in milliseconds, otherwise 0.
13890      * @hide
13891      */
13892     @TestApi
13893     @RequiresPermission(android.Manifest.permission.FORCE_DEVICE_POLICY_MANAGER_LOGS)
forceNetworkLogs()13894     public long forceNetworkLogs() {
13895         if (mService == null) {
13896             return -1;
13897         }
13898         try {
13899             return mService.forceNetworkLogs();
13900         } catch (RemoteException re) {
13901             throw re.rethrowFromSystemServer();
13902         }
13903     }
13904 
13905     /**
13906      * Forces a batch of security logs to be fetched from logd and makes it available for DPC.
13907      * If throttled, returns time to wait in milliseconds, otherwise 0.
13908      * @hide
13909      */
13910     @TestApi
13911     @RequiresPermission(android.Manifest.permission.FORCE_DEVICE_POLICY_MANAGER_LOGS)
forceSecurityLogs()13912     public long forceSecurityLogs() {
13913         if (mService == null) {
13914             return 0;
13915         }
13916         try {
13917             return mService.forceSecurityLogs();
13918         } catch (RemoteException re) {
13919             throw re.rethrowFromSystemServer();
13920         }
13921     }
13922 
13923     /**
13924      * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
13925      * profile.
13926      *
13927      * @hide
13928      */
getParentProfileInstance(UserInfo uInfo)13929     public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
13930         mContext.checkSelfPermission(
13931                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
13932         if (!uInfo.isManagedProfile()) {
13933             throw new SecurityException("The user " + uInfo.id
13934                     + " does not have a parent profile.");
13935         }
13936         return new DevicePolicyManager(mContext, mService, true);
13937     }
13938 
13939     /**
13940      * Called by a device or profile owner to restrict packages from using metered data.
13941      *
13942      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
13943      * @param packageNames the list of package names to be restricted.
13944      * @return a list of package names which could not be restricted.
13945      * @throws SecurityException if {@code admin} is not a device or profile owner.
13946      */
setMeteredDataDisabledPackages(@onNull ComponentName admin, @NonNull List<String> packageNames)13947     public @NonNull List<String> setMeteredDataDisabledPackages(@NonNull ComponentName admin,
13948             @NonNull List<String> packageNames) {
13949         throwIfParentInstance("setMeteredDataDisabled");
13950         if (mService != null) {
13951             try {
13952                 return mService.setMeteredDataDisabledPackages(admin, packageNames);
13953             } catch (RemoteException re) {
13954                 throw re.rethrowFromSystemServer();
13955             }
13956         }
13957         return packageNames;
13958     }
13959 
13960     /**
13961      * Called by a device or profile owner to retrieve the list of packages which are restricted
13962      * by the admin from using metered data.
13963      *
13964      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
13965      * @return the list of restricted package names.
13966      * @throws SecurityException if {@code admin} is not a device or profile owner.
13967      */
getMeteredDataDisabledPackages(@onNull ComponentName admin)13968     public @NonNull List<String> getMeteredDataDisabledPackages(@NonNull ComponentName admin) {
13969         throwIfParentInstance("getMeteredDataDisabled");
13970         if (mService != null) {
13971             try {
13972                 return mService.getMeteredDataDisabledPackages(admin);
13973             } catch (RemoteException re) {
13974                 throw re.rethrowFromSystemServer();
13975             }
13976         }
13977         return new ArrayList<>();
13978     }
13979 
13980     /**
13981      * Called by the system to check if a package is restricted from using metered data
13982      * by {@param admin}.
13983      *
13984      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
13985      * @param packageName the package whose restricted status is needed.
13986      * @param userId the user to which {@param packageName} belongs.
13987      * @return {@code true} if the package is restricted by admin, otherwise {@code false}
13988      * @throws SecurityException if the caller doesn't run with {@link Process#SYSTEM_UID}
13989      * @hide
13990      */
isMeteredDataDisabledPackageForUser(@onNull ComponentName admin, String packageName, @UserIdInt int userId)13991     public boolean isMeteredDataDisabledPackageForUser(@NonNull ComponentName admin,
13992             String packageName, @UserIdInt int userId) {
13993         throwIfParentInstance("getMeteredDataDisabledForUser");
13994         if (mService != null) {
13995             try {
13996                 return mService.isMeteredDataDisabledPackageForUser(admin, packageName, userId);
13997             } catch (RemoteException re) {
13998                 throw re.rethrowFromSystemServer();
13999             }
14000         }
14001         return false;
14002     }
14003 
14004     /**
14005      * Called by device owner or profile owner of an organization-owned managed profile to retrieve
14006      * device logs from before the device's last reboot.
14007      * <p>
14008      * <strong> This API is not supported on all devices. Calling this API on unsupported devices
14009      * will result in {@code null} being returned. The device logs are retrieved from a RAM region
14010      * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
14011      * about data corruption when parsing. </strong>
14012      *
14013      * <p> When called by a device owner, if there is any other user or profile on the device,
14014      * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown.
14015      * See {@link #isAffiliatedUser}.
14016      *
14017      * @param admin Which device admin this request is associated with, or {@code null}
14018      *             if called by a delegated app.
14019      * @return Device logs from before the latest reboot of the system, or {@code null} if this API
14020      *         is not supported on the device.
14021      * @throws SecurityException if the caller is not allowed to access security logging, or
14022      * there is at least one profile or secondary user that is not affiliated with the device.
14023      * @see #isAffiliatedUser
14024      * @see #retrieveSecurityLogs
14025      */
14026     @SuppressLint("NullableCollection")
14027     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SECURITY_LOGGING, conditional = true)
retrievePreRebootSecurityLogs( @ullable ComponentName admin)14028     public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
14029             @Nullable ComponentName admin) {
14030         throwIfParentInstance("retrievePreRebootSecurityLogs");
14031         try {
14032             ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(
14033                     admin, mContext.getPackageName());
14034             if (list != null) {
14035                 return list.getList();
14036             } else {
14037                 return null;
14038             }
14039         } catch (RemoteException re) {
14040             throw re.rethrowFromSystemServer();
14041         }
14042     }
14043 
14044     /**
14045      * Called by a profile owner of a managed profile to set the color used for customization. This
14046      * color is used as background color of the confirm credentials screen for that user. The
14047      * default color is teal (#00796B).
14048      * <p>
14049      * The confirm credentials screen can be created using
14050      * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
14051      * <p>
14052      * Starting from Android R, the organization color will no longer be used as the background
14053      * color of the confirm credentials screen.
14054      *
14055      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
14056      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
14057      * @throws SecurityException if {@code admin} is not a profile owner.
14058      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
14059      * used as the background color of the confirm credentials screen.
14060      */
14061     @Deprecated
setOrganizationColor(@onNull ComponentName admin, int color)14062     public void setOrganizationColor(@NonNull ComponentName admin, int color) {
14063         throwIfParentInstance("setOrganizationColor");
14064         try {
14065             // always enforce alpha channel to have 100% opacity
14066             color |= 0xFF000000;
14067             mService.setOrganizationColor(admin, color);
14068         } catch (RemoteException re) {
14069             throw re.rethrowFromSystemServer();
14070         }
14071     }
14072 
14073     /**
14074      * @hide
14075      *
14076      * Sets the color used for customization.
14077      *
14078      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
14079      * @param userId which user to set the color to.
14080      * @RequiresPermission(allOf = {
14081      *       Manifest.permission.MANAGE_USERS,
14082      *       Manifest.permission.INTERACT_ACROSS_USERS_FULL})
14083      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
14084      * used as the background color of the confirm credentials screen.
14085      */
14086     @Deprecated
setOrganizationColorForUser(@olorInt int color, @UserIdInt int userId)14087     public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
14088         try {
14089             // always enforce alpha channel to have 100% opacity
14090             color |= 0xFF000000;
14091             mService.setOrganizationColorForUser(color, userId);
14092         } catch (RemoteException re) {
14093             throw re.rethrowFromSystemServer();
14094         }
14095     }
14096 
14097     /**
14098      * Called by a profile owner of a managed profile to retrieve the color used for customization.
14099      * This color is used as background color of the confirm credentials screen for that user.
14100      *
14101      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
14102      * @return The 24bit (0xRRGGBB) representation of the color to be used.
14103      * @throws SecurityException if {@code admin} is not a profile owner.
14104      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
14105      * used as the background color of the confirm credentials screen.
14106      */
14107     @Deprecated
getOrganizationColor(@onNull ComponentName admin)14108     public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
14109         throwIfParentInstance("getOrganizationColor");
14110         try {
14111             return mService.getOrganizationColor(admin);
14112         } catch (RemoteException re) {
14113             throw re.rethrowFromSystemServer();
14114         }
14115     }
14116 
14117     /**
14118      * @hide
14119      * Retrieve the customization color for a given user.
14120      *
14121      * @param userHandle The user id of the user we're interested in.
14122      * @return The 24bit (0xRRGGBB) representation of the color to be used.
14123      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
14124      * used as the background color of the confirm credentials screen.
14125      */
14126     @Deprecated
getOrganizationColorForUser(int userHandle)14127     public @ColorInt int getOrganizationColorForUser(int userHandle) {
14128         try {
14129             return mService.getOrganizationColorForUser(userHandle);
14130         } catch (RemoteException re) {
14131             throw re.rethrowFromSystemServer();
14132         }
14133     }
14134 
14135     /**
14136      * Called by the device owner (since API 26) or profile owner (since API 24) to set the name of
14137      * the organization under management.
14138      *
14139      * <p>If the organization name needs to be localized, it is the responsibility of the caller
14140      * to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast and set a new version of this
14141      * string accordingly.
14142      *
14143      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
14144      *               caller is not a device admin.
14145      * @param title The organization name or {@code null} to clear a previously set name.
14146      * @throws SecurityException if {@code admin} is not a device or profile owner.
14147      */
14148     @RequiresPermission(value = MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY, conditional = true)
setOrganizationName(@ullable ComponentName admin, @Nullable CharSequence title)14149     public void setOrganizationName(@Nullable ComponentName admin, @Nullable CharSequence title) {
14150         throwIfParentInstance("setOrganizationName");
14151         try {
14152             mService.setOrganizationName(admin, mContext.getPackageName(), title);
14153         } catch (RemoteException re) {
14154             throw re.rethrowFromSystemServer();
14155         }
14156     }
14157 
14158     /**
14159      * Called by the device owner (since API 26) or profile owner (since API 24) or holders of the
14160      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY
14161      * to retrieve the name of the organization under management.
14162      *
14163      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
14164      *               caller is not a device admin.
14165      * @return The organization name or {@code null} if none is set.
14166      * @throws SecurityException if {@code admin} if {@code admin} is not a device or profile
14167      * owner or holder of the
14168      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY}.
14169      */
14170     @RequiresPermission(value = MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY, conditional = true)
getOrganizationName(@ullable ComponentName admin)14171     public @Nullable CharSequence getOrganizationName(@Nullable ComponentName admin) {
14172         throwIfParentInstance("getOrganizationName");
14173         try {
14174             return mService.getOrganizationName(admin, mContext.getPackageName());
14175         } catch (RemoteException re) {
14176             throw re.rethrowFromSystemServer();
14177         }
14178     }
14179 
14180     private final IpcDataCache<Void, CharSequence> mGetDeviceOwnerOrganizationNameCache =
14181             new IpcDataCache(sDpmCaches.child("getDeviceOwnerOrganizationName"),
14182                     (query) -> getService().getDeviceOwnerOrganizationName());
14183 
14184     /**
14185      * Called by the system to retrieve the name of the organization managing the device.
14186      *
14187      * @return The organization name or {@code null} if none is set.
14188      * @throws SecurityException if the caller is not the device owner, does not hold the
14189      *         MANAGE_USERS permission and is not the system.
14190      *
14191      * @hide
14192      */
14193     @SystemApi
14194     @SuppressLint("RequiresPermission")
getDeviceOwnerOrganizationName()14195     public @Nullable CharSequence getDeviceOwnerOrganizationName() {
14196         return mGetDeviceOwnerOrganizationNameCache.query(null);
14197     }
14198 
14199     private final IpcDataCache<Integer, CharSequence> mGetOrganizationNameForUserCache =
14200             new IpcDataCache<>(sDpmCaches.child("getOrganizationNameForUser"),
14201                     (query) -> getService().getOrganizationNameForUser(query));
14202 
14203     /**
14204      * Retrieve the default title message used in the confirm credentials screen for a given user.
14205      *
14206      * @param userHandle The user id of the user we're interested in.
14207      * @return The organization name or {@code null} if none is set.
14208      *
14209      * @hide
14210      */
getOrganizationNameForUser(int userHandle)14211     public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
14212         return mGetOrganizationNameForUserCache.query(userHandle);
14213     }
14214 
14215     /**
14216      * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
14217      *         return {@link #STATE_USER_UNMANAGED}
14218      * @hide
14219      */
14220     @SystemApi
14221     @RequiresPermission(anyOf = {
14222             android.Manifest.permission.MANAGE_USERS,
14223             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
14224     })
14225     @UserProvisioningState
14226     @UserHandleAware(
14227             enabledSinceTargetSdkVersion = UPSIDE_DOWN_CAKE,
14228             requiresPermissionIfNotCaller = INTERACT_ACROSS_USERS)
getUserProvisioningState()14229     public int getUserProvisioningState() {
14230         throwIfParentInstance("getUserProvisioningState");
14231         if (mService != null) {
14232             try {
14233                 return mService.getUserProvisioningState(mContext.getUserId());
14234             } catch (RemoteException e) {
14235                 throw e.rethrowFromSystemServer();
14236             }
14237         }
14238         return STATE_USER_UNMANAGED;
14239     }
14240 
14241     /**
14242      * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
14243      *
14244      * @param state to store
14245      * @param userHandle for user
14246      *
14247      * @hide
14248      */
14249     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setUserProvisioningState(@serProvisioningState int state, int userHandle)14250     public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
14251         if (mService != null) {
14252             try {
14253                 mService.setUserProvisioningState(state, userHandle);
14254             } catch (RemoteException e) {
14255                 throw e.rethrowFromSystemServer();
14256             }
14257         }
14258     }
14259 
14260     /**
14261      * Set the {@link UserProvisioningState} for the supplied user. The supplied user has to be
14262      * manged, otherwise it will throw an {@link IllegalStateException}.
14263      *
14264      * <p> For managed users/profiles/devices, only the following state changes are allowed:
14265      * <ul>
14266      *     <li>{@link #STATE_USER_UNMANAGED} can change to any other state except itself
14267      *     <li>{@link #STATE_USER_SETUP_INCOMPLETE} and {@link #STATE_USER_SETUP_COMPLETE} can only
14268      *     change to {@link #STATE_USER_SETUP_FINALIZED}</li>
14269      *     <li>{@link #STATE_USER_PROFILE_COMPLETE} can only change to
14270      *     {@link #STATE_USER_PROFILE_FINALIZED}</li>
14271      *     <li>{@link #STATE_USER_SETUP_FINALIZED} can't be changed to any other state</li>
14272      *     <li>{@link #STATE_USER_PROFILE_FINALIZED} can only change to
14273      *     {@link #STATE_USER_UNMANAGED}</li>
14274      * </ul>
14275      * @param state to store
14276      * @param userHandle for user
14277      * @throws IllegalStateException if called with an invalid state change.
14278      *
14279      * @hide
14280      */
14281     @SystemApi
14282     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setUserProvisioningState( @serProvisioningState int state, @NonNull UserHandle userHandle)14283     public void setUserProvisioningState(
14284             @UserProvisioningState int state, @NonNull UserHandle userHandle) {
14285         setUserProvisioningState(state, userHandle.getIdentifier());
14286     }
14287 
14288     /**
14289      * Indicates the entity that controls the device. Two users are
14290      * affiliated if the set of ids set by the device owner and the admin of the secondary user.
14291      *
14292      * <p>A user that is affiliated with the device owner user is considered to be
14293      * affiliated with the device.
14294      *
14295      * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
14296      * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user
14297      * is created, until it becomes affiliated. Therefore it is recommended that the appropriate
14298      * affiliation ids are set by its owner as soon as possible after the user is
14299      * created.
14300      * <p>
14301      * Note: This method used to be available for affiliating device owner and profile
14302      * owner. However, since Android 11, this combination is not possible. This method is now
14303      * only useful for affiliating the primary user with managed secondary users.
14304      *
14305      * @param admin Which device owner, or owner of secondary user, this request is associated with.
14306      * @param ids A set of opaque non-empty affiliation ids.
14307      *
14308      * @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
14309      * @see #isAffiliatedUser
14310      */
setAffiliationIds(@onNull ComponentName admin, @NonNull Set<String> ids)14311     public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) {
14312         throwIfParentInstance("setAffiliationIds");
14313         if (ids == null) {
14314             throw new IllegalArgumentException("ids must not be null");
14315         }
14316         try {
14317             mService.setAffiliationIds(admin, new ArrayList<>(ids));
14318         } catch (RemoteException e) {
14319             throw e.rethrowFromSystemServer();
14320         }
14321     }
14322 
14323     /**
14324      * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
14325      * empty set if none have been set.
14326      */
getAffiliationIds(@onNull ComponentName admin)14327     public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
14328         throwIfParentInstance("getAffiliationIds");
14329         try {
14330             return new ArraySet<>(mService.getAffiliationIds(admin));
14331         } catch (RemoteException e) {
14332             throw e.rethrowFromSystemServer();
14333         }
14334     }
14335 
14336     /**
14337      * Returns whether this user is affiliated with the device.
14338      * <p>
14339      * By definition, the user that the device owner runs on is always affiliated with the device.
14340      * Any other user is considered affiliated with the device if the set specified by its
14341      * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
14342      * @see #setAffiliationIds
14343      */
isAffiliatedUser()14344     public boolean isAffiliatedUser() {
14345         throwIfParentInstance("isAffiliatedUser");
14346         try {
14347             return mService.isCallingUserAffiliated();
14348         } catch (RemoteException e) {
14349             throw e.rethrowFromSystemServer();
14350         }
14351     }
14352 
14353     /**
14354      * @hide
14355      * Returns whether target user is affiliated with the device.
14356      */
isAffiliatedUser(@serIdInt int userId)14357     public boolean isAffiliatedUser(@UserIdInt int userId) {
14358         try {
14359             return mService.isAffiliatedUser(userId);
14360         } catch (RemoteException e) {
14361             throw e.rethrowFromSystemServer();
14362         }
14363     }
14364 
14365     /**
14366      * @hide
14367      * Returns whether the uninstall for {@code packageName} for the current user is in queue
14368      * to be started
14369      * @param packageName the package to check for
14370      * @return whether the uninstall intent for {@code packageName} is pending
14371      */
isUninstallInQueue(String packageName)14372     public boolean isUninstallInQueue(String packageName) {
14373         try {
14374             return mService.isUninstallInQueue(packageName);
14375         } catch (RemoteException re) {
14376             throw re.rethrowFromSystemServer();
14377         }
14378     }
14379 
14380     /**
14381      * @hide
14382      * @param packageName the package containing active DAs to be uninstalled
14383      */
uninstallPackageWithActiveAdmins(String packageName)14384     public void uninstallPackageWithActiveAdmins(String packageName) {
14385         try {
14386             mService.uninstallPackageWithActiveAdmins(packageName);
14387         } catch (RemoteException re) {
14388             throw re.rethrowFromSystemServer();
14389         }
14390     }
14391 
14392     /**
14393      * @hide
14394      * Remove a test admin synchronously without sending it a broadcast about being removed.
14395      * If the admin is a profile owner or device owner it will still be removed.
14396      *
14397      * @param userHandle user id to remove the admin for.
14398      * @param admin The administration compononent to remove.
14399      * @throws SecurityException if the caller is not shell / root or the admin package
14400      *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
14401      */
14402     @TestApi
14403     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
forceRemoveActiveAdmin( @onNull ComponentName adminReceiver, @UserIdInt int userHandle)14404     public void forceRemoveActiveAdmin(
14405             @NonNull ComponentName adminReceiver, @UserIdInt int userHandle) {
14406         try {
14407             mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
14408         } catch (RemoteException re) {
14409             throw re.rethrowFromSystemServer();
14410         }
14411     }
14412 
14413     /**
14414      * Returns whether the device has been provisioned.
14415      *
14416      * <p>Not for use by third-party applications.
14417      *
14418      * @hide
14419      */
14420     @SystemApi
14421     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioned()14422     public boolean isDeviceProvisioned() {
14423         try {
14424             return mService.isDeviceProvisioned();
14425         } catch (RemoteException re) {
14426             throw re.rethrowFromSystemServer();
14427         }
14428     }
14429 
14430     /**
14431       * Writes that the provisioning configuration has been applied.
14432       *
14433       * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
14434       * permission.
14435       *
14436       * <p>Not for use by third-party applications.
14437       *
14438       * @hide
14439       */
14440     @SystemApi
14441     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
setDeviceProvisioningConfigApplied()14442     public void setDeviceProvisioningConfigApplied() {
14443         try {
14444             mService.setDeviceProvisioningConfigApplied();
14445         } catch (RemoteException re) {
14446             throw re.rethrowFromSystemServer();
14447         }
14448     }
14449 
14450     /**
14451      * Returns whether the provisioning configuration has been applied.
14452      *
14453      * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
14454      *
14455      * <p>Not for use by third-party applications.
14456      *
14457      * @return whether the provisioning configuration has been applied.
14458      *
14459      * @hide
14460      */
14461     @SystemApi
14462     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioningConfigApplied()14463     public boolean isDeviceProvisioningConfigApplied() {
14464         try {
14465             return mService.isDeviceProvisioningConfigApplied();
14466         } catch (RemoteException re) {
14467             throw re.rethrowFromSystemServer();
14468         }
14469     }
14470 
14471     /**
14472      * @hide
14473      * Force update user setup completed status for the given {@code userId}.
14474      * @throws {@link SecurityException} if the caller has no
14475      *         {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS}.
14476      */
14477     @TestApi
forceUpdateUserSetupComplete(@serIdInt int userId)14478     public void forceUpdateUserSetupComplete(@UserIdInt int userId) {
14479         try {
14480             mService.forceUpdateUserSetupComplete(userId);
14481         } catch (RemoteException re) {
14482             throw re.rethrowFromSystemServer();
14483         }
14484     }
14485 
14486     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
throwIfParentInstance(String functionName)14487     private void throwIfParentInstance(String functionName) {
14488         if (mParentInstance) {
14489             throw new SecurityException(functionName + " cannot be called on the parent instance");
14490         }
14491     }
14492 
14493     /**
14494      * Allows the device owner or profile owner to enable or disable the backup service.
14495      *
14496      * <p> Each user has its own backup service which manages the backup and restore mechanisms in
14497      * that user. Disabling the backup service will prevent data from being backed up or restored.
14498      *
14499      * <p> Device owner calls this API to control backup services across all users on the device.
14500      * Profile owner can use this API to enable or disable the profile's backup service. However,
14501      * for a managed profile its backup functionality is only enabled if both the device owner
14502      * and the profile owner have enabled the backup service.
14503      *
14504      * <p> By default, backup service is disabled on a device with device owner, and within a
14505      * managed profile.
14506      *
14507      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
14508      * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
14509      * @throws SecurityException if {@code admin} is not a device owner or a profile owner.
14510      */
setBackupServiceEnabled(@onNull ComponentName admin, boolean enabled)14511     public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
14512         throwIfParentInstance("setBackupServiceEnabled");
14513         try {
14514             mService.setBackupServiceEnabled(admin, enabled);
14515         } catch (RemoteException re) {
14516             throw re.rethrowFromSystemServer();
14517         }
14518     }
14519 
14520     /**
14521      * Return whether the backup service is enabled by the device owner or profile owner for the
14522      * current user, as previously set by {@link #setBackupServiceEnabled(ComponentName, boolean)}.
14523      *
14524      * <p> Whether the backup functionality is actually enabled or not depends on settings from both
14525      * the current user and the device owner, please see
14526      * {@link #setBackupServiceEnabled(ComponentName, boolean)} for details.
14527      *
14528      * <p> Backup service manages all backup and restore mechanisms on the device.
14529      *
14530      * @return {@code true} if backup service is enabled, {@code false} otherwise.
14531      * @see #setBackupServiceEnabled
14532      */
isBackupServiceEnabled(@onNull ComponentName admin)14533     public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
14534         throwIfParentInstance("isBackupServiceEnabled");
14535         try {
14536             return mService.isBackupServiceEnabled(admin);
14537         } catch (RemoteException re) {
14538             throw re.rethrowFromSystemServer();
14539         }
14540     }
14541 
14542     /**
14543      * Called by a device owner, profile owner of a managed profile or delegated app with
14544      * {@link #DELEGATION_NETWORK_LOGGING} to control the network logging feature.
14545      *
14546      * <p> Supported for a device owner from Android 8 and a delegated app granted by a device
14547      * owner from Android 10. Supported for a profile owner of a managed profile and a delegated
14548      * app granted by a profile owner from Android 12. When network logging is enabled by a
14549      * profile owner, the network logs will only include work profile network activity, not
14550      * activity on the personal profile.
14551      *
14552      * <p> Network logs contain DNS lookup and connect() library call events. The following library
14553      *     functions are recorded while network logging is active:
14554      *     <ul>
14555      *       <li>{@code getaddrinfo()}</li>
14556      *       <li>{@code gethostbyname()}</li>
14557      *       <li>{@code connect()}</li>
14558      *     </ul>
14559      *
14560      * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
14561      *     full system call logging; event reporting is enabled by default for all processes but not
14562      *     strongly enforced.
14563      *     Events from applications using alternative implementations of libc, making direct kernel
14564      *     calls, or deliberately obfuscating traffic may not be recorded.
14565      *
14566      * <p> Some common network events may not be reported. For example:
14567      *     <ul>
14568      *       <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
14569      *           an alternative system for name resolution, and so avoid calling
14570      *           {@code getaddrinfo()} or {@code gethostbyname}.</li>
14571      *       <li>Applications may use datagram sockets for performance reasons, for example
14572      *           for a game client. Calling {@code connect()} is unnecessary for this kind of
14573      *           socket, so it will not trigger a network event.</li>
14574      *     </ul>
14575      *
14576      * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
14577      *     always-on VPN service.
14578      *     See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
14579      *     and {@link android.net.VpnService} for details.
14580      *
14581      * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
14582      * are unaffiliated secondary users or profiles on the device, regardless of whether the
14583      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
14584      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
14585      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
14586      *
14587      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
14588      *        {@code null} if called by a delegated app.
14589      * @param enabled whether network logging should be enabled or not.
14590      * @throws SecurityException if {@code admin} is not a device owner or profile owner.
14591      * @see #setAffiliationIds
14592      * @see #retrieveNetworkLogs
14593      */
setNetworkLoggingEnabled(@ullable ComponentName admin, boolean enabled)14594     public void setNetworkLoggingEnabled(@Nullable ComponentName admin, boolean enabled) {
14595         throwIfParentInstance("setNetworkLoggingEnabled");
14596         try {
14597             mService.setNetworkLoggingEnabled(admin, mContext.getPackageName(), enabled);
14598         } catch (RemoteException re) {
14599             throw re.rethrowFromSystemServer();
14600         }
14601     }
14602 
14603     private IpcDataCache<ComponentName, Boolean> mIsNetworkLoggingEnabledCache =
14604             new IpcDataCache<>(sDpmCaches.child("isNetworkLoggingEnabled"),
14605                     (admin) -> getService().isNetworkLoggingEnabled(admin,
14606                             getContext().getPackageName()));
14607 
14608     /**
14609      * Return whether network logging is enabled by a device owner or profile owner of
14610      * a managed profile.
14611      *
14612      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
14613      * be {@code null} if the caller is a delegated app with {@link #DELEGATION_NETWORK_LOGGING}
14614      * or has MANAGE_USERS permission.
14615      * @return {@code true} if network logging is enabled by device owner or profile owner,
14616      * {@code false} otherwise.
14617      * @throws SecurityException if {@code admin} is not a device owner or profile owner and
14618      * caller has no MANAGE_USERS permission
14619      */
isNetworkLoggingEnabled(@ullable ComponentName admin)14620     public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
14621         throwIfParentInstance("isNetworkLoggingEnabled");
14622         return mIsNetworkLoggingEnabledCache.query(admin);
14623     }
14624 
14625     /**
14626      * Called by device owner, profile owner of a managed profile or delegated app with
14627      * {@link #DELEGATION_NETWORK_LOGGING} to retrieve the most recent batch of
14628      * network logging events.
14629      *
14630      * <p> When network logging is enabled by a profile owner, the network logs will only include
14631      * work profile network activity, not activity on the personal profile.
14632      *
14633      * A device owner or profile owner has to provide a batchToken provided as part of
14634      * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
14635      * token of the most recent available batch of logs, {@code null} will be returned.
14636      *
14637      * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
14638      *
14639      * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
14640      *
14641      * <p> Access to the logs is rate limited and this method will only return a new batch of logs
14642      * after the device device owner has been notified via
14643      * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
14644      *
14645      * <p>If the caller is not a profile owner and a secondary user or profile is created, calling
14646      * this method will throw a {@link SecurityException} until all users become affiliated again.
14647      * It will also no longer be possible to retrieve the network logs batch with the most recent
14648      * batchToken provided by {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
14649      * See {@link DevicePolicyManager#setAffiliationIds}.
14650      *
14651      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
14652      *        {@code null} if called by a delegated app.
14653      * @param batchToken A token of the batch to retrieve
14654      * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
14655      *        {@code null} if the batch represented by batchToken is no longer available or if
14656      *        logging is disabled.
14657      * @throws SecurityException if {@code admin} is not a device owner, profile owner or if the
14658      * {@code admin} is not a profile owner and there is at least one profile or secondary user
14659      * that is not affiliated with the device.
14660      * @see #setAffiliationIds
14661      * @see DeviceAdminReceiver#onNetworkLogsAvailable
14662      */
retrieveNetworkLogs(@ullable ComponentName admin, long batchToken)14663     public @Nullable List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin,
14664             long batchToken) {
14665         throwIfParentInstance("retrieveNetworkLogs");
14666         try {
14667             return mService.retrieveNetworkLogs(admin, mContext.getPackageName(), batchToken);
14668         } catch (RemoteException re) {
14669             throw re.rethrowFromSystemServer();
14670         }
14671     }
14672 
14673     /**
14674      * Called by a device owner to bind to a service from a secondary managed user or vice versa.
14675      * See {@link #getBindDeviceAdminTargetUsers} for the pre-requirements of a
14676      * device owner to bind to services of another managed user.
14677      * <p>
14678      * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
14679      * Note that the {@link Context} used to obtain this
14680      * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
14681      * to bind to the {@link android.app.Service}.
14682      * <p>
14683      * Note: This method used to be available for communication between device owner and profile
14684      * owner. However, since Android 11, this combination is not possible. This method is now
14685      * only useful for communication between device owner and managed secondary users.
14686      *
14687      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
14688      * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
14689      *        explicit component name or a package name to match an
14690      *        {@link IntentFilter} published by a service.
14691      * @param conn Receives information as the service is started and stopped in main thread. This
14692      *        must be a valid {@link ServiceConnection} object; it must not be {@code null}.
14693      * @param flags Operation options for the binding operation. See
14694      *        {@link Context#bindService(Intent, ServiceConnection, int)}.
14695      * @param targetUser Which user to bind to. Must be one of the users returned by
14696      *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
14697      *        be thrown.
14698      * @return If you have successfully bound to the service, {@code true} is returned;
14699      *         {@code false} is returned if the connection is not made and you will not
14700      *         receive the service object.
14701      *
14702      * @see Context#bindService(Intent, ServiceConnection, int)
14703      * @see #getBindDeviceAdminTargetUsers(ComponentName)
14704      */
bindDeviceAdminServiceAsUser(@onNull ComponentName admin, @NonNull Intent serviceIntent, @NonNull ServiceConnection conn, @Context.BindServiceFlagsBits int flags, @NonNull UserHandle targetUser)14705     public boolean bindDeviceAdminServiceAsUser(@NonNull ComponentName admin,
14706             @NonNull Intent serviceIntent, @NonNull ServiceConnection conn,
14707             @Context.BindServiceFlagsBits int flags, @NonNull UserHandle targetUser) {
14708         throwIfParentInstance("bindDeviceAdminServiceAsUser");
14709         // Keep this in sync with ContextImpl.bindServiceCommon.
14710         try {
14711             final IServiceConnection sd = mContext.getServiceDispatcher(
14712                     conn, mContext.getMainThreadHandler(), Integer.toUnsignedLong(flags));
14713             serviceIntent.prepareToLeaveProcess(mContext);
14714             return mService.bindDeviceAdminServiceAsUser(admin,
14715                     mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
14716                     sd, Integer.toUnsignedLong(flags), targetUser.getIdentifier());
14717         } catch (RemoteException re) {
14718             throw re.rethrowFromSystemServer();
14719         }
14720     }
14721 
14722     /**
14723      * See {@link #bindDeviceAdminServiceAsUser(ComponentName, Intent, ServiceConnection, int,
14724      *       UserHandle)}.
14725      * Call {@link Context.BindServiceFlags#of(long)} to obtain a BindServiceFlags object.
14726      */
bindDeviceAdminServiceAsUser(@onNull ComponentName admin, @NonNull Intent serviceIntent, @NonNull ServiceConnection conn, @NonNull Context.BindServiceFlags flags, @NonNull UserHandle targetUser)14727     public boolean bindDeviceAdminServiceAsUser(@NonNull ComponentName admin,
14728             @NonNull Intent serviceIntent, @NonNull ServiceConnection conn,
14729             @NonNull Context.BindServiceFlags flags, @NonNull UserHandle targetUser) {
14730         throwIfParentInstance("bindDeviceAdminServiceAsUser");
14731         // Keep this in sync with ContextImpl.bindServiceCommon.
14732         try {
14733             final IServiceConnection sd = mContext.getServiceDispatcher(
14734                     conn, mContext.getMainThreadHandler(), flags.getValue());
14735             serviceIntent.prepareToLeaveProcess(mContext);
14736             return mService.bindDeviceAdminServiceAsUser(admin,
14737                     mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
14738                     sd, flags.getValue(), targetUser.getIdentifier());
14739         } catch (RemoteException re) {
14740             throw re.rethrowFromSystemServer();
14741         }
14742     }
14743 
14744     /**
14745      * Returns the list of target users that the calling device owner or owner of secondary user
14746      * can use when calling {@link #bindDeviceAdminServiceAsUser}.
14747      * <p>
14748      * A device owner can bind to a service from a secondary managed user and vice versa, provided
14749      * that both users are affiliated. See {@link #setAffiliationIds}.
14750      */
getBindDeviceAdminTargetUsers(@onNull ComponentName admin)14751     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
14752         throwIfParentInstance("getBindDeviceAdminTargetUsers");
14753         try {
14754             return mService.getBindDeviceAdminTargetUsers(admin);
14755         } catch (RemoteException re) {
14756             throw re.rethrowFromSystemServer();
14757         }
14758     }
14759 
14760     /**
14761      * Called by the system to get the time at which the device owner last retrieved security
14762      * logging entries.
14763      *
14764      * @return the time at which the device owner most recently retrieved security logging entries,
14765      *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
14766      * @throws SecurityException if the caller is not the device owner, does not hold the
14767      *         MANAGE_USERS permission and is not the system.
14768      *
14769      * @hide
14770      */
14771     @TestApi
getLastSecurityLogRetrievalTime()14772     public long getLastSecurityLogRetrievalTime() {
14773         try {
14774             return mService.getLastSecurityLogRetrievalTime();
14775         } catch (RemoteException re) {
14776             throw re.rethrowFromSystemServer();
14777         }
14778     }
14779 
14780     /**
14781      * Called by the system to get the time at which the device owner last requested a bug report.
14782      *
14783      * @return the time at which the device owner most recently requested a bug report, in
14784      *         milliseconds since epoch; -1 if a bug report was never requested.
14785      * @throws SecurityException if the caller is not the device owner, does not hold the
14786      *         MANAGE_USERS permission and is not the system.
14787      *
14788      * @hide
14789      */
14790     @TestApi
getLastBugReportRequestTime()14791     public long getLastBugReportRequestTime() {
14792         try {
14793             return mService.getLastBugReportRequestTime();
14794         } catch (RemoteException re) {
14795             throw re.rethrowFromSystemServer();
14796         }
14797     }
14798 
14799     /**
14800      * Called by the system to get the time at which the device owner or profile owner of a
14801      * managed profile last retrieved network logging events.
14802      *
14803      * @return the time at which the device owner or profile owner most recently retrieved network
14804      *         logging events, in milliseconds since epoch; -1 if network logging events were
14805      *         never retrieved.
14806      * @throws SecurityException if the caller is not the device owner, does not hold the
14807      *         MANAGE_USERS permission and is not the system.
14808      *
14809      * @hide
14810      */
14811     @TestApi
getLastNetworkLogRetrievalTime()14812     public long getLastNetworkLogRetrievalTime() {
14813         try {
14814             return mService.getLastNetworkLogRetrievalTime();
14815         } catch (RemoteException re) {
14816             throw re.rethrowFromSystemServer();
14817         }
14818     }
14819 
14820     /**
14821      * Called by the system to find out whether the current user's IME was set by the device/profile
14822      * owner or the user.
14823      *
14824      * @return {@code true} if the user's IME was set by the device or profile owner, {@code false}
14825      *         otherwise.
14826      * @throws SecurityException if the caller is not the device owner/profile owner.
14827      *
14828      * @hide
14829      */
14830     @TestApi
isCurrentInputMethodSetByOwner()14831     public boolean isCurrentInputMethodSetByOwner() {
14832         try {
14833             return mService.isCurrentInputMethodSetByOwner();
14834         } catch (RemoteException re) {
14835             throw re.rethrowFromSystemServer();
14836         }
14837     }
14838 
14839     /**
14840      * Called by the system to get a list of CA certificates that were installed by the device or
14841      * profile owner.
14842      *
14843      * <p> The caller must be the target user's device owner/profile Owner or hold the
14844      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
14845      *
14846      * @param user The user for whom to retrieve information.
14847      * @return list of aliases identifying CA certificates installed by the device or profile owner
14848      * @throws SecurityException if the caller does not have permission to retrieve information
14849      *         about the given user's CA certificates.
14850      *
14851      * @hide
14852      */
14853     @TestApi
getOwnerInstalledCaCerts(@onNull UserHandle user)14854     public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
14855         try {
14856             return mService.getOwnerInstalledCaCerts(user).getList();
14857         } catch (RemoteException re) {
14858             throw re.rethrowFromSystemServer();
14859         }
14860     }
14861 
14862     /**
14863      * Returns whether factory reset protection policy is supported on the device.
14864      *
14865      * @return {@code true} if the device support factory reset protection policy.
14866      *
14867      * @hide
14868      */
14869     @TestApi
isFactoryResetProtectionPolicySupported()14870     public boolean isFactoryResetProtectionPolicySupported() {
14871         try {
14872             return mService.isFactoryResetProtectionPolicySupported();
14873         } catch (RemoteException re) {
14874             throw re.rethrowFromSystemServer();
14875         }
14876     }
14877 
14878     /**
14879      * Called by the device owner or profile owner to clear application user data of a given
14880      * package. The behaviour of this is equivalent to the target application calling
14881      * {@link android.app.ActivityManager#clearApplicationUserData()}.
14882      *
14883      * <p><strong>Note:</strong> an application can store data outside of its application data, e.g.
14884      * external storage or user dictionary. This data will not be wiped by calling this API.
14885      *
14886      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
14887      * @param packageName The name of the package which will have its user data wiped.
14888      * @param executor The executor through which the listener should be invoked.
14889      * @param listener A callback object that will inform the caller when the clearing is done.
14890      * @throws SecurityException if the caller is not the device owner/profile owner.
14891      */
clearApplicationUserData(@onNull ComponentName admin, @NonNull String packageName, @NonNull @CallbackExecutor Executor executor, @NonNull OnClearApplicationUserDataListener listener)14892     public void clearApplicationUserData(@NonNull ComponentName admin,
14893             @NonNull String packageName, @NonNull @CallbackExecutor Executor executor,
14894             @NonNull OnClearApplicationUserDataListener listener) {
14895         throwIfParentInstance("clearAppData");
14896         Objects.requireNonNull(executor);
14897         Objects.requireNonNull(listener);
14898         try {
14899             mService.clearApplicationUserData(admin, packageName,
14900                     new IPackageDataObserver.Stub() {
14901                         public void onRemoveCompleted(String pkg, boolean succeeded) {
14902                             executor.execute(() ->
14903                                     listener.onApplicationUserDataCleared(pkg, succeeded));
14904                         }
14905                     });
14906         } catch (RemoteException re) {
14907             throw re.rethrowFromSystemServer();
14908         }
14909     }
14910 
14911     /**
14912      * Called by a device owner to specify whether logout is enabled for all secondary users. The
14913      * system may show a logout button that stops the user and switches back to the primary user.
14914      *
14915      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
14916      * @param enabled whether logout should be enabled or not.
14917      * @throws SecurityException if {@code admin} is not a device owner.
14918      */
setLogoutEnabled(@onNull ComponentName admin, boolean enabled)14919     public void setLogoutEnabled(@NonNull ComponentName admin, boolean enabled) {
14920         throwIfParentInstance("setLogoutEnabled");
14921         try {
14922             mService.setLogoutEnabled(admin, enabled);
14923         } catch (RemoteException re) {
14924             throw re.rethrowFromSystemServer();
14925         }
14926     }
14927 
14928     /**
14929      * Returns whether logout is enabled by a device owner.
14930      *
14931      * @return {@code true} if logout is enabled by device owner, {@code false} otherwise.
14932      */
isLogoutEnabled()14933     public boolean isLogoutEnabled() {
14934         throwIfParentInstance("isLogoutEnabled");
14935         try {
14936             return mService.isLogoutEnabled();
14937         } catch (RemoteException re) {
14938             throw re.rethrowFromSystemServer();
14939         }
14940     }
14941 
14942     /**
14943      * Callback used in {@link #clearApplicationUserData}
14944      * to indicate that the clearing of an application's user data is done.
14945      */
14946     public interface OnClearApplicationUserDataListener {
14947         /**
14948          * Method invoked when clearing the application user data has completed.
14949          *
14950          * @param packageName The name of the package which had its user data cleared.
14951          * @param succeeded Whether the clearing succeeded. Clearing fails for device administrator
14952          *                  apps and protected system packages.
14953          */
onApplicationUserDataCleared(String packageName, boolean succeeded)14954         void onApplicationUserDataCleared(String packageName, boolean succeeded);
14955     }
14956 
14957     /**
14958      * Returns set of system apps that should be removed during provisioning.
14959      *
14960      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
14961      * @param userId ID of the user to be provisioned.
14962      * @param provisioningAction action indicating type of provisioning, should be one of
14963      * {@link #ACTION_PROVISION_MANAGED_DEVICE}, {@link #ACTION_PROVISION_MANAGED_PROFILE} or
14964      * {@link #ACTION_PROVISION_MANAGED_USER}.
14965      *
14966      * @hide
14967      */
14968     @TestApi
getDisallowedSystemApps(@onNull ComponentName admin, @UserIdInt int userId, @NonNull String provisioningAction)14969     public @NonNull Set<String> getDisallowedSystemApps(@NonNull ComponentName admin,
14970             @UserIdInt int userId, @NonNull String provisioningAction) {
14971         try {
14972             return new ArraySet<>(
14973                     mService.getDisallowedSystemApps(admin, userId, provisioningAction));
14974         } catch (RemoteException re) {
14975             throw re.rethrowFromSystemServer();
14976         }
14977     }
14978 
14979     /**
14980      * Changes the current administrator to another one. All policies from the current
14981      * administrator are migrated to the new administrator. The whole operation is atomic -
14982      * the transfer is either complete or not done at all.
14983      *
14984      * <p>Depending on the current administrator (device owner, profile owner), you have the
14985      * following expected behaviour:
14986      * <ul>
14987      *     <li>A device owner can only be transferred to a new device owner</li>
14988      *     <li>A profile owner can only be transferred to a new profile owner</li>
14989      * </ul>
14990      *
14991      * <p>Use the {@code bundle} parameter to pass data to the new administrator. The data
14992      * will be received in the
14993      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}
14994      * callback of the new administrator.
14995      *
14996      * <p>The transfer has failed if the original administrator is still the corresponding owner
14997      * after calling this method.
14998      *
14999      * <p>The incoming target administrator must have the
15000      * <code>&lt;support-transfer-ownership /&gt;</code> tag inside the
15001      * <code>&lt;device-admin&gt;&lt;/device-admin&gt;</code> tags in the xml file referenced by
15002      * {@link DeviceAdminReceiver#DEVICE_ADMIN_META_DATA}. Otherwise an
15003      * {@link IllegalArgumentException} will be thrown.
15004      *
15005      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15006      * @param target which {@link DeviceAdminReceiver} we want the new administrator to be.
15007      * @param bundle data to be sent to the new administrator.
15008      * @throws SecurityException if {@code admin} is not a device owner nor a profile owner.
15009      * @throws IllegalArgumentException if {@code admin} or {@code target} is {@code null}, they
15010      * are components in the same package or {@code target} is not an active admin.
15011      */
transferOwnership(@onNull ComponentName admin, @NonNull ComponentName target, @Nullable PersistableBundle bundle)15012     public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
15013             @Nullable PersistableBundle bundle) {
15014         throwIfParentInstance("transferOwnership");
15015         try {
15016             mService.transferOwnership(admin, target, bundle);
15017         } catch (RemoteException re) {
15018             throw re.rethrowFromSystemServer();
15019         }
15020     }
15021 
15022     /**
15023      * Called by a device owner to specify the user session start message. This may be displayed
15024      * during a user switch.
15025      * <p>
15026      * The message should be limited to a short statement or it may be truncated.
15027      * <p>
15028      * If the message needs to be localized, it is the responsibility of the
15029      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
15030      * and set a new version of this message accordingly.
15031      *
15032      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15033      * @param startUserSessionMessage message for starting user session, or {@code null} to use
15034      * system default message.
15035      * @throws SecurityException if {@code admin} is not a device owner.
15036      */
setStartUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence startUserSessionMessage)15037     public void setStartUserSessionMessage(
15038             @NonNull ComponentName admin, @Nullable CharSequence startUserSessionMessage) {
15039         throwIfParentInstance("setStartUserSessionMessage");
15040         try {
15041             mService.setStartUserSessionMessage(admin, startUserSessionMessage);
15042         } catch (RemoteException re) {
15043             throw re.rethrowFromSystemServer();
15044         }
15045     }
15046 
15047     /**
15048      * Called by a device owner to specify the user session end message. This may be displayed
15049      * during a user switch.
15050      * <p>
15051      * The message should be limited to a short statement or it may be truncated.
15052      * <p>
15053      * If the message needs to be localized, it is the responsibility of the
15054      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
15055      * and set a new version of this message accordingly.
15056      *
15057      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15058      * @param endUserSessionMessage message for ending user session, or {@code null} to use system
15059      * default message.
15060      * @throws SecurityException if {@code admin} is not a device owner.
15061      */
setEndUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence endUserSessionMessage)15062     public void setEndUserSessionMessage(
15063             @NonNull ComponentName admin, @Nullable CharSequence endUserSessionMessage) {
15064         throwIfParentInstance("setEndUserSessionMessage");
15065         try {
15066             mService.setEndUserSessionMessage(admin, endUserSessionMessage);
15067         } catch (RemoteException re) {
15068             throw re.rethrowFromSystemServer();
15069         }
15070     }
15071 
15072     /**
15073      * Returns the user session start message.
15074      *
15075      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15076      * @throws SecurityException if {@code admin} is not a device owner.
15077      */
getStartUserSessionMessage(@onNull ComponentName admin)15078     public CharSequence getStartUserSessionMessage(@NonNull ComponentName admin) {
15079         throwIfParentInstance("getStartUserSessionMessage");
15080         try {
15081             return mService.getStartUserSessionMessage(admin);
15082         } catch (RemoteException re) {
15083             throw re.rethrowFromSystemServer();
15084         }
15085     }
15086 
15087     /**
15088      * Returns the user session end message.
15089      *
15090      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15091      * @throws SecurityException if {@code admin} is not a device owner.
15092      */
getEndUserSessionMessage(@onNull ComponentName admin)15093     public CharSequence getEndUserSessionMessage(@NonNull ComponentName admin) {
15094         throwIfParentInstance("getEndUserSessionMessage");
15095         try {
15096             return mService.getEndUserSessionMessage(admin);
15097         } catch (RemoteException re) {
15098             throw re.rethrowFromSystemServer();
15099         }
15100     }
15101 
15102     /**
15103      * Called by device owner or managed profile owner to add an override APN.
15104      *
15105      * <p>This method may returns {@code -1} if {@code apnSetting} conflicts with an existing
15106      * override APN. Update the existing conflicted APN with
15107      * {@link #updateOverrideApn(ComponentName, int, ApnSetting)} instead of adding a new entry.
15108      * <p>Two override APNs are considered to conflict when all the following APIs return
15109      * the same values on both override APNs:
15110      * <ul>
15111      *   <li>{@link ApnSetting#getOperatorNumeric()}</li>
15112      *   <li>{@link ApnSetting#getApnName()}</li>
15113      *   <li>{@link ApnSetting#getProxyAddressAsString()}</li>
15114      *   <li>{@link ApnSetting#getProxyPort()}</li>
15115      *   <li>{@link ApnSetting#getMmsProxyAddressAsString()}</li>
15116      *   <li>{@link ApnSetting#getMmsProxyPort()}</li>
15117      *   <li>{@link ApnSetting#getMmsc()}</li>
15118      *   <li>{@link ApnSetting#isEnabled()}</li>
15119      *   <li>{@link ApnSetting#getMvnoType()}</li>
15120      *   <li>{@link ApnSetting#getProtocol()}</li>
15121      *   <li>{@link ApnSetting#getRoamingProtocol()}</li>
15122      * </ul>
15123      *
15124      * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
15125      * Only device owners can add APNs.
15126      * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
15127      * Both device owners and managed profile owners can add enterprise APNs
15128      * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can add other type of APNs.
15129      * Enterprise APNs are specific to the managed profile and do not override any user-configured
15130      * VPNs. They are prerequisites for enabling preferential network service on the managed
15131      * profile on 4G networks ({@link #setPreferentialNetworkServiceConfigs}).
15132      *
15133      * @param admin which {@link DeviceAdminReceiver} this request is associated with
15134      * @param apnSetting the override APN to insert
15135      * @return The {@code id} of inserted override APN. Or {@code -1} when failed to insert into
15136      *         the database.
15137      * @throws SecurityException If request is for enterprise APN {@code admin} is either device
15138      * owner or profile owner and in all other types of APN if {@code admin} is not a device owner.
15139      *
15140      * @see #setOverrideApnsEnabled(ComponentName, boolean)
15141      */
addOverrideApn(@onNull ComponentName admin, @NonNull ApnSetting apnSetting)15142     public int addOverrideApn(@NonNull ComponentName admin, @NonNull ApnSetting apnSetting) {
15143         throwIfParentInstance("addOverrideApn");
15144         if (mService != null) {
15145             try {
15146                 return mService.addOverrideApn(admin, apnSetting);
15147             } catch (RemoteException e) {
15148                 throw e.rethrowFromSystemServer();
15149             }
15150         }
15151         return -1;
15152     }
15153 
15154     /**
15155      * Called by device owner or managed profile owner to update an override APN.
15156      *
15157      * <p>This method may returns {@code false} if there is no override APN with the given
15158      * {@code apnId}.
15159      * <p>This method may also returns {@code false} if {@code apnSetting} conflicts with an
15160      * existing override APN. Update the existing conflicted APN instead.
15161      * <p>See {@link #addOverrideApn} for the definition of conflict.
15162      * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
15163      * Only device owners can update APNs.
15164      * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
15165      * Both device owners and managed profile owners can update enterprise APNs
15166      * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can update other type of APNs.
15167      *
15168      * @param admin which {@link DeviceAdminReceiver} this request is associated with
15169      * @param apnId the {@code id} of the override APN to update
15170      * @param apnSetting the override APN to update
15171      * @return {@code true} if the required override APN is successfully updated,
15172      *         {@code false} otherwise.
15173      * @throws SecurityException If request is for enterprise APN {@code admin} is either device
15174      * owner or profile owner and in all other types of APN if {@code admin} is not a device owner.
15175      *
15176      * @see #setOverrideApnsEnabled(ComponentName, boolean)
15177      */
updateOverrideApn(@onNull ComponentName admin, int apnId, @NonNull ApnSetting apnSetting)15178     public boolean updateOverrideApn(@NonNull ComponentName admin, int apnId,
15179             @NonNull ApnSetting apnSetting) {
15180         throwIfParentInstance("updateOverrideApn");
15181         if (mService != null) {
15182             try {
15183                 return mService.updateOverrideApn(admin, apnId, apnSetting);
15184             } catch (RemoteException e) {
15185                 throw e.rethrowFromSystemServer();
15186             }
15187         }
15188         return false;
15189     }
15190 
15191     /**
15192      * Called by device owner or managed profile owner to remove an override APN.
15193      *
15194      * <p>This method may returns {@code false} if there is no override APN with the given
15195      * {@code apnId}.
15196      * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
15197      * Only device owners can remove APNs.
15198      * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
15199      * Both device owners and managed profile owners can remove enterprise APNs
15200      * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can remove other type of APNs.
15201      *
15202      * @param admin which {@link DeviceAdminReceiver} this request is associated with
15203      * @param apnId the {@code id} of the override APN to remove
15204      * @return {@code true} if the required override APN is successfully removed, {@code false}
15205      *         otherwise.
15206      * @throws SecurityException If request is for enterprise APN {@code admin} is either device
15207      * owner or profile owner and in all other types of APN if {@code admin} is not a device owner.
15208      *
15209      * @see #setOverrideApnsEnabled(ComponentName, boolean)
15210      */
removeOverrideApn(@onNull ComponentName admin, int apnId)15211     public boolean removeOverrideApn(@NonNull ComponentName admin, int apnId) {
15212         throwIfParentInstance("removeOverrideApn");
15213         if (mService != null) {
15214             try {
15215                 return mService.removeOverrideApn(admin, apnId);
15216             } catch (RemoteException e) {
15217                 throw e.rethrowFromSystemServer();
15218             }
15219         }
15220         return false;
15221     }
15222 
15223     /**
15224      * Called by device owner or managed profile owner to get all override APNs inserted by
15225      * device owner or managed profile owner previously using {@link #addOverrideApn}.
15226      *
15227      * @param admin which {@link DeviceAdminReceiver} this request is associated with
15228      * @return A list of override APNs inserted by device owner.
15229      * @throws SecurityException if {@code admin} is not a device owner.
15230      *
15231      * @see #setOverrideApnsEnabled(ComponentName, boolean)
15232      */
getOverrideApns(@onNull ComponentName admin)15233     public List<ApnSetting> getOverrideApns(@NonNull ComponentName admin) {
15234         throwIfParentInstance("getOverrideApns");
15235         if (mService != null) {
15236             try {
15237                 return mService.getOverrideApns(admin);
15238             } catch (RemoteException e) {
15239                 throw e.rethrowFromSystemServer();
15240             }
15241         }
15242         return Collections.emptyList();
15243     }
15244 
15245     /**
15246      * Called by device owner to set if override APNs should be enabled.
15247      * <p> Override APNs are separated from other APNs on the device, and can only be inserted or
15248      * modified by the device owner. When enabled, only override APNs are in use, any other APNs
15249      * are ignored.
15250      * <p>Note: Enterprise APNs added by managed profile owners do not need to be enabled by
15251      * this API. They are part of the preferential network service config and is controlled by
15252      * {@link #setPreferentialNetworkServiceConfigs}.
15253      *
15254      * @param admin which {@link DeviceAdminReceiver} this request is associated with
15255      * @param enabled {@code true} if override APNs should be enabled, {@code false} otherwise
15256      * @throws SecurityException if {@code admin} is not a device owner.
15257      */
setOverrideApnsEnabled(@onNull ComponentName admin, boolean enabled)15258     public void setOverrideApnsEnabled(@NonNull ComponentName admin, boolean enabled) {
15259         throwIfParentInstance("setOverrideApnEnabled");
15260         if (mService != null) {
15261             try {
15262                 mService.setOverrideApnsEnabled(admin, enabled);
15263             } catch (RemoteException e) {
15264                 throw e.rethrowFromSystemServer();
15265             }
15266         }
15267     }
15268 
15269     /**
15270      * Called by device owner to check if override APNs are currently enabled.
15271      *
15272      * @param admin which {@link DeviceAdminReceiver} this request is associated with
15273      * @return {@code true} if override APNs are currently enabled, {@code false} otherwise.
15274      * @throws SecurityException if {@code admin} is not a device owner.
15275      *
15276      * @see #setOverrideApnsEnabled(ComponentName, boolean)
15277      */
isOverrideApnEnabled(@onNull ComponentName admin)15278     public boolean isOverrideApnEnabled(@NonNull ComponentName admin) {
15279         throwIfParentInstance("isOverrideApnEnabled");
15280         if (mService != null) {
15281             try {
15282                 return mService.isOverrideApnEnabled(admin);
15283             } catch (RemoteException e) {
15284                 throw e.rethrowFromSystemServer();
15285             }
15286         }
15287         return false;
15288     }
15289 
15290     /**
15291      * Returns the data passed from the current administrator to the new administrator during an
15292      * ownership transfer. This is the same {@code bundle} passed in
15293      * {@link #transferOwnership(ComponentName, ComponentName, PersistableBundle)}. The bundle is
15294      * persisted until the profile owner or device owner is removed.
15295      *
15296      * <p>This is the same <code>bundle</code> received in the
15297      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}.
15298      * Use this method to retrieve it after the transfer as long as the new administrator is the
15299      * active device or profile owner.
15300      *
15301      * <p>Returns <code>null</code> if no ownership transfer was started for the calling user.
15302      *
15303      * @see #transferOwnership
15304      * @see DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)
15305      * @throws SecurityException if the caller is not a device or profile owner.
15306      */
15307     @Nullable
getTransferOwnershipBundle()15308     public PersistableBundle getTransferOwnershipBundle() {
15309         throwIfParentInstance("getTransferOwnershipBundle");
15310         try {
15311             return mService.getTransferOwnershipBundle();
15312         } catch (RemoteException re) {
15313             throw re.rethrowFromSystemServer();
15314         }
15315     }
15316 
15317     /**
15318      * Sets the global Private DNS mode to opportunistic.
15319      * May only be called by the device owner.
15320      *
15321      * <p>In this mode, the DNS subsystem will attempt a TLS handshake to the network-supplied
15322      * resolver prior to attempting name resolution in cleartext.
15323      *
15324      * <p>Note: The device owner won't be able to set the global private DNS mode if there are
15325      * unaffiliated secondary users or profiles on the device. It's recommended that affiliation
15326      * ids are set for new users as soon as possible after provisioning via
15327      * {@link #setAffiliationIds}.
15328      *
15329      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15330      *
15331      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully, or
15332      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set.
15333      *
15334      * @throws SecurityException if the caller is not the device owner.
15335      */
setGlobalPrivateDnsModeOpportunistic( @onNull ComponentName admin)15336     public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeOpportunistic(
15337             @NonNull ComponentName admin) {
15338         throwIfParentInstance("setGlobalPrivateDnsModeOpportunistic");
15339 
15340         if (mService == null) {
15341             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
15342         }
15343 
15344         try {
15345             return mService.setGlobalPrivateDns(admin, PRIVATE_DNS_MODE_OPPORTUNISTIC, null);
15346         } catch (RemoteException re) {
15347             throw re.rethrowFromSystemServer();
15348         }
15349     }
15350 
15351     /**
15352      * Sets the global Private DNS host to be used.
15353      * May only be called by the device owner.
15354      *
15355      * <p>Note that the method is blocking as it will perform a connectivity check to the resolver,
15356      * to ensure it is valid. Because of that, the method should not be called on any thread that
15357      * relates to user interaction, such as the UI thread.
15358      *
15359      * <p>In case a VPN is used in conjunction with Private DNS resolver, the Private DNS resolver
15360      * must be reachable both from within and outside the VPN. Otherwise, the device may lose
15361      * the ability to resolve hostnames as system traffic to the resolver may not go through the
15362      * VPN.
15363      *
15364      * <p>Note: The device owner won't be able to set the global private DNS mode if there are
15365      * unaffiliated secondary users or profiles on the device. It's recommended that affiliation
15366      * ids are set for new users as soon as possible after provisioning via
15367      * {@link #setAffiliationIds}.
15368      *
15369      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15370      * @param privateDnsHost The hostname of a server that implements DNS over TLS (RFC7858).
15371      *
15372      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully,
15373      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set or
15374      *         {@code PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING} if the specified host does not
15375      *         implement RFC7858.
15376      *
15377      * @throws IllegalArgumentException if the {@code privateDnsHost} is not a valid hostname.
15378      *
15379      * @throws SecurityException if the caller is not the device owner.
15380      */
setGlobalPrivateDnsModeSpecifiedHost( @onNull ComponentName admin, @NonNull String privateDnsHost)15381     @WorkerThread public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeSpecifiedHost(
15382             @NonNull ComponentName admin, @NonNull String privateDnsHost) {
15383         throwIfParentInstance("setGlobalPrivateDnsModeSpecifiedHost");
15384         Objects.requireNonNull(privateDnsHost, "dns resolver is null");
15385 
15386         if (mService == null) {
15387             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
15388         }
15389 
15390         if (NetworkUtilsInternal.isWeaklyValidatedHostname(privateDnsHost)) {
15391             if (!PrivateDnsConnectivityChecker.canConnectToPrivateDnsServer(privateDnsHost)) {
15392                 return PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING;
15393             }
15394         }
15395 
15396         try {
15397             return mService.setGlobalPrivateDns(
15398                     admin, PRIVATE_DNS_MODE_PROVIDER_HOSTNAME, privateDnsHost);
15399         } catch (RemoteException re) {
15400             throw re.rethrowFromSystemServer();
15401         }
15402     }
15403 
15404     /**
15405      * Called by device owner or profile owner of an organization-owned managed profile to install
15406      * a system update from the given file. The device will be
15407      * rebooted in order to finish installing the update. Note that if the device is rebooted, this
15408      * doesn't necessarily mean that the update has been applied successfully. The caller should
15409      * additionally check the system version with {@link android.os.Build#FINGERPRINT} or {@link
15410      * android.os.Build.VERSION}. If an error occurs during processing the OTA before the reboot,
15411      * the caller will be notified by {@link InstallSystemUpdateCallback}. If device does not have
15412      * sufficient battery level, the installation will fail with error {@link
15413      * InstallSystemUpdateCallback#UPDATE_ERROR_BATTERY_LOW}.
15414      *
15415      * @param admin The {@link DeviceAdminReceiver} that this request is associated with. Null if
15416      *              the caller is not a device admin
15417      * @param updateFilePath A Uri of the file that contains the update. The file should be
15418      * readable by the calling app.
15419      * @param executor The executor through which the callback should be invoked.
15420      * @param callback A callback object that will inform the caller when installing an update
15421      * fails.
15422      */
15423     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SYSTEM_UPDATES, conditional = true)
installSystemUpdate( @ullable ComponentName admin, @NonNull Uri updateFilePath, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)15424     public void installSystemUpdate(
15425             @Nullable ComponentName admin, @NonNull Uri updateFilePath,
15426             @NonNull @CallbackExecutor Executor executor,
15427             @NonNull InstallSystemUpdateCallback callback) {
15428         throwIfParentInstance("installUpdate");
15429         if (mService == null) {
15430             return;
15431         }
15432         try (ParcelFileDescriptor fileDescriptor = mContext.getContentResolver()
15433                     .openFileDescriptor(updateFilePath, "r")) {
15434             mService.installUpdateFromFile(
15435                     admin, mContext.getPackageName(), fileDescriptor,
15436                     new StartInstallingUpdateCallback.Stub() {
15437                         @Override
15438                         public void onStartInstallingUpdateError(
15439                                 int errorCode, String errorMessage) {
15440                             executeCallback(errorCode, errorMessage, executor, callback);
15441                         }
15442                     });
15443         } catch (RemoteException e) {
15444             throw e.rethrowFromSystemServer();
15445         } catch (FileNotFoundException e) {
15446             Log.w(TAG, e);
15447             executeCallback(
15448                     InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
15449                     Log.getStackTraceString(e),
15450                     executor, callback);
15451         } catch (IOException e) {
15452             Log.w(TAG, e);
15453             executeCallback(
15454                     InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN, Log.getStackTraceString(e),
15455                     executor, callback);
15456         }
15457     }
15458 
executeCallback(int errorCode, String errorMessage, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)15459     private void executeCallback(int errorCode, String errorMessage,
15460             @NonNull @CallbackExecutor Executor executor,
15461             @NonNull InstallSystemUpdateCallback callback) {
15462         executor.execute(() -> callback.onInstallUpdateError(errorCode, errorMessage));
15463     }
15464 
15465     /**
15466      * Returns the system-wide Private DNS mode.
15467      *
15468      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15469      * @return one of {@code PRIVATE_DNS_MODE_OFF}, {@code PRIVATE_DNS_MODE_OPPORTUNISTIC},
15470      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} or {@code PRIVATE_DNS_MODE_UNKNOWN}.
15471      * @throws SecurityException if the caller is not the device owner.
15472      */
getGlobalPrivateDnsMode(@onNull ComponentName admin)15473     public int getGlobalPrivateDnsMode(@NonNull ComponentName admin) {
15474         throwIfParentInstance("setGlobalPrivateDns");
15475         if (mService == null) {
15476             return PRIVATE_DNS_MODE_UNKNOWN;
15477         }
15478 
15479         try {
15480             return mService.getGlobalPrivateDnsMode(admin);
15481         } catch (RemoteException re) {
15482             throw re.rethrowFromSystemServer();
15483         }
15484     }
15485 
15486     /**
15487      * Returns the system-wide Private DNS host.
15488      *
15489      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15490      * @return The hostname used for Private DNS queries, null if none is set.
15491      * @throws SecurityException if the caller is not the device owner.
15492      */
getGlobalPrivateDnsHost(@onNull ComponentName admin)15493     public @Nullable String getGlobalPrivateDnsHost(@NonNull ComponentName admin) {
15494         throwIfParentInstance("setGlobalPrivateDns");
15495         if (mService == null) {
15496             return null;
15497         }
15498 
15499         try {
15500             return mService.getGlobalPrivateDnsHost(admin);
15501         } catch (RemoteException re) {
15502             throw re.rethrowFromSystemServer();
15503         }
15504     }
15505 
15506     /**
15507      * Deprecated. Use {@code markProfileOwnerOnOrganizationOwnedDevice} instead.
15508      * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#Q} or
15509      * below, will behave the same as {@link #setProfileOwnerOnOrganizationOwnedDevice}.
15510      *
15511      * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#R}
15512      * or above, will throw an UnsupportedOperationException when called.
15513      *
15514      * @deprecated Use {@link #setProfileOwnerOnOrganizationOwnedDevice} instead.
15515      *
15516      * @hide
15517      */
15518     @Deprecated
15519     @SystemApi
15520     @RequiresPermission(value = android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS,
15521             conditional = true)
setProfileOwnerCanAccessDeviceIds(@onNull ComponentName who)15522     public void setProfileOwnerCanAccessDeviceIds(@NonNull ComponentName who) {
15523         ApplicationInfo ai = mContext.getApplicationInfo();
15524         if (ai.targetSdkVersion > Build.VERSION_CODES.Q) {
15525             throw new UnsupportedOperationException(
15526                     "This method is deprecated. use markProfileOwnerOnOrganizationOwnedDevice"
15527                     + " instead.");
15528         } else {
15529             setProfileOwnerOnOrganizationOwnedDevice(who, true);
15530         }
15531     }
15532 
15533     /**
15534      * Sets whether the profile owner of the given user as managing an organization-owned device.
15535      * Managing an organization-owned device will give it access to device identifiers (such as
15536      * serial number, IMEI and MEID) as well as other privileges.
15537      *
15538      * @hide
15539      */
15540     @TestApi
15541     @RequiresPermission(anyOf = {
15542             android.Manifest.permission.MARK_DEVICE_ORGANIZATION_OWNED,
15543             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
15544             }, conditional = true)
setProfileOwnerOnOrganizationOwnedDevice(@onNull ComponentName who, boolean isProfileOwnerOnOrganizationOwnedDevice)15545     public void setProfileOwnerOnOrganizationOwnedDevice(@NonNull ComponentName who,
15546             boolean isProfileOwnerOnOrganizationOwnedDevice) {
15547         if (mService == null) {
15548             return;
15549         }
15550         try {
15551             mService.setProfileOwnerOnOrganizationOwnedDevice(who, myUserId(),
15552                     isProfileOwnerOnOrganizationOwnedDevice);
15553         } catch (RemoteException re) {
15554             throw re.rethrowFromSystemServer();
15555         }
15556     }
15557 
15558     /**
15559      * Allows a set of packages to access cross-profile calendar APIs.
15560      *
15561      * <p>Called by a profile owner of a managed profile.
15562      *
15563      * <p>Calling with a {@code null} value for the set disables the restriction so that all
15564      * packages are allowed to access cross-profile calendar APIs. Calling with an empty set
15565      * disallows all packages from accessing cross-profile calendar APIs. If this method isn't
15566      * called, no package is allowed to access cross-profile calendar APIs by default.
15567      *
15568      * @param admin which {@link DeviceAdminReceiver} this request is associated with
15569      * @param packageNames set of packages to be allowlisted
15570      * @throws SecurityException if {@code admin} is not a profile owner
15571      *
15572      * @see #getCrossProfileCalendarPackages(ComponentName)
15573      * @deprecated Use {@link #setCrossProfilePackages(ComponentName, Set)}.
15574      */
15575     @Deprecated
setCrossProfileCalendarPackages(@onNull ComponentName admin, @Nullable Set<String> packageNames)15576     public void setCrossProfileCalendarPackages(@NonNull ComponentName admin,
15577             @Nullable Set<String> packageNames) {
15578         throwIfParentInstance("setCrossProfileCalendarPackages");
15579         if (mService != null) {
15580             try {
15581                 mService.setCrossProfileCalendarPackages(admin, packageNames == null ? null
15582                         : new ArrayList<>(packageNames));
15583             } catch (RemoteException e) {
15584                 throw e.rethrowFromSystemServer();
15585             }
15586         }
15587     }
15588 
15589     /**
15590      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
15591      *
15592      * <p>Called by a profile owner of a managed profile.
15593      *
15594      * @param admin which {@link DeviceAdminReceiver} this request is associated with
15595      * @return the set of names of packages that were previously allowed via
15596      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
15597      * empty set if none have been allowed
15598      * @throws SecurityException if {@code admin} is not a profile owner
15599      *
15600      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
15601      * @deprecated Use {@link #setCrossProfilePackages(ComponentName, Set)}.
15602      */
15603     @Deprecated
getCrossProfileCalendarPackages(@onNull ComponentName admin)15604     public @Nullable Set<String> getCrossProfileCalendarPackages(@NonNull ComponentName admin) {
15605         throwIfParentInstance("getCrossProfileCalendarPackages");
15606         if (mService != null) {
15607             try {
15608                 final List<String> packageNames = mService.getCrossProfileCalendarPackages(admin);
15609                 return packageNames == null ? null : new ArraySet<>(packageNames);
15610             } catch (RemoteException e) {
15611                 throw e.rethrowFromSystemServer();
15612             }
15613         }
15614         return Collections.emptySet();
15615     }
15616 
15617     /**
15618      * Returns if a package is allowed to access cross-profile calendar APIs.
15619      *
15620      * <p>A package is allowed to access cross-profile calendar APIs if it's allowed by
15621      * admins via {@link #setCrossProfileCalendarPackages(ComponentName, Set)} and
15622      * {@link android.provider.Settings.Secure#CROSS_PROFILE_CALENDAR_ENABLED}
15623      * is turned on in the managed profile.
15624      *
15625      * <p>To query for a specific user, use
15626      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
15627      * that user, and get a {@link DevicePolicyManager} from this context.
15628      *
15629      * @param packageName the name of the package
15630      * @return {@code true} if the package is allowed to access cross-profile calendar APIs,
15631      * {@code false} otherwise
15632      *
15633      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
15634      * @see #getCrossProfileCalendarPackages(ComponentName)
15635      * @hide
15636      */
15637     @RequiresPermission(anyOf = {
15638             INTERACT_ACROSS_USERS_FULL,
15639             permission.INTERACT_ACROSS_USERS
15640     }, conditional = true)
isPackageAllowedToAccessCalendar(@onNull String packageName)15641     public boolean isPackageAllowedToAccessCalendar(@NonNull  String packageName) {
15642         throwIfParentInstance("isPackageAllowedToAccessCalendar");
15643         if (mService != null) {
15644             try {
15645                 return mService.isPackageAllowedToAccessCalendarForUser(packageName,
15646                         myUserId());
15647             } catch (RemoteException e) {
15648                 throw e.rethrowFromSystemServer();
15649             }
15650         }
15651         return false;
15652     }
15653 
15654     /**
15655      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
15656      *
15657      * <p>To query for a specific user, use
15658      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
15659      * that user, and get a {@link DevicePolicyManager} from this context.
15660      *
15661      * @return the set of names of packages that were previously allowed via
15662      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
15663      * empty set if none have been allowed
15664      *
15665      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
15666      * @see #getCrossProfileCalendarPackages(ComponentName)
15667      * @hide
15668      */
15669     @RequiresPermission(anyOf = {
15670             INTERACT_ACROSS_USERS_FULL,
15671             permission.INTERACT_ACROSS_USERS
15672     })
getCrossProfileCalendarPackages()15673     public @Nullable Set<String> getCrossProfileCalendarPackages() {
15674         throwIfParentInstance("getCrossProfileCalendarPackages");
15675         if (mService != null) {
15676             try {
15677                 final List<String> packageNames = mService.getCrossProfileCalendarPackagesForUser(
15678                         myUserId());
15679                 return packageNames == null ? null : new ArraySet<>(packageNames);
15680             } catch (RemoteException e) {
15681                 throw e.rethrowFromSystemServer();
15682             }
15683         }
15684         return Collections.emptySet();
15685     }
15686 
15687     /**
15688      * Sets the set of admin-allowlisted package names that are allowed to request user consent for
15689      * cross-profile communication.
15690      *
15691      * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
15692      *
15693      * <p>Previous calls are overridden by each subsequent call to this method.
15694      *
15695      * <p>Note that other apps may be able to request user consent for cross-profile communication
15696      * if they have been explicitly allowlisted by the OEM.
15697      *
15698      * <p>When previously-set cross-profile packages are missing from {@code packageNames}, the
15699      * app-op for {@code INTERACT_ACROSS_PROFILES} will be reset for those packages. This will not
15700      * occur for packages that are allowlisted by the OEM.
15701      *
15702      * @param admin the {@link DeviceAdminReceiver} this request is associated with
15703      * @param packageNames the new cross-profile package names
15704      */
setCrossProfilePackages( @onNull ComponentName admin, @NonNull Set<String> packageNames)15705     public void setCrossProfilePackages(
15706             @NonNull ComponentName admin, @NonNull Set<String> packageNames) {
15707         throwIfParentInstance("setCrossProfilePackages");
15708         if (mService != null) {
15709             try {
15710                 mService.setCrossProfilePackages(admin, new ArrayList<>(packageNames));
15711             } catch (RemoteException e) {
15712                 throw e.rethrowFromSystemServer();
15713             }
15714         }
15715     }
15716 
15717     /**
15718      * Returns the set of package names that the admin has previously set as allowed to request user
15719      * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
15720      * Set)}.
15721      *
15722      * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
15723      *
15724      * <p>Note that other apps not included in the returned set may be able to request user consent
15725      * for cross-profile communication if they have been explicitly allowlisted by the OEM.
15726      *
15727      * @param admin the {@link DeviceAdminReceiver} this request is associated with
15728      * @return the set of package names the admin has previously set as allowed to request user
15729      * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
15730      * Set)}
15731      */
getCrossProfilePackages(@onNull ComponentName admin)15732     public @NonNull Set<String> getCrossProfilePackages(@NonNull ComponentName admin) {
15733         throwIfParentInstance("getCrossProfilePackages");
15734         if (mService != null) {
15735             try {
15736                 return new ArraySet<>(mService.getCrossProfilePackages(admin));
15737             } catch (RemoteException e) {
15738                 throw e.rethrowFromSystemServer();
15739             }
15740         }
15741         return Collections.emptySet();
15742     }
15743 
15744     /**
15745      * Returns the combined set of the following:
15746      * <ul>
15747      * <li>The package names that the admin has previously set as allowed to request user consent
15748      * for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
15749      * Set)}.</li>
15750      * <li>The default package names set by the OEM that are allowed to request user consent for
15751      * cross-profile communication without being explicitly enabled by the admin, via {@link
15752      * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array
15753      * #vendor_cross_profile_apps}.</li>
15754      * </ul>
15755      *
15756      * @return the combined set of allowlisted package names set via
15757      * {@link #setCrossProfilePackages(ComponentName, Set)}, {@link com.android.internal.R.array
15758      * #cross_profile_apps}, and {@link com.android.internal.R.array#vendor_cross_profile_apps}.
15759      *
15760      * @hide
15761      */
15762     @RequiresPermission(anyOf = {
15763             INTERACT_ACROSS_USERS_FULL,
15764             permission.INTERACT_ACROSS_USERS,
15765             permission.INTERACT_ACROSS_PROFILES
15766     })
getAllCrossProfilePackages()15767     public @NonNull Set<String> getAllCrossProfilePackages() {
15768         throwIfParentInstance("getAllCrossProfilePackages");
15769         if (mService != null) {
15770             try {
15771                 return new ArraySet<>(mService.getAllCrossProfilePackages(mContext.getUserId()));
15772             } catch (RemoteException e) {
15773                 throw e.rethrowFromSystemServer();
15774             }
15775         }
15776         return Collections.emptySet();
15777     }
15778 
15779     /**
15780      * Returns the default package names set by the OEM that are allowed to communicate
15781      * cross-profile without being explicitly enabled by the admin, via {@link
15782      * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array
15783      * #vendor_cross_profile_apps}.
15784      *
15785      * @hide
15786      */
15787     @TestApi
getDefaultCrossProfilePackages()15788     public @NonNull Set<String> getDefaultCrossProfilePackages() {
15789         throwIfParentInstance("getDefaultCrossProfilePackages");
15790         if (mService != null) {
15791             try {
15792                 return new ArraySet<>(mService.getDefaultCrossProfilePackages());
15793             } catch (RemoteException e) {
15794                 throw e.rethrowFromSystemServer();
15795             }
15796         }
15797         return Collections.emptySet();
15798     }
15799 
15800     /**
15801      * Returns whether the device is being used as a managed kiosk. These requirements are as
15802      * follows:
15803      * <ul>
15804      *     <li>The device is in Lock Task (therefore there is also a Device Owner app on the
15805      *     device)</li>
15806      *     <li>The Lock Task feature {@link DevicePolicyManager#LOCK_TASK_FEATURE_SYSTEM_INFO} is
15807      *     not enabled, so the system info in the status bar is not visible</li>
15808      *     <li>The device does not have a secure lock screen (e.g. it has no lock screen or has
15809      *     swipe-to-unlock)</li>
15810      *     <li>The device is not in the middle of an ephemeral user session</li>
15811      * </ul>
15812      *
15813      * <p>Publicly-accessible dedicated devices don't have the same privacy model as
15814      * personally-used devices. In particular, user consent popups don't make sense as a barrier to
15815      * accessing persistent data on these devices since the user giving consent and the user whose
15816      * data is on the device are unlikely to be the same. These consent popups prevent the true
15817      * remote management of these devices.
15818      *
15819      * <p>This condition is not sufficient to cover APIs that would access data that only lives for
15820      * the duration of the user's session, since the user has an expectation of privacy in these
15821      * conditions that more closely resembles use of a personal device. In those cases, see {@link
15822      * #isUnattendedManagedKiosk()}.
15823      *
15824      * @hide
15825      */
15826     @SystemApi
15827     @RequiresPermission(anyOf = {
15828             android.Manifest.permission.MANAGE_USERS,
15829             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
15830     })
isManagedKiosk()15831     public boolean isManagedKiosk() {
15832         throwIfParentInstance("isManagedKiosk");
15833         if (mService != null) {
15834             try {
15835                 return mService.isManagedKiosk();
15836             } catch (RemoteException e) {
15837                 throw e.rethrowFromSystemServer();
15838             }
15839         }
15840         return false;
15841     }
15842 
15843     /**
15844      * Returns whether the device is being used as an unattended managed kiosk. These requirements
15845      * are as follows:
15846      * <ul>
15847      *     <li>The device is being used as a managed kiosk, as defined at {@link
15848      *     #isManagedKiosk()}</li>
15849      *     <li>The device has not received user input for at least 30 minutes</li>
15850      * </ul>
15851      *
15852      * <p>See {@link #isManagedKiosk()} for context. This is a stronger requirement that also
15853      * ensures that the device hasn't been interacted with recently, making it an appropriate check
15854      * for privacy-sensitive APIs that wouldn't be appropriate during an active user session.
15855      *
15856      * @hide
15857      */
15858     @SystemApi
15859     @RequiresPermission(anyOf = {
15860             android.Manifest.permission.MANAGE_USERS,
15861             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
15862     })
isUnattendedManagedKiosk()15863     public boolean isUnattendedManagedKiosk() {
15864         throwIfParentInstance("isUnattendedManagedKiosk");
15865         if (mService != null) {
15866             try {
15867                 return mService.isUnattendedManagedKiosk();
15868             } catch (RemoteException e) {
15869                 throw e.rethrowFromSystemServer();
15870             }
15871         }
15872         return false;
15873     }
15874 
15875     /**
15876      * Starts an activity to view calendar events in the managed profile.
15877      *
15878      * @param eventId the id of the event to be viewed
15879      * @param start the start time of the event
15880      * @param end the end time of the event
15881      * @param allDay if the event is an all-day event
15882      * @param flags flags to be set for the intent
15883      * @return {@code true} if the activity is started successfully, {@code false} otherwise
15884      *
15885      * @see CalendarContract#startViewCalendarEventInManagedProfile(Context, String, long, long,
15886      * long, boolean, int)
15887      *
15888      * @hide
15889      */
startViewCalendarEventInManagedProfile(long eventId, long start, long end, boolean allDay, int flags)15890     public boolean startViewCalendarEventInManagedProfile(long eventId, long start, long end,
15891             boolean allDay, int flags) {
15892         throwIfParentInstance("startViewCalendarEventInManagedProfile");
15893         if (mService != null) {
15894             try {
15895                 return mService.startViewCalendarEventInManagedProfile(mContext.getPackageName(),
15896                         eventId, start, end, allDay, flags);
15897             } catch (RemoteException e) {
15898                 throw e.rethrowFromSystemServer();
15899             }
15900         }
15901         return false;
15902     }
15903 
15904     /**
15905      * Service-specific error code used in {@link #setApplicationExemptions(String, Set)} and
15906      * {@link #getApplicationExemptions(String)}.
15907      * @hide
15908      */
15909     public static final int ERROR_PACKAGE_NAME_NOT_FOUND = 1;
15910 
15911     /**
15912      * Called by an application with the
15913      * {@link  android.Manifest.permission#MANAGE_DEVICE_POLICY_APP_EXEMPTIONS} permission, to
15914      * grant platform restriction exemptions to a given application.
15915      *
15916      * @param  packageName The package name of the application to be exempt.
15917      * @param  exemptions The set of exemptions to be applied.
15918      * @throws SecurityException If the caller does not have
15919      *             {@link  android.Manifest.permission#MANAGE_DEVICE_POLICY_APP_EXEMPTIONS}
15920      * @throws NameNotFoundException If either the package is not installed or the package is not
15921      *              visible to the caller.
15922      * @hide
15923      */
15924     @SystemApi
15925     @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_POLICY_APP_EXEMPTIONS)
setApplicationExemptions(@onNull String packageName, @NonNull @ApplicationExemptionConstants Set<Integer> exemptions)15926     public void setApplicationExemptions(@NonNull String packageName,
15927             @NonNull @ApplicationExemptionConstants Set<Integer> exemptions)
15928             throws NameNotFoundException {
15929         throwIfParentInstance("setApplicationExemptions");
15930         if (mService != null) {
15931             try {
15932                 mService.setApplicationExemptions(mContext.getPackageName(), packageName,
15933                         ArrayUtils.convertToIntArray(new ArraySet<>(exemptions)));
15934             } catch (ServiceSpecificException e) {
15935                 switch (e.errorCode) {
15936                     case ERROR_PACKAGE_NAME_NOT_FOUND:
15937                         throw new NameNotFoundException(e.getMessage());
15938                     default:
15939                         throw new RuntimeException(
15940                                 "Unknown error setting application exemptions: " + e.errorCode, e);
15941                 }
15942             } catch (RemoteException e) {
15943                 throw e.rethrowFromSystemServer();
15944             }
15945         }
15946     }
15947 
15948     /**
15949      * Returns all the platform restriction exemptions currently applied to an application. Called
15950      * by an application with the
15951      * {@link  android.Manifest.permission#MANAGE_DEVICE_POLICY_APP_EXEMPTIONS} permission.
15952      *
15953      * @param  packageName The package name to check.
15954      * @return A set of platform restrictions an application is exempt from.
15955      * @throws SecurityException If the caller does not have
15956      *             {@link  android.Manifest.permission#MANAGE_DEVICE_POLICY_APP_EXEMPTIONS}
15957      * @throws NameNotFoundException If either the package is not installed or the package is not
15958      *              visible to the caller.
15959      * @hide
15960      */
15961     @NonNull
15962     @SystemApi
15963     @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_POLICY_APP_EXEMPTIONS)
getApplicationExemptions(@onNull String packageName)15964     public Set<Integer> getApplicationExemptions(@NonNull String packageName)
15965             throws NameNotFoundException {
15966         throwIfParentInstance("getApplicationExemptions");
15967         if (mService == null) {
15968             return Collections.emptySet();
15969         }
15970         try {
15971             return intArrayToSet(mService.getApplicationExemptions(packageName));
15972         } catch (ServiceSpecificException e) {
15973             switch (e.errorCode) {
15974                 case ERROR_PACKAGE_NAME_NOT_FOUND:
15975                     throw new NameNotFoundException(e.getMessage());
15976                 default:
15977                     throw new RuntimeException(
15978                             "Unknown error getting application exemptions: " + e.errorCode, e);
15979             }
15980         } catch (RemoteException e) {
15981             throw e.rethrowFromSystemServer();
15982         }
15983     }
15984 
intArrayToSet(int[] array)15985     private Set<Integer> intArrayToSet(int[] array) {
15986         Set<Integer> set = new ArraySet<>();
15987         for (int item : array) {
15988             set.add(item);
15989         }
15990         return set;
15991     }
15992 
15993     /**
15994      * Called by a device owner or a profile owner or holder of the permission
15995      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL} to disable user
15996      * control over apps. User will not be able to clear app data or force-stop packages. When
15997      * called by a device owner, applies to all users on the device. Packages with user control
15998      * disabled are exempted from App Standby Buckets.
15999      * <p>
16000      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the user control disabled
16001      * packages policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
16002      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
16003      * successfully set or not. This callback will contain:
16004      * <ul>
16005      * <li> The policy identifier
16006      * {@link DevicePolicyIdentifiers#USER_CONTROL_DISABLED_PACKAGES_POLICY}
16007      * <li> The {@link TargetUser} that this policy relates to
16008      * <li> The {@link PolicyUpdateResult}, which will be
16009      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
16010      * reason the policy failed to be set
16011      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
16012      * </ul>
16013      * If there has been a change to the policy,
16014      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
16015      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
16016      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
16017      * will contain the reason why the policy changed.
16018      *
16019      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
16020      *               caller is not a device admin.
16021      * @param packages The package names for the apps.
16022      * @throws SecurityException if {@code admin} is not a device owner or a profile owner or
16023      * holder of the permission
16024      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL}.
16025      */
16026     @RequiresPermission(value = MANAGE_DEVICE_POLICY_APPS_CONTROL, conditional = true)
16027     @SupportsCoexistence
setUserControlDisabledPackages(@ullable ComponentName admin, @NonNull List<String> packages)16028     public void setUserControlDisabledPackages(@Nullable ComponentName admin,
16029             @NonNull List<String> packages) {
16030         throwIfParentInstance("setUserControlDisabledPackages");
16031         if (mService != null) {
16032             try {
16033                 mService.setUserControlDisabledPackages(admin, mContext.getPackageName(), packages);
16034             } catch (RemoteException re) {
16035                 throw re.rethrowFromSystemServer();
16036             }
16037         }
16038     }
16039 
16040     /**
16041      * Returns the list of packages over which user control is disabled by a device or profile
16042      * owner or holders of the permission
16043      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL}.
16044      * <p>
16045      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the returned policy will be the
16046      * current resolved policy rather than the policy set by the calling admin.
16047      *
16048      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
16049      *               caller is not a device admin.
16050      * @throws SecurityException if {@code admin} is not a device or profile owner or holder of the
16051      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL}.
16052      */
16053     @RequiresPermission(value = MANAGE_DEVICE_POLICY_APPS_CONTROL, conditional = true)
16054     @NonNull
getUserControlDisabledPackages(@ullable ComponentName admin)16055     public List<String> getUserControlDisabledPackages(@Nullable ComponentName admin) {
16056         throwIfParentInstance("getUserControlDisabledPackages");
16057         if (mService != null) {
16058             try {
16059                 return mService.getUserControlDisabledPackages(admin, mContext.getPackageName());
16060             } catch (RemoteException re) {
16061                 throw re.rethrowFromSystemServer();
16062             }
16063         }
16064         return Collections.emptyList();
16065     }
16066 
16067     /**
16068      * Called by device owner or profile owner of an organization-owned managed profile to toggle
16069      * Common Criteria mode for the device. When the device is in Common Criteria mode,
16070      * certain device functionalities are tuned to meet the higher
16071      * security level required by Common Criteria certification. For example:
16072      * <ul>
16073      * <li> Bluetooth long term key material is additionally integrity-protected with AES-GCM. </li>
16074      * <li> WiFi configuration store is additionally integrity-protected with AES-GCM. </li>
16075      * </ul>
16076      * Common Criteria mode is disabled by default.
16077      *
16078      * <p><em>Note:</em> if Common Critera mode is turned off after being enabled previously,
16079      * all existing WiFi configurations will be lost.
16080      *
16081      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
16082      *              caller is not a device admin.
16083      * @param enabled whether Common Criteria mode should be enabled or not.
16084      */
16085     @RequiresPermission(value = MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE, conditional = true)
setCommonCriteriaModeEnabled(@ullable ComponentName admin, boolean enabled)16086     public void setCommonCriteriaModeEnabled(@Nullable ComponentName admin, boolean enabled) {
16087         throwIfParentInstance("setCommonCriteriaModeEnabled");
16088         if (mService != null) {
16089             try {
16090                 mService.setCommonCriteriaModeEnabled(admin, mContext.getPackageName(), enabled);
16091             } catch (RemoteException e) {
16092                 throw e.rethrowFromSystemServer();
16093             }
16094         }
16095     }
16096 
16097     /**
16098      * Returns whether Common Criteria mode is currently enabled. Device owner and profile owner of
16099      * an organization-owned managed profile can query its own Common Criteria mode setting by
16100      * calling this method with its admin {@link ComponentName}. Any caller can obtain the
16101      * aggregated device-wide Common Criteria mode state by passing {@code null} as the
16102      * {@code admin} argument.
16103      *
16104      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
16105      *              caller is not a device admin.
16106      * @return {@code true} if Common Criteria mode is enabled, {@code false} otherwise.
16107      */
isCommonCriteriaModeEnabled(@ullable ComponentName admin)16108     public boolean isCommonCriteriaModeEnabled(@Nullable ComponentName admin) {
16109         throwIfParentInstance("isCommonCriteriaModeEnabled");
16110         if (mService != null) {
16111             try {
16112                 return mService.isCommonCriteriaModeEnabled(admin);
16113             } catch (RemoteException e) {
16114                 throw e.rethrowFromSystemServer();
16115             }
16116         }
16117         return false;
16118     }
16119 
16120     /**
16121      * Called by profile owner of an organization-owned managed profile to check whether
16122      * personal apps are suspended.
16123      *
16124      * @return a bitmask of reasons for personal apps suspension or
16125      *     {@link #PERSONAL_APPS_NOT_SUSPENDED} if apps are not suspended.
16126      * @see #setPersonalAppsSuspended
16127      */
getPersonalAppsSuspendedReasons( @onNull ComponentName admin)16128     public @PersonalAppsSuspensionReason int getPersonalAppsSuspendedReasons(
16129             @NonNull ComponentName admin) {
16130         throwIfParentInstance("getPersonalAppsSuspendedReasons");
16131         if (mService != null) {
16132             try {
16133                 return mService.getPersonalAppsSuspendedReasons(admin);
16134             } catch (RemoteException re) {
16135                 throw re.rethrowFromSystemServer();
16136             }
16137         }
16138         return 0;
16139     }
16140 
16141     /**
16142      * Called by a profile owner of an organization-owned managed profile to suspend personal
16143      * apps on the device. When personal apps are suspended the device can only be used for calls.
16144      *
16145      * <p>When personal apps are suspended, an ongoing notification about that is shown to the user.
16146      * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE}
16147      * in the profile owner package. Profile owner implementation that uses personal apps suspension
16148      * must handle this intent.
16149      *
16150      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
16151      * @param suspended Whether personal apps should be suspended.
16152      * @throws IllegalStateException if the profile owner doesn't have an activity that handles
16153      *        {@link #ACTION_CHECK_POLICY_COMPLIANCE}
16154      */
setPersonalAppsSuspended(@onNull ComponentName admin, boolean suspended)16155     public void setPersonalAppsSuspended(@NonNull ComponentName admin, boolean suspended) {
16156         throwIfParentInstance("setPersonalAppsSuspended");
16157         if (mService != null) {
16158             try {
16159                 mService.setPersonalAppsSuspended(admin, suspended);
16160             } catch (RemoteException re) {
16161                 throw re.rethrowFromSystemServer();
16162             }
16163         }
16164     }
16165 
16166     /**
16167      * Called by a profile owner of an organization-owned managed profile to set maximum time
16168      * the profile is allowed to be turned off. If the profile is turned off for longer, personal
16169      * apps are suspended on the device.
16170      *
16171      * <p>When personal apps are suspended, an ongoing notification about that is shown to the user.
16172      * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE}
16173      * in the profile owner package. Profile owner implementation that uses personal apps suspension
16174      * must handle this intent.
16175      *
16176      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
16177      * @param timeoutMillis Maximum time the profile is allowed to be off in milliseconds or 0 if
16178      *        not limited. The minimum non-zero value corresponds to 72 hours. If an admin sets a
16179      *        smaller non-zero vaulue, 72 hours will be set instead.
16180      * @throws IllegalStateException if the profile owner doesn't have an activity that handles
16181      *        {@link #ACTION_CHECK_POLICY_COMPLIANCE}
16182      * @see #setPersonalAppsSuspended
16183      */
setManagedProfileMaximumTimeOff(@onNull ComponentName admin, long timeoutMillis)16184     public void setManagedProfileMaximumTimeOff(@NonNull ComponentName admin, long timeoutMillis) {
16185         throwIfParentInstance("setManagedProfileMaximumTimeOff");
16186         if (mService != null) {
16187             try {
16188                 mService.setManagedProfileMaximumTimeOff(admin, timeoutMillis);
16189             } catch (RemoteException re) {
16190                 throw re.rethrowFromSystemServer();
16191             }
16192         }
16193     }
16194 
16195      /**
16196      * Called by a profile owner of an organization-owned managed profile to get maximum time
16197      * the profile is allowed to be turned off.
16198      *
16199      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
16200      * @return Maximum time the profile is allowed to be off in milliseconds or 0 if not limited.
16201      * @see #setPersonalAppsSuspended
16202      */
getManagedProfileMaximumTimeOff(@onNull ComponentName admin)16203     public long getManagedProfileMaximumTimeOff(@NonNull ComponentName admin) {
16204         throwIfParentInstance("getManagedProfileMaximumTimeOff");
16205         if (mService != null) {
16206             try {
16207                 return mService.getManagedProfileMaximumTimeOff(admin);
16208             } catch (RemoteException re) {
16209                 throw re.rethrowFromSystemServer();
16210             }
16211         }
16212         return 0;
16213     }
16214 
16215     /**
16216      * Called by a profile owner of an organization-owned managed profile to acknowledge that the
16217      * device is compliant and the user can turn the profile off if needed according to the maximum
16218      * time off policy.
16219      *
16220      * This method should be called when the device is deemed compliant after getting
16221      * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)} callback in
16222      * case it is overridden. Before this method is called the user is still free to turn the
16223      * profile off, but the timer won't be reset, so personal apps will be suspended sooner.
16224      *
16225      * DPCs only need acknowledging device compliance if they override
16226      * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)}, otherwise
16227      * compliance is acknowledged automatically.
16228      *
16229      * @throws IllegalStateException if the user isn't unlocked
16230      * @see #isComplianceAcknowledgementRequired()
16231      * @see #setManagedProfileMaximumTimeOff(ComponentName, long)
16232      * @see DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)
16233      */
acknowledgeDeviceCompliant()16234     public void acknowledgeDeviceCompliant() {
16235         throwIfParentInstance("acknowledgeDeviceCompliant");
16236         if (mService != null) {
16237             try {
16238                 mService.acknowledgeDeviceCompliant();
16239             } catch (RemoteException re) {
16240                 throw re.rethrowFromSystemServer();
16241             }
16242         }
16243     }
16244 
16245     /**
16246      * Called by a profile owner of an organization-owned managed profile to query whether it needs
16247      * to acknowledge device compliance to allow the user to turn the profile off if needed
16248      * according to the maximum profile time off policy.
16249      *
16250      * Normally when acknowledgement is needed the DPC gets a
16251      * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)} callback.
16252      * But if the callback was not delivered or handled for some reason, this method can be used to
16253      * verify if acknowledgement is needed.
16254      *
16255      * @throws IllegalStateException if the user isn't unlocked
16256      * @see #acknowledgeDeviceCompliant()
16257      * @see #setManagedProfileMaximumTimeOff(ComponentName, long)
16258      * @see DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)
16259      */
isComplianceAcknowledgementRequired()16260     public boolean isComplianceAcknowledgementRequired() {
16261         throwIfParentInstance("isComplianceAcknowledgementRequired");
16262         if (mService != null) {
16263             try {
16264                 return mService.isComplianceAcknowledgementRequired();
16265             } catch (RemoteException re) {
16266                 throw re.rethrowFromSystemServer();
16267             }
16268         }
16269         return false;
16270     }
16271 
16272     /**
16273      * Returns {@code true} when {@code userId} has a profile owner that is capable of resetting
16274      * password in RUNNING_LOCKED state. For that it should have at least one direct boot aware
16275      * component and have an active password reset token. Can only be called by the system.
16276      * @hide
16277      */
canProfileOwnerResetPasswordWhenLocked(int userId)16278     public boolean canProfileOwnerResetPasswordWhenLocked(int userId) {
16279         if (mService != null) {
16280             try {
16281                 return mService.canProfileOwnerResetPasswordWhenLocked(userId);
16282             } catch (RemoteException re) {
16283                 throw re.rethrowFromSystemServer();
16284             }
16285         }
16286         return false;
16287     }
16288 
16289     /**
16290      * Used by CTS to set the result of the next safety operation check.
16291      *
16292      * @hide
16293      */
16294     @TestApi
16295     @RequiresPermission(MANAGE_DEVICE_ADMINS)
setNextOperationSafety(@evicePolicyOperation int operation, @OperationSafetyReason int reason)16296     public void setNextOperationSafety(@DevicePolicyOperation int operation,
16297             @OperationSafetyReason int reason) {
16298         if (mService != null) {
16299             try {
16300                 mService.setNextOperationSafety(operation, reason);
16301             } catch (RemoteException re) {
16302                 throw re.rethrowFromSystemServer();
16303             }
16304         }
16305     }
16306 
16307     /**
16308      * Returns an enrollment-specific identifier of this device, which is guaranteed to be the same
16309      * value for the same device, enrolled into the same organization by the same managing app.
16310      * This identifier is high-entropy, useful for uniquely identifying individual devices within
16311      * the same organisation.
16312      * It is available both in a work profile and on a fully-managed device.
16313      * The identifier would be consistent even if the work profile is removed and enrolled again
16314      * (to the same organization), or the device is factory reset and re-enrolled.
16315      *
16316      * Can only be called by the Profile Owner or Device Owner, if the
16317      * {@link #setOrganizationId(String)} was previously called.
16318      * If {@link #setOrganizationId(String)} was not called, then the returned value will be an
16319      * empty string.
16320      *
16321      * <p>Note about access to device identifiers: a device owner, a profile owner of an
16322      * organization-owned device or the delegated certificate installer (holding the
16323      * {@link #DELEGATION_CERT_INSTALL} delegation) on such a device can still obtain hardware
16324      * identifiers by calling e.g. {@link android.os.Build#getSerial()}, in addition to using
16325      * this method. However, a profile owner on a personal (non organization-owned) device, or the
16326      * delegated certificate installer on such a device, cannot obtain hardware identifiers anymore
16327      * and must switch to using this method.
16328      *
16329      * @return A stable, enrollment-specific identifier.
16330      * @throws SecurityException if the caller is not a profile owner or device owner.
16331      */
getEnrollmentSpecificId()16332     @NonNull public String getEnrollmentSpecificId() {
16333         throwIfParentInstance("getEnrollmentSpecificId");
16334         if (mService == null) {
16335             return "";
16336         }
16337 
16338         try {
16339             return mService.getEnrollmentSpecificId(mContext.getPackageName());
16340         } catch (RemoteException re) {
16341             throw re.rethrowFromSystemServer();
16342         }
16343     }
16344 
16345     /**
16346      * Sets the Enterprise ID for the work profile or managed device. This is a requirement for
16347      * generating an enrollment-specific ID for the device, see {@link #getEnrollmentSpecificId()}.
16348      *
16349      * It is recommended that the Enterprise ID is at least 6 characters long, and no more than
16350      * 64 characters.
16351      *
16352      * @param enterpriseId An identifier of the organization this work profile or device is
16353      *                     enrolled into.
16354      */
setOrganizationId(@onNull String enterpriseId)16355     public void setOrganizationId(@NonNull String enterpriseId) {
16356         throwIfParentInstance("setOrganizationId");
16357         setOrganizationIdForUser(mContext.getPackageName(), enterpriseId, myUserId());
16358     }
16359 
16360     /**
16361      * Sets the Enterprise ID for the work profile or managed device. This is a requirement for
16362      * generating an enrollment-specific ID for the device, see
16363      * {@link #getEnrollmentSpecificId()}.
16364      *
16365      * @hide
16366      */
setOrganizationIdForUser(@onNull String packageName, @NonNull String enterpriseId, @UserIdInt int userId)16367     public void setOrganizationIdForUser(@NonNull String packageName,
16368             @NonNull String enterpriseId, @UserIdInt int userId) {
16369         if (mService == null) {
16370             return;
16371         }
16372         try {
16373             mService.setOrganizationIdForUser(packageName, enterpriseId, userId);
16374         } catch (RemoteException re) {
16375             throw re.rethrowFromSystemServer();
16376         }
16377     }
16378 
16379     /**
16380      * Clears organization ID set by the DPC and resets the precomputed enrollment specific ID.
16381      * @hide
16382      */
16383     @TestApi
16384     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
clearOrganizationId()16385     public void clearOrganizationId() {
16386         if (mService == null) {
16387             return;
16388         }
16389         try {
16390             mService.clearOrganizationIdForUser(myUserId());
16391         } catch (RemoteException re) {
16392             throw re.rethrowFromSystemServer();
16393         }
16394     }
16395 
16396     /**
16397      * Creates and provisions a managed profile and sets the
16398      * {@link ManagedProfileProvisioningParams#getProfileAdminComponentName()} as the profile
16399      * owner.
16400      *
16401      * <p>The method {@link #checkProvisioningPrecondition} must be returning {@link #STATUS_OK}
16402      * before calling this method.
16403      *
16404      * @param provisioningParams Params required to provision a managed profile,
16405      * see {@link ManagedProfileProvisioningParams}.
16406      * @return The {@link UserHandle} of the created profile or {@code null} if the service is
16407      * not available.
16408      * @throws SecurityException if the caller does not hold
16409      * {@link android.Manifest.permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
16410      * @throws ProvisioningException if an error occurred during provisioning.
16411      * @hide
16412      */
16413     @Nullable
16414     @SystemApi
16415     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
createAndProvisionManagedProfile( @onNull ManagedProfileProvisioningParams provisioningParams)16416     public UserHandle createAndProvisionManagedProfile(
16417             @NonNull ManagedProfileProvisioningParams provisioningParams)
16418             throws ProvisioningException {
16419         if (mService == null) {
16420             return null;
16421         }
16422         try {
16423             return mService.createAndProvisionManagedProfile(
16424                     provisioningParams, mContext.getPackageName());
16425         } catch (ServiceSpecificException e) {
16426             throw new ProvisioningException(e, e.errorCode, getErrorMessage(e));
16427         } catch (RemoteException e) {
16428             throw e.rethrowFromSystemServer();
16429         }
16430     }
16431 
16432     /**
16433      * Called when a managed profile has been provisioned.
16434      *
16435      * @throws SecurityException if the caller does not hold
16436      * {@link android.Manifest.permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
16437      * @hide
16438      */
16439     @SystemApi
16440     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
finalizeWorkProfileProvisioning( @onNull UserHandle managedProfileUser, @Nullable Account migratedAccount)16441     public void finalizeWorkProfileProvisioning(
16442             @NonNull UserHandle managedProfileUser, @Nullable Account migratedAccount) {
16443         Objects.requireNonNull(managedProfileUser, "managedProfileUser can't be null");
16444         if (mService == null) {
16445             throw new IllegalStateException("Could not find DevicePolicyManagerService");
16446         }
16447         try {
16448             mService.finalizeWorkProfileProvisioning(managedProfileUser, migratedAccount);
16449         } catch (RemoteException e) {
16450             throw e.rethrowFromSystemServer();
16451         }
16452     }
16453 
16454     /**
16455      * The localized error message to show to the end-user. If {@code null}, a generic error
16456      * message will be shown.
16457      */
getErrorMessage(ServiceSpecificException e)16458     private String getErrorMessage(ServiceSpecificException e) {
16459         return null;
16460     }
16461 
16462 
16463     /**
16464      * Provisions a managed device and sets the {@code deviceAdminComponentName} as the device
16465      * owner.
16466      *
16467      * <p>The method {@link #checkProvisioningPrecondition} must be returning {@link #STATUS_OK}
16468      * before calling this method.
16469      *
16470      * <p>Holders of {@link android.Manifest.permission#PROVISION_DEMO_DEVICE} can call this API
16471      * only if {@link FullyManagedDeviceProvisioningParams#isDemoDevice()} is {@code true}.</p>
16472      *
16473      * @param provisioningParams Params required to provision a fully managed device,
16474      * see {@link FullyManagedDeviceProvisioningParams}.
16475      *
16476      * @throws ProvisioningException if an error occurred during provisioning.
16477      *
16478      * @hide
16479      */
16480     @SystemApi
16481     @RequiresPermission(anyOf = {
16482             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
16483             android.Manifest.permission.PROVISION_DEMO_DEVICE})
provisionFullyManagedDevice( @onNull FullyManagedDeviceProvisioningParams provisioningParams)16484     public void provisionFullyManagedDevice(
16485             @NonNull FullyManagedDeviceProvisioningParams provisioningParams)
16486             throws ProvisioningException {
16487         if (mService != null) {
16488             try {
16489                 mService.provisionFullyManagedDevice(provisioningParams, mContext.getPackageName());
16490             } catch (ServiceSpecificException e) {
16491                 throw new ProvisioningException(e, e.errorCode, getErrorMessage(e));
16492             } catch (RemoteException re) {
16493                 throw re.rethrowFromSystemServer();
16494             }
16495         }
16496     }
16497 
16498     /**
16499      * Resets the default cross profile intent filters that were set during
16500      * {@link #createAndProvisionManagedProfile} between {@code userId} and all it's managed
16501      * profiles if any.
16502      *
16503      * @hide
16504      */
16505     @TestApi
16506     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
resetDefaultCrossProfileIntentFilters(@serIdInt int userId)16507     public void resetDefaultCrossProfileIntentFilters(@UserIdInt int userId) {
16508         if (mService != null) {
16509             try {
16510                 mService.resetDefaultCrossProfileIntentFilters(userId);
16511             } catch (RemoteException re) {
16512                 throw re.rethrowFromSystemServer();
16513             }
16514         }
16515     }
16516 
16517     /**
16518      * Returns true if the caller is running on a device where an admin can grant
16519      * permissions related to device sensors.
16520      * This is a signal that the device is a fully-managed device where personal usage is
16521      * discouraged.
16522      * The list of permissions is listed in
16523      * {@link #setPermissionGrantState(ComponentName, String, String, int)}.
16524      *
16525      * May be called by any app.
16526      * @return true if an admin can grant device sensors-related permissions, false otherwise.
16527      */
canAdminGrantSensorsPermissions()16528     public boolean canAdminGrantSensorsPermissions() {
16529         throwIfParentInstance("canAdminGrantSensorsPermissions");
16530         if (mService == null) {
16531             return false;
16532         }
16533         try {
16534             return mService.canAdminGrantSensorsPermissions();
16535         } catch (RemoteException re) {
16536             throw re.rethrowFromSystemServer();
16537         }
16538     }
16539 
16540     /**
16541      * Sets the device owner type for a managed device (e.g. financed device).
16542      *
16543      * @param admin The {@link DeviceAdminReceiver} that is the device owner.
16544      * @param deviceOwnerType The device owner type is set to. Use
16545      * {@link #DEVICE_OWNER_TYPE_DEFAULT} for the default device owner type. Use
16546      * {@link #DEVICE_OWNER_TYPE_FINANCED} for the financed device owner type.
16547      *
16548      * @throws IllegalStateException When admin is not the device owner, or there is no device
16549      *     owner, or attempting to set the device owner type again for the same admin.
16550      * @throws SecurityException If the caller does not have the permission
16551      *     {@link permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
16552      *
16553      * @hide
16554      */
16555     @TestApi
setDeviceOwnerType(@onNull ComponentName admin, @DeviceOwnerType int deviceOwnerType)16556     public void setDeviceOwnerType(@NonNull ComponentName admin,
16557             @DeviceOwnerType int deviceOwnerType) {
16558         throwIfParentInstance("setDeviceOwnerType");
16559         if (mService != null) {
16560             try {
16561                 mService.setDeviceOwnerType(admin, deviceOwnerType);
16562             } catch (RemoteException re) {
16563                 throw re.rethrowFromSystemServer();
16564             }
16565         }
16566     }
16567 
16568     /**
16569      * Returns the device owner type for the admin used in
16570      * {@link #setDeviceOwnerType(ComponentName, int)}. {@link #DEVICE_OWNER_TYPE_DEFAULT}
16571      * would be returned when the device owner type is not set for the device owner admin.
16572      *
16573      * @param admin The {@link DeviceAdminReceiver} that is the device owner.
16574      *
16575      * @throws IllegalStateException When admin is not the device owner or there is no device owner.
16576      *
16577      * @deprecated Use type-specific APIs (e.g. {@link #isFinancedDevice}).
16578      * @hide
16579      */
16580     @TestApi
16581     @DeviceOwnerType
16582     @Deprecated
16583     // TODO(b/259908270): remove
getDeviceOwnerType(@onNull ComponentName admin)16584     public int getDeviceOwnerType(@NonNull ComponentName admin) {
16585         throwIfParentInstance("getDeviceOwnerType");
16586         if (mService != null) {
16587             try {
16588                 return mService.getDeviceOwnerType(admin);
16589             } catch (RemoteException re) {
16590                 throw re.rethrowFromSystemServer();
16591             }
16592         }
16593         return DEVICE_OWNER_TYPE_DEFAULT;
16594     }
16595 
16596     /**
16597      * {@code true} if this device is financed.
16598      * @hide
16599      */
16600     @RequiresPermission(anyOf = {
16601             android.Manifest.permission.MANAGE_USERS,
16602             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
16603     })
isFinancedDevice()16604     public boolean isFinancedDevice() {
16605         return isDeviceManaged()
16606                 && getDeviceOwnerType(getDeviceOwnerComponentOnAnyUser())
16607                 == DEVICE_OWNER_TYPE_FINANCED;
16608     }
16609 
16610     /**
16611      * Called by a device owner or profile owner of an organization-owned managed profile to enable
16612      * or disable USB data signaling for the device. When disabled, USB data connections
16613      * (except from charging functions) are prohibited.
16614      *
16615      * <p> This API is not supported on all devices, the caller should call
16616      * {@link #canUsbDataSignalingBeDisabled()} to check whether enabling or disabling USB data
16617      * signaling is supported on the device.
16618      *
16619      * @param enabled whether USB data signaling should be enabled or not.
16620      * @throws SecurityException if the caller is not permitted to set this policy
16621      * @throws IllegalStateException if disabling USB data signaling is not supported or
16622      *         if USB data signaling fails to be enabled/disabled.
16623      */
16624     @RequiresPermission(value = MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING, conditional = true)
setUsbDataSignalingEnabled(boolean enabled)16625     public void setUsbDataSignalingEnabled(boolean enabled) {
16626         throwIfParentInstance("setUsbDataSignalingEnabled");
16627         if (mService != null) {
16628             try {
16629                 mService.setUsbDataSignalingEnabled(mContext.getPackageName(), enabled);
16630             } catch (RemoteException e) {
16631                 throw e.rethrowFromSystemServer();
16632             }
16633         }
16634     }
16635 
16636     /**
16637      * Returns whether USB data signaling is currently enabled.
16638      *
16639      * <p> When called by a device owner or profile owner of an organization-owned managed profile,
16640      * this API returns whether USB data signaling is currently enabled by that admin. When called
16641      * by any other app, returns whether USB data signaling is currently enabled on the device.
16642      *
16643      * @return {@code true} if USB data signaling is enabled, {@code false} otherwise.
16644      */
isUsbDataSignalingEnabled()16645     public boolean isUsbDataSignalingEnabled() {
16646         throwIfParentInstance("isUsbDataSignalingEnabled");
16647         if (mService != null) {
16648             try {
16649                 return mService.isUsbDataSignalingEnabled(mContext.getPackageName());
16650             } catch (RemoteException e) {
16651                 throw e.rethrowFromSystemServer();
16652             }
16653         }
16654         return true;
16655     }
16656 
16657     /**
16658      * Called by the system to check whether USB data signaling is currently enabled for this user.
16659      *
16660      * @param userId which user to check for.
16661      * @return {@code true} if USB data signaling is enabled, {@code false} otherwise.
16662      * @hide
16663      */
isUsbDataSignalingEnabledForUser(@serIdInt int userId)16664     public boolean isUsbDataSignalingEnabledForUser(@UserIdInt int userId) {
16665         throwIfParentInstance("isUsbDataSignalingEnabledForUser");
16666         if (mService != null) {
16667             try {
16668                 return mService.isUsbDataSignalingEnabledForUser(userId);
16669             } catch (RemoteException e) {
16670                 throw e.rethrowFromSystemServer();
16671             }
16672         }
16673         return true;
16674     }
16675 
16676     /**
16677      * Returns whether enabling or disabling USB data signaling is supported on the device.
16678      *
16679      * @return {@code true} if the device supports enabling and disabling USB data signaling.
16680      */
canUsbDataSignalingBeDisabled()16681     public boolean canUsbDataSignalingBeDisabled() {
16682         throwIfParentInstance("canUsbDataSignalingBeDisabled");
16683         if (mService != null) {
16684             try {
16685                 return mService.canUsbDataSignalingBeDisabled();
16686             } catch (RemoteException re) {
16687                 throw re.rethrowFromSystemServer();
16688             }
16689         }
16690         return false;
16691     }
16692 
16693     /**
16694      * Gets the list of {@link #isAffiliatedUser() affiliated} users running on foreground.
16695      *
16696      * @return list of {@link #isAffiliatedUser() affiliated} users running on foreground.
16697      *
16698      * @throws SecurityException if the calling application is not a device owner
16699      */
16700     @NonNull
listForegroundAffiliatedUsers()16701     public List<UserHandle> listForegroundAffiliatedUsers() {
16702         if (mService == null) return Collections.emptyList();
16703 
16704         try {
16705             return mService.listForegroundAffiliatedUsers();
16706         } catch (RemoteException re) {
16707             throw re.rethrowFromSystemServer();
16708         }
16709     }
16710 
16711     /**
16712      * Lists apps that are exempt from policies (such as
16713      * {@link #setPackagesSuspended(ComponentName, String[], boolean)}).
16714      *
16715      * @hide
16716      */
16717     @TestApi
16718     @RequiresPermission(value = MANAGE_DEVICE_ADMINS)
getPolicyExemptApps()16719     public @NonNull Set<String> getPolicyExemptApps() {
16720         if (mService == null) return Collections.emptySet();
16721 
16722         try {
16723             return new HashSet<>(mService.listPolicyExemptApps());
16724         } catch (RemoteException e) {
16725             throw e.rethrowFromSystemServer();
16726         }
16727     }
16728 
16729     /**
16730      * Creates a {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent
16731      * from the provided {@code nfcIntent}.
16732      *
16733      * <p>Prerequisites to create the provisioning intent:
16734      *
16735      * <ul>
16736      * <li>{@code nfcIntent}'s action is {@link NfcAdapter#ACTION_NDEF_DISCOVERED}</li>
16737      * <li>{@code nfcIntent}'s NFC properties contain either
16738      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} or
16739      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} </li>
16740      * </ul>
16741      *
16742      * This method returns {@code null} if the prerequisites are not met or if an error occurs
16743      * when reading the NFC properties.
16744      *
16745      * @param nfcIntent the nfc intent generated from scanning a NFC tag
16746      * @return a {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent with
16747      * intent extras as read by {@code nfcIntent}'s NFC properties or {@code null} if the
16748      * prerequisites are not met or if an error occurs when reading the NFC properties.
16749      *
16750      * @hide
16751      */
16752     @Nullable
16753     @SystemApi
createProvisioningIntentFromNfcIntent(@onNull Intent nfcIntent)16754     public Intent createProvisioningIntentFromNfcIntent(@NonNull Intent nfcIntent) {
16755         return ProvisioningIntentHelper.createProvisioningIntentFromNfcIntent(nfcIntent);
16756     }
16757 
16758     /**
16759      * Called by device owner or profile owner of an organization-owned managed profile to
16760      * specify the minimum security level required for Wi-Fi networks.
16761      * The device may not connect to networks that do not meet the minimum security level.
16762      * If the current network does not meet the minimum security level set, it will be disconnected.
16763      *
16764      * The following shows the Wi-Fi security levels from the lowest to the highest security level:
16765      * {@link #WIFI_SECURITY_OPEN}
16766      * {@link #WIFI_SECURITY_PERSONAL}
16767      * {@link #WIFI_SECURITY_ENTERPRISE_EAP}
16768      * {@link #WIFI_SECURITY_ENTERPRISE_192}
16769      *
16770      * @param level minimum security level
16771      * @throws SecurityException if the caller is not permitted to set this policy
16772      */
16773     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true)
setMinimumRequiredWifiSecurityLevel(@ifiSecurity int level)16774     public void setMinimumRequiredWifiSecurityLevel(@WifiSecurity int level) {
16775         throwIfParentInstance("setMinimumRequiredWifiSecurityLevel");
16776         if (mService != null) {
16777             try {
16778                 mService.setMinimumRequiredWifiSecurityLevel(mContext.getPackageName(), level);
16779             } catch (RemoteException e) {
16780                 throw e.rethrowFromSystemServer();
16781             }
16782         }
16783     }
16784 
16785     /**
16786      * Returns the current Wi-Fi minimum security level.
16787      *
16788      * @see #setMinimumRequiredWifiSecurityLevel(int)
16789      */
getMinimumRequiredWifiSecurityLevel()16790     public @WifiSecurity int getMinimumRequiredWifiSecurityLevel() {
16791         throwIfParentInstance("getMinimumRequiredWifiSecurityLevel");
16792         if (mService == null) {
16793             return WIFI_SECURITY_OPEN;
16794         }
16795         try {
16796             return mService.getMinimumRequiredWifiSecurityLevel();
16797         } catch (RemoteException e) {
16798             throw e.rethrowFromSystemServer();
16799         }
16800     }
16801 
16802     /**
16803      * Called by device owner or profile owner of an organization-owned managed profile to
16804      * specify the Wi-Fi SSID policy ({@link WifiSsidPolicy}).
16805      * Wi-Fi SSID policy specifies the SSID restriction the network must satisfy
16806      * in order to be eligible for a connection. Providing a null policy results in the
16807      * deactivation of the SSID restriction
16808      *
16809      * @param policy Wi-Fi SSID policy
16810      * @throws SecurityException if the caller is not permitted to manage wifi policy
16811      */
16812     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true)
setWifiSsidPolicy(@ullable WifiSsidPolicy policy)16813     public void setWifiSsidPolicy(@Nullable WifiSsidPolicy policy) {
16814         throwIfParentInstance("setWifiSsidPolicy");
16815         if (mService == null) {
16816             return;
16817         }
16818         try {
16819             mService.setWifiSsidPolicy(mContext.getPackageName(), policy);
16820         } catch (RemoteException e) {
16821             throw e.rethrowFromSystemServer();
16822         }
16823 
16824     }
16825 
16826     /**
16827      * Returns the current Wi-Fi SSID policy.
16828      * If the policy has not been set, it will return NULL.
16829      *
16830      * @see #setWifiSsidPolicy(WifiSsidPolicy)
16831      * @throws SecurityException if the caller is not a device owner or a profile owner on
16832      * an organization-owned managed profile.
16833      */
16834     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true)
16835     @Nullable
getWifiSsidPolicy()16836     public WifiSsidPolicy getWifiSsidPolicy() {
16837         throwIfParentInstance("getWifiSsidPolicy");
16838         if (mService == null) {
16839             return null;
16840         }
16841         try {
16842             return mService.getWifiSsidPolicy(mContext.getPackageName());
16843         } catch (RemoteException e) {
16844             throw e.rethrowFromSystemServer();
16845         }
16846     }
16847 
16848     /**
16849      * Returns a {@link DevicePolicyResourcesManager} containing the required APIs to set, reset,
16850      * and get device policy related resources.
16851      */
16852     @NonNull
getResources()16853     public DevicePolicyResourcesManager getResources() {
16854         return mResourcesManager;
16855     }
16856 
16857     /**
16858      * Returns a boolean for whether the DPC
16859      * (Device Policy Controller, the agent responsible for enforcing policy)
16860      * has been downloaded during provisioning.
16861      *
16862      * <p>If true is returned, then any attempts to begin setup again should result in factory reset
16863      *
16864      * @hide
16865      */
16866     @SystemApi
16867     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
isDpcDownloaded()16868     public boolean isDpcDownloaded() {
16869         throwIfParentInstance("isDpcDownloaded");
16870         if (mService != null) {
16871             try {
16872                 return mService.isDpcDownloaded();
16873             } catch (RemoteException e) {
16874                 throw e.rethrowFromSystemServer();
16875             }
16876         }
16877         return false;
16878     }
16879 
16880     /**
16881      * Indicates that the DPC (Device Policy Controller, the agent responsible for enforcing policy)
16882      * has or has not been downloaded during provisioning.
16883      *
16884      * @param downloaded {@code true} if the dpc has been downloaded during provisioning.
16885      *                               {@code false} otherwise.
16886      *
16887      * @hide
16888      */
16889     @SystemApi
16890     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setDpcDownloaded(boolean downloaded)16891     public void setDpcDownloaded(boolean downloaded) {
16892         throwIfParentInstance("setDpcDownloaded");
16893         if (mService != null) {
16894             try {
16895                 mService.setDpcDownloaded(downloaded);
16896             } catch (RemoteException e) {
16897                 throw e.rethrowFromSystemServer();
16898             }
16899         }
16900     }
16901 
16902     /**
16903      * Returns the package name of the device policy management role holder.
16904      *
16905      * <p>If the device policy management role holder is not configured for this device, returns
16906      * {@code null}.
16907      */
16908     @Nullable
getDevicePolicyManagementRoleHolderPackage()16909     public String getDevicePolicyManagementRoleHolderPackage() {
16910         String devicePolicyManagementConfig = mContext.getString(
16911                 com.android.internal.R.string.config_devicePolicyManagement);
16912         return extractPackageNameFromDeviceManagerConfig(devicePolicyManagementConfig);
16913     }
16914 
16915     /**
16916      * Returns the package name of the device policy management role holder updater.
16917      *
16918      * <p>If the device policy management role holder updater is not configured for this device,
16919      * returns {@code null}.
16920      *
16921      * @hide
16922      */
16923     @Nullable
16924     @TestApi
getDevicePolicyManagementRoleHolderUpdaterPackage()16925     public String getDevicePolicyManagementRoleHolderUpdaterPackage() {
16926         String devicePolicyManagementUpdaterConfig = mContext.getString(
16927                 com.android.internal.R.string.config_devicePolicyManagementUpdater);
16928         if (TextUtils.isEmpty(devicePolicyManagementUpdaterConfig)) {
16929             return null;
16930         }
16931         return devicePolicyManagementUpdaterConfig;
16932     }
16933 
16934     /**
16935      * Returns a {@link List} of managed profiles managed by some profile owner within the profile
16936      * group of the given user, or an empty {@link List} if there is not one.
16937      *
16938      * @param user the user whose profile group to look within to return managed profiles
16939      *
16940      * @hide
16941      */
16942     @SystemApi
16943     @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
16944     @NonNull
getPolicyManagedProfiles(@onNull UserHandle user)16945     public List<UserHandle> getPolicyManagedProfiles(@NonNull UserHandle user) {
16946         Objects.requireNonNull(user);
16947         if (mService != null) {
16948             try {
16949                 return mService.getPolicyManagedProfiles(user);
16950             } catch (RemoteException e) {
16951                 throw e.rethrowFromSystemServer();
16952             }
16953         }
16954         return Collections.emptyList();
16955     }
16956 
16957     /**
16958      * Retrieves the package name for a given {@code deviceManagerConfig}.
16959      *
16960      * <p>Valid configs look like:
16961      * <ul>
16962      *     <li>{@code com.package.name}</li>
16963      *     <li>{@code com.package.name:<SHA256 checksum>}</li>
16964      * </ul>
16965      *
16966      * <p>If the supplied {@code deviceManagerConfig} is {@code null} or empty, returns
16967      * {@code null}.
16968      */
16969     @Nullable
extractPackageNameFromDeviceManagerConfig( @ullable String deviceManagerConfig)16970     private String extractPackageNameFromDeviceManagerConfig(
16971             @Nullable String deviceManagerConfig) {
16972         if (TextUtils.isEmpty(deviceManagerConfig)) {
16973             return null;
16974         }
16975         if (deviceManagerConfig.contains(":")) {
16976             return deviceManagerConfig.split(":")[0];
16977         }
16978         return deviceManagerConfig;
16979     }
16980 
16981     /**
16982      * Reset cache for {@link #shouldAllowBypassingDevicePolicyManagementRoleQualification}.
16983      *
16984      * @hide
16985      */
16986     @TestApi
16987     @RequiresPermission(android.Manifest.permission.MANAGE_ROLE_HOLDERS)
resetShouldAllowBypassingDevicePolicyManagementRoleQualificationState()16988     public void resetShouldAllowBypassingDevicePolicyManagementRoleQualificationState() {
16989         if (mService != null) {
16990             try {
16991                 mService.resetShouldAllowBypassingDevicePolicyManagementRoleQualificationState();
16992             } catch (RemoteException e) {
16993                 throw e.rethrowFromSystemServer();
16994             }
16995         }
16996     }
16997 
16998     /**
16999      * Recalculate the incompatible accounts cache.
17000      *
17001      * @hide
17002      */
17003     @TestApi
17004     @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
calculateHasIncompatibleAccounts()17005     public void calculateHasIncompatibleAccounts() {
17006         if (mService != null) {
17007             try {
17008                 mService.calculateHasIncompatibleAccounts();
17009             } catch (RemoteException e) {
17010                 throw e.rethrowFromSystemServer();
17011             }
17012         }
17013     }
17014 
17015     /**
17016      * @return {@code true} if bypassing the device policy management role qualification is allowed
17017      * with the current state of the device.
17018      *
17019      * @hide
17020      */
17021     @SystemApi
17022     @RequiresPermission(android.Manifest.permission.MANAGE_ROLE_HOLDERS)
shouldAllowBypassingDevicePolicyManagementRoleQualification()17023     public boolean shouldAllowBypassingDevicePolicyManagementRoleQualification() {
17024         if (mService != null) {
17025             try {
17026                 return mService.shouldAllowBypassingDevicePolicyManagementRoleQualification();
17027             } catch (RemoteException e) {
17028                 throw e.rethrowFromSystemServer();
17029             }
17030         }
17031         return false;
17032     }
17033 
17034     /**
17035      * Returns a {@link DevicePolicyState} object containing information about the current state
17036      * of device policies (e.g. values set by different admins, info about the enforcing admins,
17037      * resolved policy, etc).
17038      *
17039      * @hide
17040      */
17041     @SystemApi
17042     @NonNull
17043     @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
getDevicePolicyState()17044     public DevicePolicyState getDevicePolicyState() {
17045         if (mService != null) {
17046             try {
17047                 return mService.getDevicePolicyState();
17048             } catch (RemoteException e) {
17049                 throw e.rethrowFromSystemServer();
17050             }
17051         }
17052         return null;
17053     }
17054 
17055     /**
17056      * Overrides the effective cached value of enable_keep_profiles_running for testing purposes.
17057      *
17058      * @hide
17059      */
17060     @TestApi
17061     @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setOverrideKeepProfilesRunning(boolean enabled)17062     public void setOverrideKeepProfilesRunning(boolean enabled) {
17063         if (mService != null) {
17064             try {
17065                 mService.setOverrideKeepProfilesRunning(enabled);
17066             } catch (RemoteException e) {
17067                 throw e.rethrowFromSystemServer();
17068             }
17069         }
17070     }
17071 
17072     /**
17073      * Triggers the data migration of device policies for existing DPCs to the Device Policy Engine.
17074      * If {@code forceMigration} is set to {@code true} it skips the prerequisite checks before
17075      * triggering the migration.
17076      *
17077      * <p>Returns {@code true} if migration was completed successfully, {@code false} otherwise.
17078      *
17079      * @hide
17080      */
17081     @TestApi
17082     @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
triggerDevicePolicyEngineMigration(boolean forceMigration)17083     public boolean triggerDevicePolicyEngineMigration(boolean forceMigration) {
17084         if (mService != null) {
17085             try {
17086                 return mService.triggerDevicePolicyEngineMigration(forceMigration);
17087             } catch (RemoteException e) {
17088                 throw e.rethrowFromSystemServer();
17089             }
17090         }
17091         return false;
17092     }
17093 
17094     /**
17095      * Returns {@code true} if this device is marked as a financed device.
17096      *
17097      * <p>A financed device can be entered into lock task mode (see {@link #setLockTaskPackages})
17098      * by the holder of the role {@link android.app.role.RoleManager#ROLE_FINANCED_DEVICE_KIOSK}.
17099      * If this occurs, Device Owners and Profile Owners that have set lock task packages or
17100      * features, or that attempt to set lock task packages or features, will receive a callback
17101      * indicating that it could not be set. See {@link PolicyUpdateReceiver#onPolicyChanged} and
17102      * {@link PolicyUpdateReceiver#onPolicySetResult}.
17103      *
17104      * <p>To be informed of changes to this status you can subscribe to the broadcast
17105      * {@link ACTION_DEVICE_FINANCING_STATE_CHANGED}.
17106      *
17107      * @throws SecurityException if the caller is not a device owner, profile owner of an
17108      * organization-owned managed profile, profile owner on the primary user or holder of one of the
17109      * following roles: {@link android.app.role.RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT},
17110      * android.app.role.RoleManager.ROLE_SYSTEM_SUPERVISION.
17111      */
isDeviceFinanced()17112     public boolean isDeviceFinanced() {
17113         throwIfParentInstance("isDeviceFinanced");
17114         if (mService != null) {
17115             try {
17116                 return mService.isDeviceFinanced(mContext.getPackageName());
17117             } catch (RemoteException e) {
17118                 throw e.rethrowFromSystemServer();
17119             }
17120         }
17121         return false;
17122     }
17123 
17124     /**
17125      * Returns the package name of the application holding the role:
17126      * {@link android.app.role.RoleManager#ROLE_FINANCED_DEVICE_KIOSK}.
17127      *
17128      * @return the package name of the application holding the role or {@code null} if the role is
17129      * not held by any applications.
17130      * @hide
17131      */
17132     @SystemApi
17133     @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
17134     @Nullable
getFinancedDeviceKioskRoleHolder()17135     public String getFinancedDeviceKioskRoleHolder() {
17136         if (mService != null) {
17137             try {
17138                 return mService.getFinancedDeviceKioskRoleHolder(mContext.getPackageName());
17139             } catch (RemoteException e) {
17140                 throw e.rethrowFromSystemServer();
17141             }
17142         }
17143         return null;
17144     }
17145 }
17146