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.LOCK_DEVICE;
22 import static android.Manifest.permission.MANAGE_DEVICE_ADMINS;
23 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT;
24 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_APPS_CONTROL;
25 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CAMERA;
26 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CERTIFICATES;
27 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE;
28 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CONTENT_PROTECTION;
29 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_DEFAULT_SMS;
30 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_FACTORY_RESET;
31 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_INPUT_METHODS;
32 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_KEYGUARD;
33 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK;
34 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS;
35 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK_TASK;
36 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MTE;
37 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY;
38 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PACKAGE_STATE;
39 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PROFILE_INTERACTION;
40 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_QUERY_SYSTEM_UPDATES;
41 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RESET_PASSWORD;
42 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS;
43 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SCREEN_CAPTURE;
44 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SECURITY_LOGGING;
45 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_STATUS_BAR;
46 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE;
47 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SYSTEM_UPDATES;
48 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING;
49 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WIFI;
50 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WIPE_DATA;
51 import static android.Manifest.permission.QUERY_ADMIN_POLICY;
52 import static android.Manifest.permission.QUERY_DEVICE_STOLEN_STATE;
53 import static android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY;
54 import static android.Manifest.permission.SET_TIME;
55 import static android.Manifest.permission.SET_TIME_ZONE;
56 import static android.app.admin.DeviceAdminInfo.HEADLESS_DEVICE_OWNER_MODE_UNSUPPORTED;
57 import static android.app.admin.flags.Flags.FLAG_DEVICE_POLICY_SIZE_TRACKING_INTERNAL_BUG_FIX_ENABLED;
58 import static android.app.admin.flags.Flags.FLAG_DEVICE_THEFT_API_ENABLED;
59 import static android.app.admin.flags.Flags.FLAG_ESIM_MANAGEMENT_ENABLED;
60 import static android.app.admin.flags.Flags.FLAG_DEVICE_POLICY_SIZE_TRACKING_ENABLED;
61 import static android.app.admin.flags.Flags.FLAG_HEADLESS_DEVICE_OWNER_PROVISIONING_FIX_ENABLED;
62 import static android.app.admin.flags.Flags.FLAG_HEADLESS_DEVICE_OWNER_SINGLE_USER_ENABLED;
63 import static android.app.admin.flags.Flags.FLAG_SECURITY_LOG_V2_ENABLED;
64 import static android.app.admin.flags.Flags.onboardingBugreportV2Enabled;
65 import static android.app.admin.flags.Flags.onboardingConsentlessBugreports;
66 import static android.app.admin.flags.Flags.FLAG_IS_MTE_POLICY_ENFORCED;
67 import static android.content.Intent.LOCAL_FLAG_FROM_SYSTEM;
68 import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
69 import static android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE;
70 
71 import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
72 
73 import android.Manifest.permission;
74 import android.accounts.Account;
75 import android.annotation.BroadcastBehavior;
76 import android.annotation.CallbackExecutor;
77 import android.annotation.ColorInt;
78 import android.annotation.FlaggedApi;
79 import android.annotation.IntDef;
80 import android.annotation.NonNull;
81 import android.annotation.Nullable;
82 import android.annotation.RequiresFeature;
83 import android.annotation.RequiresPermission;
84 import android.annotation.SdkConstant;
85 import android.annotation.SdkConstant.SdkConstantType;
86 import android.annotation.StringDef;
87 import android.annotation.SupportsCoexistence;
88 import android.annotation.SuppressLint;
89 import android.annotation.SystemApi;
90 import android.annotation.SystemService;
91 import android.annotation.TestApi;
92 import android.annotation.UserHandleAware;
93 import android.annotation.UserIdInt;
94 import android.annotation.WorkerThread;
95 import android.app.Activity;
96 import android.app.IServiceConnection;
97 import android.app.KeyguardManager;
98 import android.app.admin.SecurityLog.SecurityEvent;
99 import android.app.admin.flags.Flags;
100 import android.app.compat.CompatChanges;
101 import android.compat.annotation.ChangeId;
102 import android.compat.annotation.EnabledSince;
103 import android.compat.annotation.UnsupportedAppUsage;
104 import android.content.ComponentName;
105 import android.content.Context;
106 import android.content.Intent;
107 import android.content.IntentFilter;
108 import android.content.ServiceConnection;
109 import android.content.pm.ApplicationInfo;
110 import android.content.pm.IPackageDataObserver;
111 import android.content.pm.PackageManager;
112 import android.content.pm.PackageManager.NameNotFoundException;
113 import android.content.pm.ParceledListSlice;
114 import android.content.pm.UserInfo;
115 import android.graphics.Bitmap;
116 import android.graphics.drawable.Drawable;
117 import android.net.PrivateDnsConnectivityChecker;
118 import android.net.ProxyInfo;
119 import android.net.Uri;
120 import android.nfc.NfcAdapter;
121 import android.os.Binder;
122 import android.os.Build;
123 import android.os.Bundle;
124 import android.os.IpcDataCache;
125 import android.os.ParcelFileDescriptor;
126 import android.os.Parcelable;
127 import android.os.PersistableBundle;
128 import android.os.Process;
129 import android.os.RemoteCallback;
130 import android.os.RemoteException;
131 import android.os.ServiceSpecificException;
132 import android.os.UserHandle;
133 import android.os.UserManager;
134 import android.os.UserManager.UserOperationException;
135 import android.os.UserManager.UserOperationResult;
136 import android.provider.CalendarContract;
137 import android.provider.ContactsContract.Directory;
138 import android.provider.Settings;
139 import android.security.AttestedKeyPair;
140 import android.security.Credentials;
141 import android.security.KeyChain;
142 import android.security.KeyChainException;
143 import android.security.keymaster.KeymasterCertificateChain;
144 import android.security.keystore.AttestationUtils;
145 import android.security.keystore.KeyAttestationException;
146 import android.security.keystore.KeyGenParameterSpec;
147 import android.security.keystore.ParcelableKeyGenParameterSpec;
148 import android.security.keystore.StrongBoxUnavailableException;
149 import android.service.restrictions.RestrictionsReceiver;
150 import android.telephony.TelephonyManager;
151 import android.telephony.data.ApnSetting;
152 import android.text.TextUtils;
153 import android.util.ArraySet;
154 import android.util.DebugUtils;
155 import android.util.Log;
156 import android.util.Pair;
157 
158 import com.android.internal.annotations.VisibleForTesting;
159 import com.android.internal.infra.AndroidFuture;
160 import com.android.internal.net.NetworkUtilsInternal;
161 import com.android.internal.os.BackgroundThread;
162 import com.android.internal.os.Zygote;
163 import com.android.internal.util.ArrayUtils;
164 import com.android.internal.util.Preconditions;
165 import com.android.org.conscrypt.TrustedCertificateStore;
166 
167 import java.io.ByteArrayInputStream;
168 import java.io.FileNotFoundException;
169 import java.io.IOException;
170 import java.lang.annotation.Retention;
171 import java.lang.annotation.RetentionPolicy;
172 import java.net.InetSocketAddress;
173 import java.net.Proxy;
174 import java.security.KeyFactory;
175 import java.security.KeyPair;
176 import java.security.NoSuchAlgorithmException;
177 import java.security.PrivateKey;
178 import java.security.cert.Certificate;
179 import java.security.cert.CertificateException;
180 import java.security.cert.CertificateFactory;
181 import java.security.cert.X509Certificate;
182 import java.security.spec.InvalidKeySpecException;
183 import java.security.spec.PKCS8EncodedKeySpec;
184 import java.util.ArrayList;
185 import java.util.Arrays;
186 import java.util.Collections;
187 import java.util.HashSet;
188 import java.util.List;
189 import java.util.Map;
190 import java.util.Objects;
191 import java.util.Set;
192 import java.util.concurrent.CompletableFuture;
193 import java.util.concurrent.ExecutionException;
194 import java.util.concurrent.Executor;
195 import java.util.function.Consumer;
196 
197 /**
198  * Manages device policy and restrictions applied to the user of the device or
199  * apps running on the device.
200  *
201  * <p>This class contains three types of methods:
202  * <ol><li>Those aimed at <a href="#managingapps">managing apps</a>
203  * <li>Those aimed at the <a href="#roleholder">Device Policy Management Role Holder</a>
204  * <li>Those aimed at <a href="#querying">apps which wish to respect device policy</a>
205  * </ol>
206  *
207  * <p>The intended caller for each API is indicated in its Javadoc.
208  *
209  * <p id="managingapps"><b>Managing Apps</b>
210  * <p>Apps can be made capable of setting device policy ("Managing Apps") either by
211  * being set as a <a href="#deviceadmin">Device Administrator</a>, being set as a
212  * <a href="#devicepolicycontroller">Device Policy Controller</a>, or by holding the
213  * appropriate <a href="#permissions">Permissions</a>.
214  *
215  * <p id="deviceadmin">A <b>Device Administrator</b> is an app which is able to enforce device
216  * policies that it has declared in its device admin XML file. An app can prompt the user to give it
217  * device administator privileges using the {@link #ACTION_ADD_DEVICE_ADMIN} action.
218  *
219  * <p>For more information about Device Administration, read the
220  * <a href="{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a>
221  * developer guide.
222  *
223  * <p id="devicepolicycontroller">Through <a href="#managed_provisioning">Managed Provisioning</a>,
224  * Device Administrator apps can also be recognised as <b>
225  Device Policy Controllers</b>. Device Policy Controllers can be one of
226  * two types:
227  * <ul>
228  * <li>A <i id="deviceowner">Device Owner</i>, which only ever exists on the
229  * {@link UserManager#isSystemUser System User} or {@link UserManager#isMainUser Main User}, is
230  * the most powerful type of Device Policy Controller and can affect policy across the device.
231  * <li>A <i id="profileowner">Profile Owner<i>, which can exist on any user, can
232  * affect policy on the user it is on, and when it is running on
233  * {@link UserManager#isProfile a profile} has
234  * <a href="#profile-on-parent">limited</a> ability to affect policy on its
235  * {@link UserManager#getProfileParent parent}.
236  * </ul>
237  *
238  * <p>Additional capabilities can be provided to Device Policy Controllers in
239  * the following circumstances:
240  * <ul>
241  * <li>A Profile Owner on an <a href="#organization-owned">organization owned</a> device has access
242  * to additional abilities, both <a href="#profile-on-parent-organization-owned">affecting policy on the profile's</a>
243  * {@link UserManager#getProfileParent parent} and also the profile itself.
244  * <li>A Profile Owner running on the {@link UserManager#isSystemUser System User} has access to
245  * additional capabilities which affect the {@link UserManager#isSystemUser System User} and
246  * also the whole device.
247  * <li>A Profile Owner running on an <a href="#affiliated">affiliated</a> user has
248  * capabilities similar to that of a <a href="#deviceowner">Device Owner</a>
249  * </ul>
250  *
251  * <p>For more information, see <a href="{@docRoot}work/dpc/build-dpc">Building a Device Policy
252  * Controller</a>.
253  *
254  * <p><a href="#permissions">Permissions</a> are generally only given to apps
255  * fulfilling particular key roles on the device (such as managing {@link DeviceLockManager
256 device locks}).
257  *
258  * <p id="roleholder"><b>Device Policy Management Role Holder</b>
259  * <p>One app on the device fulfills the {@link RoleManager#ROLE_DEVICE_POLICY_MANAGEMENT Device
260 Policy Management Role} and is trusted with managing the overall state of
261  * Device Policy. This has access to much more powerful methods than
262  * <a href="#managingapps">managing apps</a>.
263  *
264  * <p id="querying"><b>Querying Device Policy</b>
265  * <p>In most cases, regular apps do not need to concern themselves with device
266  * policy, and restrictions will be enforced automatically. There are some cases
267  * where an app may wish to query device policy to provide a better user
268  * experience. Only a small number of policies allow apps to query them directly.
269  * These APIs will typically have no special required permissions.
270  *
271  * <p id="managedprovisioning"><b>Managed Provisioning</b>
272  * <p>Managed Provisioning is the process of recognising an app as a
273  * <a href="#deviceowner">Device Owner</a> or <a href="#profileowner">Profile Owner</a>. It
274  * involves presenting education and consent screens to the user to ensure they
275  * are aware of the capabilities this grants the <a href="#devicepolicycontroller">Device Policy
276  * Controller</a>
277  *
278  * <p>For more information on provisioning, see <a href="{@docRoot}work/dpc/build-dpc">Building a
279  * Device Policy Controller</a>.
280  *
281  * <p id="managed_profile">A <b>Managed Profile</b> enables data separation. For example to use
282  * a device both for personal and corporate usage. The managed profile and its
283  * {@link UserManager#getProfileParent parent} share a launcher.
284  *
285  * <p id="affiliated"><b>Affiliation</b>
286  * <p>Using the {@link #setAffiliationIds} method, a
287  * <a href="#deviceowner">Device Owner</a> can set a list of affiliation ids for the
288  * {@link UserManager#isSystemUser System User}. Any <a href="#profileowner">Profile Owner</a> on
289  * the same device can also call {@link #setAffiliationIds} to set affiliation ids
290  * for the {@link UserManager user} it is on. When there is the same ID
291  * present in both lists, the user is said to be "affiliated" and we can refer to
292  * the <a href="#profileowner">Profile Owner</a> as a "profile owner on an affiliated
293  * user" or an "affiliated profile owner".
294  *
295  * Becoming affiliated grants the <a href="#profileowner">Profile Owner</a> capabilities similar to
296  * that of the <a href="#deviceowner">Device Owner</a>. It also allows use of the
297  * {@link #bindDeviceAdminServiceAsUser} APIs for direct communication between the
298  * <a href="#deviceowner">Device Owner</a> and
299  * affiliated <a href="#profileowner">Profile Owners</a>.
300  *
301  * <p id="organization-owned"><b>Organization Owned</b></p>
302  * An organization owned device is one which is not owned by the person making use of the device and
303  * is instead owned by an organization such as their employer or education provider. These devices
304  * are recognised as being organization owned either by the presence of a
305  * <a href="#deviceowner">device owner</a> or of a
306  * {@link #isOrganizationOwnedDeviceWithManagedProfile profile which has a profile owner is marked
307  * as organization owned}.
308  *
309  * <p id="profile-on-parent-organization-owned">Profile owners running on an
310  * <a href="organization-owned">organization owned</a> device can exercise additional capabilities
311  * using the {@link #getParentProfileInstance(ComponentName)} API which apply to the parent user.
312  * Each API will indicate if it is usable in this way.
313  *
314  * <p id="automotive"><b>Android Automotive</b>
315  * <p>On {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE
316  * "Android Automotive builds"}, some methods can throw
317  * {@link UnsafeStateException "an exception"} if an action is unsafe (for example, if the vehicle
318  * is moving). Callers running on
319  * {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE
320  * "Android Automotive builds"} should always check for this exception.
321  */
322 
323 @SystemService(Context.DEVICE_POLICY_SERVICE)
324 @RequiresFeature(PackageManager.FEATURE_DEVICE_ADMIN)
325 public class DevicePolicyManager {
326 
327     /** @hide */
328     public static final String DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_FLAG =
329             "deprecate_usermanagerinternal_devicepolicy";
330     /** @hide */
331     public static final boolean DEPRECATE_USERMANAGERINTERNAL_DEVICEPOLICY_DEFAULT = true;
332     /** @hide */
333     public static final String ADD_ISFINANCED_DEVICE_FLAG =
334             "add-isfinanced-device";
335     /** @hide */
336     public static final boolean ADD_ISFINANCED_FEVICE_DEFAULT = true;
337 
338     private static String TAG = "DevicePolicyManager";
339 
340     private final Context mContext;
341     private final IDevicePolicyManager mService;
342     private final boolean mParentInstance;
343     private final DevicePolicyResourcesManager mResourcesManager;
344 
345     /** @hide */
DevicePolicyManager(Context context, IDevicePolicyManager service)346     public DevicePolicyManager(Context context, IDevicePolicyManager service) {
347         this(context, service, false);
348     }
349 
350     /** @hide */
351     @VisibleForTesting
DevicePolicyManager(Context context, IDevicePolicyManager service, boolean parentInstance)352     protected DevicePolicyManager(Context context, IDevicePolicyManager service,
353             boolean parentInstance) {
354         mContext = context;
355         mService = service;
356         mParentInstance = parentInstance;
357         mResourcesManager = new DevicePolicyResourcesManager(context, service);
358     }
359 
360     /**
361      * Fetch the current value of mService.  This is used in the binder cache lambda
362      * expressions.
363      */
getService()364     private IDevicePolicyManager getService() {
365         return mService;
366     }
367 
368     /**
369      * Fetch the current value of mParentInstance.  This is used in the binder cache
370      * lambda expressions.
371      */
isParentInstance()372     private boolean isParentInstance() {
373         return mParentInstance;
374     }
375 
376     /**
377      * Fetch the current value of mContext.  This is used in the binder cache lambda
378      * expressions.
379      */
getContext()380     private Context getContext() {
381         return mContext;
382     }
383 
384     /** @hide test will override it. */
385     @VisibleForTesting
myUserId()386     protected int myUserId() {
387         return mContext.getUserId();
388     }
389 
390     /**
391      * Activity action: Starts the provisioning flow which sets up a
392      * <a href="#managed-profile">managed profile</a>.
393      *
394      * <p>It is possible to check if provisioning is allowed or not by querying the method
395      * {@link #isProvisioningAllowed(String)}.
396      *
397      * <p>The intent may contain the following extras:
398      *
399      * <table>
400      *  <thead>
401      *      <tr>
402      *          <th>Extra</th>
403      *          <th></th>
404      *          <th>Supported Versions</th>
405      *      </tr>
406      *  </thead>
407      *  <tbody>
408      *      <tr>
409      *          <td>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}</td>
410      *          <td colspan="2"></td>
411      *      </tr>
412      *      <tr>
413      *          <td>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}</td>
414      *          <td></td>
415      *          <td>{@link android.os.Build.VERSION_CODES#N}+</td>
416      *      </tr>
417      *      <tr>
418      *          <td>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}</td>
419      *          <td colspan="2"></td>
420      *      </tr>
421      *      <tr>
422      *          <td>{@link #EXTRA_PROVISIONING_LOGO_URI}</td>
423      *          <td colspan="2"></td>
424      *      </tr>
425      *      <tr>
426      *          <td>{@link #EXTRA_PROVISIONING_SKIP_USER_CONSENT}</td>
427      *          <td colspan="2"><b>Can only be used by an existing device owner trying to create a
428      *          managed profile</b></td>
429      *      </tr>
430      *      <tr>
431      *          <td>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION}</td>
432      *          <td colspan="2"></td>
433      *      </tr>
434      *      <tr>
435      *          <td>{@link #EXTRA_PROVISIONING_DISCLAIMERS}</td>
436      *          <td colspan="2"></td>
437      *      </tr>
438      *      <tr>
439      *          <td>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</td>
440      *          <td>
441      *              <b>Required if {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} is not
442      *              specified. Must match the package name of the calling application.</b>
443      *          </td>
444      *          <td>{@link android.os.Build.VERSION_CODES#LOLLIPOP}+</td>
445      *      </tr>
446      *      <tr>
447      *          <td>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</td>
448      *          <td>
449      *              <b>Required if {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is not
450      *              specified. Package name must match the package name of the calling
451      *              application.</b>
452      *          </td>
453      *          <td>{@link android.os.Build.VERSION_CODES#M}+</td>
454      *      </tr>
455      *      <tr>
456      *          <td>{@link #EXTRA_PROVISIONING_ALLOW_OFFLINE}</td>
457      *          <td colspan="2">On {@link android.os.Build.VERSION_CODES#TIRAMISU}+, when set to
458      *          true this will <b>force</b> offline provisioning instead of allowing it</td>
459      *      </tr>
460      *  </tbody>
461      * </table>
462      *
463      * <p>When <a href="#managedprovisioning">managed provisioning</a> has completed, broadcasts
464      * are sent to the application specified in the provisioning intent. The
465      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the
466      * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in
467      * the primary profile.
468      *
469      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when managed provisioning has
470      * completed, along with the above broadcast, activity intent
471      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the profile owner.
472      *
473      * <p>If provisioning fails, the managed profile is removed so the device returns to its
474      * previous state.
475      *
476      * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
477      * result code of {@link android.app.Activity#RESULT_OK} indicates that the synchronous part of
478      * the provisioning flow was successful, although this doesn't guarantee the full flow will
479      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} indicates
480      * that the user backed-out of provisioning or some precondition for provisioning wasn't met.
481      *
482      * <p>If a <a href="#roleholder">device policy management role holder</a> updater is present on
483      * the device, an internet connection attempt must be made prior to launching this intent. If
484      * an internet connection can not be established, provisioning will fail unless {@link
485      * #EXTRA_PROVISIONING_ALLOW_OFFLINE} is explicitly set to {@code true}, in which case
486      * provisioning will continue without using the
487      * <a href="#roleholder">device policy management role holder</a>. If an internet connection
488      * has been established, the <a href="#roleholder">device policy management role holder</a>
489      * updater will be launched, which may update the
490      * <a href="#roleholder">device policy management role holder</a> before continuing
491      * provisioning.
492      */
493     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
494     public static final String ACTION_PROVISION_MANAGED_PROFILE
495         = "android.app.action.PROVISION_MANAGED_PROFILE";
496 
497     /**
498      * Activity action: Starts the provisioning flow which sets up a managed user.
499      *
500      * <p>This intent will typically be sent by a mobile device management application (MDM).
501      * Provisioning configures the user as managed user and sets the MDM as the profile
502      * owner who has full control over the user. Provisioning can only happen before user setup has
503      * been completed. Use {@link #isProvisioningAllowed(String)} to check if provisioning is
504      * allowed.
505      *
506      * <p>The intent contains the following extras:
507      * <ul>
508      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
509      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
510      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
511      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
512      * </ul>
513      *
514      * <p>If provisioning fails, the device returns to its previous state.
515      *
516      * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
517      * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
518      * the provisioning flow was successful, although this doesn't guarantee the full flow will
519      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
520      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
521      *
522      * @hide
523      */
524     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
525     public static final String ACTION_PROVISION_MANAGED_USER
526         = "android.app.action.PROVISION_MANAGED_USER";
527 
528     /**
529      * Activity action: Starts the provisioning flow which sets up a managed device.
530      * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
531      *
532      * <p> During device owner provisioning a device admin app is set as the owner of the device.
533      * A device owner has full control over the device. The device owner can not be modified by the
534      * user.
535      *
536      * <p> A typical use case would be a device that is owned by a company, but used by either an
537      * employee or client.
538      *
539      * <p> An intent with this action can be sent only on an unprovisioned device.
540      * It is possible to check if provisioning is allowed or not by querying the method
541      * {@link #isProvisioningAllowed(String)}.
542      *
543      * <p>The intent contains the following extras:
544      * <ul>
545      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
546      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
547      * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
548      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
549      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
550      * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
551      * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional</li>
552      * </ul>
553      *
554      * <p>When device owner provisioning has completed, an intent of the type
555      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
556      * device owner.
557      *
558      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
559      * completed, along with the above broadcast, activity intent
560      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
561      *
562      * <p>If provisioning fails, the device is factory reset.
563      *
564      * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
565      * of the provisioning flow was successful, although this doesn't guarantee the full flow will
566      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
567      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
568      *
569      * @deprecated to support {@link android.os.Build.VERSION_CODES#S} and later, admin apps must
570      * implement activities with intent filters for the {@link #ACTION_GET_PROVISIONING_MODE} and
571      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} intent actions; using {@link
572      * #ACTION_PROVISION_MANAGED_DEVICE} to start provisioning will cause the provisioning to fail;
573      * to additionally support pre-{@link android.os.Build.VERSION_CODES#S}, admin apps must also
574      * continue to use this constant.
575      */
576     @Deprecated
577     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
578     public static final String ACTION_PROVISION_MANAGED_DEVICE
579         = "android.app.action.PROVISION_MANAGED_DEVICE";
580 
581     /**
582      * Activity action: launch when user provisioning completed, i.e.
583      * {@link #getUserProvisioningState()} returns one of the complete state.
584      *
585      * <p> Please note that the API behavior is not necessarily consistent across various releases,
586      * and devices, as it's contract between SetupWizard and ManagedProvisioning. The default
587      * implementation is that ManagedProvisioning launches SetupWizard in NFC provisioning only.
588      *
589      * <p> The activity must be protected by permission
590      * {@link android.Manifest.permission#BIND_DEVICE_ADMIN}, and the process must hold
591      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE} to be launched.
592      * Only one {@link ComponentName} in the entire system should be enabled, and the rest of the
593      * components are not started by this intent.
594      *
595      * @deprecated Starting from Android 13, the system no longer launches an intent with this
596      * action when user provisioning completes.
597      * @hide
598      */
599     @Deprecated
600     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
601     @SystemApi
602     public static final String ACTION_STATE_USER_SETUP_COMPLETE =
603             "android.app.action.STATE_USER_SETUP_COMPLETE";
604 
605     /**
606      * Activity action: Starts the provisioning flow which sets up a managed device.
607      *
608      * <p>During device owner provisioning, a device admin app is downloaded and set as the owner of
609      * the device. A device owner has full control over the device. The device owner can not be
610      * modified by the user and the only way of resetting the device is via factory reset.
611      *
612      * <p>From version {@link android.os.Build.VERSION_CODES#Q}, the admin app can choose
613      * whether to set up a fully managed device or a managed profile. For the admin app to support
614      * this, it must have an activity with intent filter {@link #ACTION_GET_PROVISIONING_MODE} and
615      * another one with intent filter {@link #ACTION_ADMIN_POLICY_COMPLIANCE}. For example:
616      * <pre>
617      * &lt;activity
618      *     android:name=".GetProvisioningModeActivity"
619      *     android:label="@string/app_name"
620      *     android:permission="android.permission.BIND_DEVICE_ADMIN"&gt;
621      *     &lt;intent-filter&gt;
622      *         &lt;action
623      *             android:name="android.app.action.GET_PROVISIONING_MODE" /&gt;
624      *         &lt;category android:name="android.intent.category.DEFAULT" /&gt;
625      *     &lt;/intent-filter&gt;
626      * &lt;/activity&gt;
627      *
628      * &lt;activity
629      *     android:name=".PolicyComplianceActivity"
630      *     android:label="@string/app_name"
631      *     android:permission="android.permission.BIND_DEVICE_ADMIN"&gt;
632      *     &lt;intent-filter&gt;
633      *         &lt;action
634      *             android:name="android.app.action.ADMIN_POLICY_COMPLIANCE" /&gt;
635      *         &lt;category android:name="android.intent.category.DEFAULT" /&gt;
636      *     &lt;/intent-filter&gt;
637      * &lt;/activity&gt;</pre>
638      *
639      * <p>A typical use case would be a device that is owned by a company, but used by either an
640      * employee or client.
641      *
642      * <p>The provisioning message should be sent to an unprovisioned device.
643      *
644      * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
645      * by a privileged app with the permission
646      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
647      *
648      * <p>If a device policy management role holder (DPMRH) updater is present on the device, an
649      * internet connection attempt must be made prior to launching this intent. If internet
650      * connection could not be established, provisioning will fail unless {@link
651      * #EXTRA_PROVISIONING_ALLOW_OFFLINE} is explicitly set to {@code true}, in which case
652      * provisioning will continue without using the DPMRH. If an internet connection has been
653      * established, the DPMRH updater will be launched via {@link
654      * #ACTION_UPDATE_DEVICE_MANAGEMENT_ROLE_HOLDER}, which will update the DPMRH if it's not
655      * present on the device, or if it's present and not valid.
656      *
657      * <p>A DPMRH is considered valid if it has intent filters for {@link
658      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}, {@link
659      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} and {@link
660      * #ACTION_ROLE_HOLDER_PROVISION_FINALIZATION}.
661      *
662      * <p>If a DPMRH is present on the device and valid, the provisioning flow will be deferred to
663      * it via the {@link #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent.
664      *
665      * <p>The provisioning intent contains the following properties:
666      * <ul>
667      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
668      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
669      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
670      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
671      * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
672      * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
673      * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
674      * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
675      * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
676      * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
677      * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
678      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
679      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
680      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
681      * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
682      * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
683      * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
684      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
685      * <li>{@link #EXTRA_PROVISIONING_USE_MOBILE_DATA}, optional </li>
686      * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional - when not used for
687      * cloud enrollment, NFC or QR provisioning</li>
688      * </ul>
689      *
690      * @hide
691      */
692     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
693     @SystemApi
694     public static final String ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
695             "android.app.action.PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
696 
697     /**
698      * Activity action: Starts the provisioning flow which sets up a financed device.
699      *
700      * <p>During financed device provisioning, a device admin app is downloaded and set as the owner
701      * of the device. A device owner has full control over the device. The device owner can not be
702      * modified by the user.
703      *
704      * <p>A typical use case would be a device that is bought from the reseller through financing
705      * program.
706      *
707      * <p>An intent with this action can be sent only on an unprovisioned device.
708      *
709      * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
710      * by a privileged app with the permission
711      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
712      *
713      * <p>The provisioning intent contains the following properties:
714      * <ul>
715      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
716      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
717      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
718      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
719      * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
720      * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
721      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
722      * </ul>
723      *
724      * <p>Once the device admin app is set as the device owner, the following APIs are available for
725      * managing polices on the device:
726      * <ul>
727      * <li>{@link #isDeviceManaged()}</li>
728      * <li>{@link #isUninstallBlocked(ComponentName, String)}</li>
729      * <li>{@link #setUninstallBlocked(ComponentName, String, boolean)}</li>
730      * <li>{@link #setUserControlDisabledPackages(ComponentName, List)}</li>
731      * <li>{@link #getUserControlDisabledPackages(ComponentName)}</li>
732      * <li>{@link #setOrganizationName(ComponentName, CharSequence)}</li>
733      * <li>{@link #getOrganizationName(ComponentName)} </li>
734      * <li>{@link #setShortSupportMessage(ComponentName, CharSequence)}</li>
735      * <li>{@link #getShortSupportMessage(ComponentName)}</li>
736      * <li>{@link #isBackupServiceEnabled(ComponentName)}</li>
737      * <li>{@link #setBackupServiceEnabled(ComponentName, boolean)}</li>
738      * <li>{@link #isLockTaskPermitted(String)}</li>
739      * <li>{@link #setLockTaskFeatures(ComponentName, int)}, where the following lock task features
740      * can be set (otherwise a {@link SecurityException} will be thrown):</li>
741      * <ul>
742      *     <li>{@link #LOCK_TASK_FEATURE_SYSTEM_INFO}</li>
743      *     <li>{@link #LOCK_TASK_FEATURE_KEYGUARD}</li>
744      *     <li>{@link #LOCK_TASK_FEATURE_HOME}</li>
745      *     <li>{@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}</li>
746      *     <li>{@link #LOCK_TASK_FEATURE_NOTIFICATIONS}</li>
747      *     <li>{@link #LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK}</li>
748      * </ul>
749      * <li>{@link #getLockTaskFeatures(ComponentName)}</li>
750      * <li>{@link #setLockTaskPackages(ComponentName, String[])}</li>
751      * <li>{@link #getLockTaskPackages(ComponentName)}</li>
752      * <li>{@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}</li>
753      * <li>{@link #clearPackagePersistentPreferredActivities(ComponentName, String)} </li>
754      * <li>{@link #wipeData(int)}</li>
755      * <li>{@link #isDeviceOwnerApp(String)}</li>
756      * <li>{@link #clearDeviceOwnerApp(String)}</li>
757      * <li>{@link #setPermissionGrantState(ComponentName, String, String, int)}, where
758      * {@link permission#READ_PHONE_STATE} is the <b>only</b> permission that can be
759      * {@link #PERMISSION_GRANT_STATE_GRANTED}, {@link #PERMISSION_GRANT_STATE_DENIED}, or
760      * {@link #PERMISSION_GRANT_STATE_DEFAULT} and can <b>only</b> be applied to the device admin
761      * app (otherwise a {@link SecurityException} will be thrown)</li>
762      * <li>{@link #getPermissionGrantState(ComponentName, String, String)}, where
763      * {@link permission#READ_PHONE_STATE} is the <b>only</b> permission that can be
764      * used and device admin app is the only package that can be used to retrieve the permission
765      * permission grant state for (otherwise a {@link SecurityException} will be thrown)</li>
766      * <li>{@link #addUserRestriction(ComponentName, String)}, where the following user restrictions
767      * are permitted (otherwise a {@link SecurityException} will be thrown):</li>
768      * <ul>
769      *     <li>{@link UserManager#DISALLOW_ADD_USER}</li>
770      *     <li>{@link UserManager#DISALLOW_DEBUGGING_FEATURES}</li>
771      *     <li>{@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}</li>
772      *     <li>{@link UserManager#DISALLOW_SAFE_BOOT}</li>
773      *     <li>{@link UserManager#DISALLOW_CONFIG_DATE_TIME}</li>
774      *     <li>{@link UserManager#DISALLOW_OUTGOING_CALLS}</li>
775      * </ul>
776      * <li>{@link #getUserRestrictions(ComponentName)}</li>
777      * <li>{@link #clearUserRestriction(ComponentName, String)}, where the following user
778      * restrictions are permitted (otherwise a {@link SecurityException} will be thrown):</li>
779      * <ul>
780      *     <li>{@link UserManager#DISALLOW_ADD_USER}</li>
781      *     <li>{@link UserManager#DISALLOW_DEBUGGING_FEATURES}</li>
782      *     <li>{@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}</li>
783      *     <li>{@link UserManager#DISALLOW_SAFE_BOOT}</li>
784      *     <li>{@link UserManager#DISALLOW_CONFIG_DATE_TIME}</li>
785      *     <li>{@link UserManager#DISALLOW_OUTGOING_CALLS}</li>
786      * </ul>
787      * </ul>
788      *
789      * @hide
790      */
791     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
792     @SystemApi
793     public static final String ACTION_PROVISION_FINANCED_DEVICE =
794             "android.app.action.PROVISION_FINANCED_DEVICE";
795 
796     /**
797      * Activity action: Finalizes management provisioning, should be used after user-setup
798      * has been completed and {@link #getUserProvisioningState()} returns one of:
799      * <ul>
800      * <li>{@link #STATE_USER_SETUP_INCOMPLETE}</li>
801      * <li>{@link #STATE_USER_SETUP_COMPLETE}</li>
802      * <li>{@link #STATE_USER_PROFILE_COMPLETE}</li>
803      * </ul>
804      *
805      * <p>If a device policy management role holder (DPMRH) is present on the device and
806      * valid, the provisioning flow will be deferred to it via the {@link
807      * #ACTION_ROLE_HOLDER_PROVISION_FINALIZATION} intent.
808      *
809      * @hide
810      */
811     @SystemApi
812     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
813     public static final String ACTION_PROVISION_FINALIZATION
814             = "android.app.action.PROVISION_FINALIZATION";
815 
816     /**
817      * Activity action: starts the managed profile provisioning flow inside the device policy
818      * management role holder.
819      *
820      * <p>During the managed profile provisioning flow, the platform-provided provisioning handler
821      * will delegate provisioning to the device policy management role holder, by firing this
822      * intent. Third-party mobile device management applications attempting to fire this intent will
823      * receive a {@link SecurityException}.
824      *
825      * <p>Device policy management role holders are required to have a handler for this intent
826      * action.
827      *
828      * <p>If {@link #EXTRA_ROLE_HOLDER_STATE} is supplied to this intent, it is the responsibility
829      * of the role holder to restore its state from this extra. This is the same {@link Bundle}
830      * which the role holder returns alongside {@link #RESULT_UPDATE_ROLE_HOLDER}.
831      *
832      * <p>A result code of {@link Activity#RESULT_OK} implies that managed profile provisioning
833      * finished successfully. If it did not, a result code of {@link Activity#RESULT_CANCELED}
834      * is used instead.
835      *
836      * @see #ACTION_PROVISION_MANAGED_PROFILE
837      *
838      * @hide
839      */
840     @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP)
841     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
842     @SystemApi
843     public static final String ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE =
844             "android.app.action.ROLE_HOLDER_PROVISION_MANAGED_PROFILE";
845 
846     /**
847      * Result code that can be returned by the {@link
848      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link
849      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent handlers if a work
850      * profile has been created.
851      *
852      * @hide
853      */
854     @SystemApi
855     public static final int RESULT_WORK_PROFILE_CREATED = 122;
856 
857     /**
858      * Result code that can be returned by the {@link
859      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link
860      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent handlers if the
861      * device owner was set.
862      *
863      * @hide
864      */
865     @SystemApi
866     public static final int RESULT_DEVICE_OWNER_SET = 123;
867 
868     /**
869      * Activity action: starts the trusted source provisioning flow inside the device policy
870      * management role holder.
871      *
872      * <p>During the trusted source provisioning flow, the platform-provided provisioning handler
873      * will delegate provisioning to the device policy management role holder, by firing this
874      * intent. Third-party mobile device management applications attempting to fire this intent will
875      * receive a {@link SecurityException}.
876      *
877      * <p>Device policy management role holders are required to have a handler for this intent
878      * action.
879      *
880      * <p>If {@link #EXTRA_ROLE_HOLDER_STATE} is supplied to this intent, it is the responsibility
881      * of the role holder to restore its state from this extra. This is the same {@link Bundle}
882      * which the role holder returns alongside {@link #RESULT_UPDATE_ROLE_HOLDER}.
883      *
884      * <p>The result codes can be either {@link #RESULT_WORK_PROFILE_CREATED}, {@link
885      * #RESULT_DEVICE_OWNER_SET} or {@link Activity#RESULT_CANCELED} if provisioning failed.
886      *
887      * @see #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE
888      *
889      * @hide
890      */
891     @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP)
892     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
893     @SystemApi
894     public static final String ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
895             "android.app.action.ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
896 
897     /**
898      * Activity action: starts the provisioning finalization flow inside the device policy
899      * management role holder.
900      *
901      * <p>During the provisioning finalization flow, the platform-provided provisioning handler
902      * will delegate provisioning to the device policy management role holder, by firing this
903      * intent. Third-party mobile device management applications attempting to fire this intent will
904      * receive a {@link SecurityException}.
905      *
906      * <p>Device policy management role holders are required to have a handler for this intent
907      * action.
908      *
909      * <p>This handler forwards the result from the admin app's {@link
910      * #ACTION_ADMIN_POLICY_COMPLIANCE} handler. Result code {@link Activity#RESULT_CANCELED}
911      * implies the provisioning finalization flow has failed.
912      *
913      * @see #ACTION_PROVISION_FINALIZATION
914      *
915      * @hide
916      */
917     @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP)
918     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
919     @SystemApi
920     public static final String ACTION_ROLE_HOLDER_PROVISION_FINALIZATION =
921             "android.app.action.ROLE_HOLDER_PROVISION_FINALIZATION";
922 
923     /**
924      * {@link Activity} result code which can be returned by {@link
925      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} and {@link
926      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} to signal that an update
927      * to the role holder is required.
928      *
929      * <p>This result code can be accompanied by {@link #EXTRA_ROLE_HOLDER_STATE}.
930      *
931      * @hide
932      */
933     @SystemApi
934     public static final int RESULT_UPDATE_ROLE_HOLDER = 2;
935 
936     /**
937      * A {@link PersistableBundle} extra which the role holder can use to describe its own state
938      * when it returns {@link #RESULT_UPDATE_ROLE_HOLDER}.
939      *
940      * <p>If {@link #RESULT_UPDATE_ROLE_HOLDER} was accompanied by this extra, after the update
941      * completes, the role holder's {@link #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} or {@link
942      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent will be relaunched,
943      * which will contain this extra. It is the role holder's responsibility to restore its
944      * state from this extra.
945      *
946      * <p>The content of this {@link PersistableBundle} is entirely up to the role holder. It
947      * should contain anything the role holder needs to restore its original state when it gets
948      * restarted.
949      *
950      * @hide
951      */
952     @SystemApi
953     public static final String EXTRA_ROLE_HOLDER_STATE = "android.app.extra.ROLE_HOLDER_STATE";
954 
955     /**
956      * A {@code boolean} extra which determines whether to force a role holder update, regardless
957      * of any internal conditions {@link #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} might
958      * have.
959      *
960      * <p>This extra can be provided to intents with action {@link
961      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER}.
962      *
963      * @hide
964      */
965     @SystemApi
966     public static final String EXTRA_FORCE_UPDATE_ROLE_HOLDER =
967             "android.app.extra.FORCE_UPDATE_ROLE_HOLDER";
968 
969     /**
970      * A boolean extra indicating whether offline provisioning should be used.
971      *
972      * <p>The default value is {@code false}.
973      *
974      * <p>Usually during the <a href="#managedprovisioning">provisioning flow</a>, there will be
975      * an attempt to download and install the latest version of the <a href="#roleholder">device
976      * policy management role holder</a>. The platform will then
977      * delegate provisioning to the <a href="#roleholder">device
978      *      * policy management role holder</a>.
979      *
980      * <p>When this extra is set to {@code true}, the
981      * <a href="#managedprovisioning">provisioning flow</a> will always be handled by the platform
982      * and the <a href="#roleholder">device policy management role holder</a>'s part skipped.
983      *
984      * <p>On Android versions prior to {@link Build.VERSION_CODES#TIRAMISU}, when this extra is
985      * {@code false}, the <a href="#managedprovisioning">provisioning flow</a> will enforce that an
986      * internet connection is established, or otherwise fail. When this extra is {@code true}, a
987      * connection will still be attempted but when it cannot be established provisioning will
988      * continue offline.
989      */
990     public static final String EXTRA_PROVISIONING_ALLOW_OFFLINE =
991             "android.app.extra.PROVISIONING_ALLOW_OFFLINE";
992 
993     /**
994      * A String extra holding a url that specifies the download location of the device policy
995      * management role holder package.
996      *
997      * <p>This is only meant to be used in cases when a specific variant of the role holder package
998      * is needed (such as a debug variant). If not provided, the default variant of the device
999      * manager role holder package is downloaded.
1000      *
1001      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
1002      * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1003      * provisioning via an NFC bump.
1004      *
1005      * @hide
1006      */
1007     @SystemApi
1008     public static final String EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION =
1009             "android.app.extra.PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION";
1010 
1011     /**
1012      * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
1013      * android package archive at the download location specified in {@link
1014      * #EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION}.
1015      *
1016      * <p>The signatures of an android package archive can be obtained using
1017      * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
1018      * {@link android.content.pm.PackageManager#GET_SIGNING_CERTIFICATES}.
1019      *
1020      * <p>If {@link #EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION} is provided, it must
1021      * be accompanied by this extra. The provided checksum must match the checksum of any signature
1022      * of the file at the download location. If the checksum does not match an error will be shown
1023      * to the user and the user will be asked to factory reset the device.
1024      *
1025      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
1026      * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1027      * provisioning via an NFC bump.
1028      *
1029      * @hide
1030      */
1031     @SystemApi
1032     public static final String EXTRA_PROVISIONING_ROLE_HOLDER_SIGNATURE_CHECKSUM =
1033             "android.app.extra.PROVISIONING_ROLE_HOLDER_SIGNATURE_CHECKSUM";
1034 
1035     /**
1036      * A String extra holding a http cookie header which should be used in the http request to the
1037      * url specified in {@link #EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_LOCATION}.
1038      *
1039      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
1040      * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1041      * provisioning via an NFC bump.
1042      *
1043      * @hide
1044      */
1045     @SystemApi
1046     public static final String EXTRA_PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_COOKIE_HEADER =
1047             "android.app.extra.PROVISIONING_ROLE_HOLDER_PACKAGE_DOWNLOAD_COOKIE_HEADER";
1048 
1049     /**
1050      * An extra of type {@link android.os.PersistableBundle} that allows the provisioning initiator
1051      * to pass data to the device policy management role holder.
1052      *
1053      * <p>The device policy management role holder will receive this extra via the {@link
1054      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent.
1055      *
1056      * <p>The contents of this extra are up to the contract between the provisioning initiator
1057      * and the device policy management role holder.
1058      *
1059      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
1060      * or in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1061      * provisioning via an NFC bump.
1062      *
1063      * @hide
1064      */
1065     @SystemApi
1066     public static final String EXTRA_PROVISIONING_ROLE_HOLDER_EXTRAS_BUNDLE =
1067             "android.app.extra.PROVISIONING_ROLE_HOLDER_EXTRAS_BUNDLE";
1068 
1069     /**
1070      * A String extra containing the package name of the provisioning initiator.
1071      *
1072      * <p>Use in an intent with action {@link
1073      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}.
1074      *
1075      * @hide
1076      */
1077     @SystemApi
1078     public static final String EXTRA_ROLE_HOLDER_PROVISIONING_INITIATOR_PACKAGE =
1079             "android.app.extra.ROLE_HOLDER_PROVISIONING_INITIATOR_PACKAGE";
1080 
1081     /**
1082      * An {@link Intent} result extra specifying the {@link Intent} to be launched after
1083      * provisioning is finalized.
1084      *
1085      * <p>If {@link #EXTRA_PROVISIONING_SHOULD_LAUNCH_RESULT_INTENT} is set to {@code false},
1086      * this result will be supplied as part of the result {@link Intent} for provisioning actions
1087      * such as {@link #ACTION_PROVISION_MANAGED_PROFILE}. This result will also be supplied as
1088      * part of the result {@link Intent} for the device policy management role holder provisioning
1089      * actions.
1090      */
1091     public static final String EXTRA_RESULT_LAUNCH_INTENT =
1092             "android.app.extra.RESULT_LAUNCH_INTENT";
1093 
1094     /**
1095      * A boolean extra that determines whether the provisioning flow should launch the resulting
1096      * launch intent, if one is supplied by the device policy management role holder via {@link
1097      * #EXTRA_RESULT_LAUNCH_INTENT}. Default value is {@code false}.
1098      *
1099      * <p>If {@code true}, the resulting intent will be launched by the provisioning flow, if one
1100      * is supplied by the device policy management role holder.
1101      *
1102      * <p>If {@code false}, the resulting intent will be returned as {@link
1103      * #EXTRA_RESULT_LAUNCH_INTENT} to the provisioning initiator, if one is supplied by the device
1104      * manager role holder. It will be the responsibility of the provisioning initiator to launch
1105      * this {@link Intent} after provisioning completes.
1106      *
1107      * <p>This extra is respected when provided via the provisioning intent actions such as {@link
1108      * #ACTION_PROVISION_MANAGED_PROFILE}.
1109      */
1110     public static final String EXTRA_PROVISIONING_SHOULD_LAUNCH_RESULT_INTENT =
1111             "android.app.extra.PROVISIONING_SHOULD_LAUNCH_RESULT_INTENT";
1112 
1113     /**
1114      * Action: Bugreport sharing with device owner has been accepted by the user.
1115      *
1116      * @hide
1117      */
1118     public static final String ACTION_BUGREPORT_SHARING_ACCEPTED =
1119             "com.android.server.action.REMOTE_BUGREPORT_SHARING_ACCEPTED";
1120 
1121     /**
1122      * Action: Bugreport sharing with device owner has been declined by the user.
1123      *
1124      * @hide
1125      */
1126     public static final String ACTION_BUGREPORT_SHARING_DECLINED =
1127             "com.android.server.action.REMOTE_BUGREPORT_SHARING_DECLINED";
1128 
1129     /**
1130      * Action: Bugreport has been collected and is dispatched to {@code DevicePolicyManagerService}.
1131      *
1132      * @hide
1133      */
1134     public static final String ACTION_REMOTE_BUGREPORT_DISPATCH =
1135             "android.intent.action.REMOTE_BUGREPORT_DISPATCH";
1136 
1137     /**
1138      * Extra for shared bugreport's SHA-256 hash.
1139      *
1140      * @hide
1141      */
1142     public static final String EXTRA_REMOTE_BUGREPORT_HASH =
1143             "android.intent.extra.REMOTE_BUGREPORT_HASH";
1144 
1145     /**
1146      * Extra for shared bugreport's nonce in long integer type.
1147      *
1148      * @hide
1149      */
1150     public static final String EXTRA_REMOTE_BUGREPORT_NONCE =
1151             "android.intent.extra.REMOTE_BUGREPORT_NONCE";
1152 
1153     /**
1154      * Extra for remote bugreport notification shown type.
1155      *
1156      * @hide
1157      */
1158     public static final String EXTRA_BUGREPORT_NOTIFICATION_TYPE =
1159             "android.app.extra.bugreport_notification_type";
1160 
1161     /**
1162      * Default value for preferential network service enabling.
1163      *
1164      * @hide
1165      */
1166     public static final boolean PREFERENTIAL_NETWORK_SERVICE_ENABLED_DEFAULT = false;
1167 
1168     /**
1169      * Notification type for a started remote bugreport flow.
1170      *
1171      * @hide
1172      */
1173     public static final int NOTIFICATION_BUGREPORT_STARTED = 1;
1174 
1175     /**
1176      * Notification type for a bugreport that has already been accepted to be shared, but is still
1177      * being taken.
1178      *
1179      * @hide
1180      */
1181     public static final int NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED = 2;
1182 
1183     /**
1184      * Notification type for a bugreport that has been taken and can be shared or declined.
1185      *
1186      * @hide
1187      */
1188     public static final int NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED = 3;
1189 
1190     /**
1191      * Default and maximum timeout in milliseconds after which unlocking with weak auth times out,
1192      * i.e. the user has to use a strong authentication method like password, PIN or pattern.
1193      *
1194      * @hide
1195      */
1196     public static final long DEFAULT_STRONG_AUTH_TIMEOUT_MS = 72 * 60 * 60 * 1000; // 72h
1197 
1198     /**
1199      * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that is
1200      * passed directly to the <a href="#devicepolicycontroller">Device Policy Controller</a>
1201      * after <a href="#managed-provisioning">provisioning</a>.
1202      *
1203      * <p>
1204      * Starting from {@link android.os.Build.VERSION_CODES#M}, if used with
1205      * {@link #MIME_TYPE_PROVISIONING_NFC} as part of NFC managed device provisioning, the NFC
1206      * message should contain a stringified {@link java.util.Properties} instance, whose string
1207      * properties will be converted into a {@link android.os.PersistableBundle} and passed to the
1208      * management application after provisioning.
1209      */
1210     public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE =
1211             "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE";
1212 
1213     /**
1214      * A String extra holding the package name of the application that
1215      * will be set as <a href="#devicepolicycontroller">Device Policy Controller</a>.
1216      *
1217      * <p>When this extra is set, the application must have exactly one
1218      * {@link DeviceAdminReceiver device admin receiver}. This receiver will be set as the
1219      * <a href="#devicepolicycontroller">Device Policy Controller</a>.
1220      *
1221      * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}.
1222      */
1223     @Deprecated
1224     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME
1225         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME";
1226 
1227     /**
1228      * A ComponentName extra indicating the {@link DeviceAdminReceiver device admin receiver} of
1229      * the application that will be set as the <a href="#devicepolicycontroller">
1230      *     Device Policy Controller</a>.
1231      *
1232      * <p>If an application starts provisioning directly via an intent with action
1233      * {@link #ACTION_PROVISION_MANAGED_DEVICE} the package name of this
1234      * component has to match the package name of the application that started provisioning.
1235      *
1236      * <p>This component is set as device owner and active admin when device owner provisioning is
1237      * started by an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or by an NFC
1238      * message containing an NFC record with MIME type
1239      * {@link #MIME_TYPE_PROVISIONING_NFC}. For the NFC record, the component name must be
1240      * flattened to a string, via {@link ComponentName#flattenToShortString()}.
1241      */
1242     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME
1243         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME";
1244 
1245     /**
1246      * An {@link android.accounts.Account} extra holding the account to migrate during managed
1247      * profile provisioning.
1248      *
1249      * <p>If the account supplied is present in the user, it will be copied, along with its
1250      * credentials to the managed profile and removed from the user.
1251      */
1252     public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
1253         = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE";
1254 
1255     /**
1256      * Boolean extra to indicate that the
1257      * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE migrated account} should be kept.
1258      *
1259      * <p>If it's set to {@code true}, the account will not be removed from the user after it is
1260      * migrated to the newly created user or profile.
1261      *
1262      * <p>Defaults to {@code false}
1263      *
1264      * @see #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
1265      */
1266     public static final String EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION
1267             = "android.app.extra.PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION";
1268 
1269     /**
1270      * @deprecated From {@link android.os.Build.VERSION_CODES#O}, never used while provisioning the
1271      * device.
1272      */
1273     @Deprecated
1274     public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
1275         = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
1276 
1277     /**
1278      * A integer extra indicating the predominant color to show during the provisioning.
1279      * Refer to {@link android.graphics.Color} for how the color is represented.
1280      *
1281      * <p>Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1282      * {@link #ACTION_PROVISION_MANAGED_DEVICE}.
1283      *
1284      * @deprecated Color customization is no longer supported in the provisioning flow.
1285      */
1286     @Deprecated
1287     public static final String EXTRA_PROVISIONING_MAIN_COLOR =
1288              "android.app.extra.PROVISIONING_MAIN_COLOR";
1289 
1290     /**
1291      * A Boolean extra that can be used by the mobile device management application to skip the
1292      * disabling of system apps during provisioning when set to {@code true}.
1293      *
1294      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC}, an intent with action
1295      * {@link #ACTION_PROVISION_MANAGED_PROFILE} that starts profile owner provisioning or
1296      * set as an extra to the intent result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
1297      */
1298     public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED =
1299             "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED";
1300 
1301     /**
1302      * A String extra holding the time zone {@link android.app.AlarmManager} that the device
1303      * will be set to.
1304      *
1305      * <p>Use only for device owner provisioning. This extra can be returned by the admin app when
1306      * performing the admin-integrated provisioning flow as a result of the {@link
1307      * #ACTION_GET_PROVISIONING_MODE} activity.
1308      *
1309      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1310      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1311      */
1312     public static final String EXTRA_PROVISIONING_TIME_ZONE
1313         = "android.app.extra.PROVISIONING_TIME_ZONE";
1314 
1315     /**
1316      * A Long extra holding the wall clock time (in milliseconds) to be set on the device's
1317      * {@link android.app.AlarmManager}.
1318      *
1319      * <p>Use only for device owner provisioning. This extra can be returned by the admin app when
1320      * performing the admin-integrated provisioning flow as a result of the {@link
1321      * #ACTION_GET_PROVISIONING_MODE} activity.
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     public static final String EXTRA_PROVISIONING_LOCAL_TIME
1327         = "android.app.extra.PROVISIONING_LOCAL_TIME";
1328 
1329     /**
1330      * A String extra holding the {@link java.util.Locale} that the device will be set to.
1331      * Format: xx_yy, where xx is the language code, and yy the country code.
1332      *
1333      * <p>Use only for device owner provisioning. This extra can be returned by the admin app when
1334      * performing the admin-integrated provisioning flow as a result of the {@link
1335      * #ACTION_GET_PROVISIONING_MODE} activity.
1336      *
1337      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1338      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1339      */
1340     public static final String EXTRA_PROVISIONING_LOCALE
1341         = "android.app.extra.PROVISIONING_LOCALE";
1342 
1343     /**
1344      * A String extra holding the ssid of the wifi network that should be used during nfc device
1345      * owner provisioning for downloading the mobile device management application.
1346      *
1347      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1348      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1349      */
1350     public static final String EXTRA_PROVISIONING_WIFI_SSID
1351         = "android.app.extra.PROVISIONING_WIFI_SSID";
1352 
1353     /**
1354      * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
1355      * is hidden or not.
1356      *
1357      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1358      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1359      */
1360     public static final String EXTRA_PROVISIONING_WIFI_HIDDEN
1361         = "android.app.extra.PROVISIONING_WIFI_HIDDEN";
1362 
1363     /**
1364      * A String extra indicating the security type of the wifi network in
1365      * {@link #EXTRA_PROVISIONING_WIFI_SSID} and could be one of {@code NONE}, {@code WPA},
1366      * {@code WEP} or {@code EAP}.
1367      *
1368      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1369      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1370      */
1371     public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE
1372         = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE";
1373 
1374     /**
1375      * A String extra holding the password of the wifi network in
1376      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1377      *
1378      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1379      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1380      */
1381     public static final String EXTRA_PROVISIONING_WIFI_PASSWORD =
1382             "android.app.extra.PROVISIONING_WIFI_PASSWORD";
1383 
1384     /**
1385      * The EAP method of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
1386      * and could be one of {@code PEAP}, {@code TLS}, {@code TTLS}, {@code PWD}, {@code SIM},
1387      * {@code AKA} or {@code AKA_PRIME}. This is only used if the
1388      * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1389      *
1390      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1391      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1392      */
1393     public static final String EXTRA_PROVISIONING_WIFI_EAP_METHOD =
1394             "android.app.extra.PROVISIONING_WIFI_EAP_METHOD";
1395 
1396     /**
1397      * The phase 2 authentication of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
1398      * and could be one of {@code NONE}, {@code PAP}, {@code MSCHAP}, {@code MSCHAPV2}, {@code GTC},
1399      * {@code SIM}, {@code AKA} or {@code AKA_PRIME}. This is only used if the
1400      * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1401      *
1402      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1403      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1404      */
1405     public static final String EXTRA_PROVISIONING_WIFI_PHASE2_AUTH =
1406             "android.app.extra.PROVISIONING_WIFI_PHASE2_AUTH";
1407 
1408     /**
1409      * The CA certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This should
1410      * be an X.509 certificate Base64 encoded DER format, ie. PEM representation of a certificate
1411      * without header, footer and line breaks. <a href=
1412      * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only
1413      * used if the {@link
1414      * #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1415      *
1416      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1417      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1418      */
1419     public static final String EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE =
1420             "android.app.extra.PROVISIONING_WIFI_CA_CERTIFICATE";
1421 
1422     /**
1423      * The user certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This
1424      * should be an X.509 certificate and private key Base64 encoded DER format, ie. PEM
1425      * representation of a certificate and key without header, footer and line breaks. <a href=
1426      * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only
1427      * used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1428      *
1429      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1430      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1431      */
1432     public static final String EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE =
1433             "android.app.extra.PROVISIONING_WIFI_USER_CERTIFICATE";
1434 
1435     /**
1436      * The identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used
1437      * if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1438      *
1439      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1440      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1441      */
1442     public static final String EXTRA_PROVISIONING_WIFI_IDENTITY =
1443             "android.app.extra.PROVISIONING_WIFI_IDENTITY";
1444 
1445     /**
1446      * The anonymous identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is
1447      * only used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1448      *
1449      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1450      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1451      */
1452 
1453     public static final String EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY =
1454             "android.app.extra.PROVISIONING_WIFI_ANONYMOUS_IDENTITY";
1455     /**
1456      * The domain of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used if
1457      * the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
1458      *
1459      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1460      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1461      */
1462     public static final String EXTRA_PROVISIONING_WIFI_DOMAIN =
1463             "android.app.extra.PROVISIONING_WIFI_DOMAIN";
1464 
1465     /**
1466      * A String extra holding the proxy host for the wifi network in
1467      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1468      *
1469      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1470      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1471      */
1472     public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST
1473         = "android.app.extra.PROVISIONING_WIFI_PROXY_HOST";
1474 
1475     /**
1476      * An int extra holding the proxy port for the wifi network in
1477      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1478      *
1479      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1480      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1481      */
1482     public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT
1483         = "android.app.extra.PROVISIONING_WIFI_PROXY_PORT";
1484 
1485     /**
1486      * A String extra holding the proxy bypass for the wifi network in
1487      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1488      *
1489      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1490      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1491      */
1492     public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS
1493         = "android.app.extra.PROVISIONING_WIFI_PROXY_BYPASS";
1494 
1495     /**
1496      * A String extra holding the proxy auto-config (PAC) URL for the wifi network in
1497      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
1498      *
1499      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1500      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1501      */
1502     public static final String EXTRA_PROVISIONING_WIFI_PAC_URL
1503         = "android.app.extra.PROVISIONING_WIFI_PAC_URL";
1504 
1505     /**
1506      * A String extra holding a url that specifies the download location of the device admin
1507      * package. When not provided it is assumed that the device admin package is already installed.
1508      *
1509      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1510      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1511      */
1512     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION
1513         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION";
1514 
1515     /**
1516      * A String extra holding the localized name of the organization under management.
1517      *
1518      * The name is displayed only during provisioning.
1519      *
1520      * <p>Use in an intent with action {@link #ACTION_PROVISION_FINANCED_DEVICE}
1521      *
1522      * @hide
1523      */
1524     @SystemApi
1525     public static final String EXTRA_PROVISIONING_ORGANIZATION_NAME =
1526             "android.app.extra.PROVISIONING_ORGANIZATION_NAME";
1527 
1528     /**
1529      * A String extra holding a url to the website of the device provider so the user can open it
1530      * during provisioning. If the url is not HTTPS, an error will be shown.
1531      *
1532      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
1533      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
1534      *
1535      * @hide
1536      */
1537     @SystemApi
1538     public static final String EXTRA_PROVISIONING_SUPPORT_URL =
1539             "android.app.extra.PROVISIONING_SUPPORT_URL";
1540 
1541     /**
1542      * A String extra holding the localized name of the device admin package. It should be the same
1543      * as the app label of the package.
1544      *
1545      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
1546      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
1547      *
1548      * @deprecated This extra is no longer respected in the provisioning flow.
1549      * @hide
1550      */
1551     @Deprecated
1552     @SystemApi
1553     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL =
1554             "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL";
1555 
1556     /**
1557      * A {@link Uri} extra pointing to the app icon of device admin package. This image will be
1558      * shown during the provisioning.
1559      * <h5>The following URI schemes are accepted:</h5>
1560      * <ul>
1561      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1562      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1563      * </ul>
1564      *
1565      * <p> It is the responsibility of the caller to provide an image with a reasonable
1566      * pixel density for the device.
1567      *
1568      * <p> If a content: URI is passed, the intent should have the flag
1569      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1570      * {@link android.content.ClipData} of the intent too.
1571      *
1572      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
1573      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
1574      *
1575      * @deprecated This extra is no longer respected in the provisioning flow.
1576      * @hide
1577      */
1578     @SystemApi
1579     @Deprecated
1580     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI =
1581             "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI";
1582 
1583     /**
1584      * An int extra holding a minimum required version code for the device admin package. If the
1585      * device admin is already installed on the device, it will only be re-downloaded from
1586      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION} if the version of the
1587      * installed package is less than this version code.
1588      *
1589      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1590      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1591      */
1592     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE
1593         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE";
1594 
1595     /**
1596      * A String extra holding a http cookie header which should be used in the http request to the
1597      * url specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
1598      *
1599      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1600      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1601      */
1602     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER
1603         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER";
1604 
1605     /**
1606      * A String extra holding the URL-safe base64 encoded SHA-256 hash of the file at download
1607      * location specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
1608      *
1609      * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM} must be
1610      * present. The provided checksum must match the checksum of the file at the download
1611      * location. If the checksum doesn't match an error will be shown to the user and the user will
1612      * be asked to factory reset the device.
1613      *
1614      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1615      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1616      *
1617      * <p><strong>Note:</strong> for devices running {@link android.os.Build.VERSION_CODES#LOLLIPOP}
1618      * and {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} only SHA-1 hash is supported.
1619      * Starting from {@link android.os.Build.VERSION_CODES#M}, this parameter accepts SHA-256 in
1620      * addition to SHA-1. From {@link android.os.Build.VERSION_CODES#Q}, only SHA-256 hash is
1621      * supported.
1622      */
1623     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM
1624         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM";
1625 
1626     /**
1627      * A boolean extra indicating the admin of a fully-managed device opts out of controlling
1628      * permission grants for sensor-related permissions,
1629      * see {@link #setPermissionGrantState(ComponentName, String, String, int)}.
1630      *
1631      * The default for this extra is {@code false} - by default, the admin of a fully-managed
1632      * device has the ability to grant sensors-related permissions.
1633      *
1634      * <p>Use only for device owner provisioning. This extra can be returned by the
1635      * admin app when performing the admin-integrated provisioning flow as a result of the
1636      * {@link #ACTION_GET_PROVISIONING_MODE} activity.
1637      *
1638      * <p>This extra may also be provided to the admin app via an intent extra for {@link
1639      * #ACTION_GET_PROVISIONING_MODE}.
1640      *
1641      * @see #ACTION_GET_PROVISIONING_MODE
1642      */
1643     public static final String EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT =
1644             "android.app.extra.PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT";
1645 
1646     /**
1647      * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
1648      * android package archive at the download location specified in {@link
1649      * #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
1650      *
1651      * <p>The signatures of an android package archive can be obtained using
1652      * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
1653      * {@link android.content.pm.PackageManager#GET_SIGNATURES}.
1654      *
1655      * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM} must be
1656      * present. The provided checksum must match the checksum of any signature of the file at
1657      * the download location. If the checksum does not match an error will be shown to the user and
1658      * the user will be asked to factory reset the device.
1659      *
1660      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1661      * provisioning via an NFC bump. It can also be used for QR code provisioning.
1662      */
1663     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM
1664         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM";
1665 
1666     /**
1667      * Broadcast Action: This broadcast is sent to indicate that provisioning of a managed profile
1668      * has completed successfully.
1669      *
1670      * <p>The broadcast is limited to the primary profile, to the app specified in the provisioning
1671      * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
1672      *
1673      * <p>This intent will contain the following extras
1674      * <ul>
1675      * <li>{@link Intent#EXTRA_USER}, corresponds to the {@link UserHandle} of the managed
1676      * profile.</li>
1677      * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, corresponds to the account requested to
1678      * be migrated at provisioning time, if any.</li>
1679      * </ul>
1680      */
1681     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1682     public static final String ACTION_MANAGED_PROFILE_PROVISIONED
1683         = "android.app.action.MANAGED_PROFILE_PROVISIONED";
1684 
1685     /**
1686      * Activity action: This activity action is sent to indicate that provisioning of a managed
1687      * profile or managed device has completed successfully. It'll be sent at the same time as
1688      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast but this will be
1689      * delivered faster as it's an activity intent.
1690      *
1691      * <p>The intent is only sent to the new device or profile owner.
1692      *
1693      * @see #ACTION_PROVISION_MANAGED_PROFILE
1694      * @see #ACTION_PROVISION_MANAGED_DEVICE
1695      */
1696     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1697     public static final String ACTION_PROVISIONING_SUCCESSFUL =
1698             "android.app.action.PROVISIONING_SUCCESSFUL";
1699 
1700     /**
1701      * A boolean extra indicating whether device encryption can be skipped as part of
1702      * <a href="#managed-provisioning">provisioning</a>.
1703      *
1704      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
1705      * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
1706      *
1707      * <p>From {@link android.os.Build.VERSION_CODES#N} onwards, this is also supported for an
1708      * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
1709      */
1710     public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION =
1711              "android.app.extra.PROVISIONING_SKIP_ENCRYPTION";
1712 
1713     /**
1714      * A {@link Uri} extra pointing to a logo image. This image will be shown during the
1715      * provisioning. If this extra is not passed, a default image will be shown.
1716      *
1717      * <p><b>The following URI schemes are accepted:</b>
1718      * <ul>
1719      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1720      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1721      * </ul>
1722      *
1723      * <p>It is the responsibility of the caller to provide an image with a reasonable
1724      * pixel density for the device.
1725      *
1726      * <p>If a content: URI is passed, the intent should also have the flag
1727      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1728      * {@link android.content.ClipData} of the intent.
1729      *
1730      * @deprecated Logo customization is no longer supported in the
1731      *             <a href="#managedprovisioning">provisioning flow</a>.
1732      */
1733     @Deprecated
1734     public static final String EXTRA_PROVISIONING_LOGO_URI =
1735             "android.app.extra.PROVISIONING_LOGO_URI";
1736 
1737     /**
1738      * A {@link Bundle}[] extra consisting of list of disclaimer headers and disclaimer contents.
1739      *
1740      * <p>Each {@link Bundle} must have both {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}
1741      * as disclaimer header, and {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} as disclaimer
1742      * content.
1743      *
1744      * <p> The extra typically contains one disclaimer from the company of mobile device
1745      * management application (MDM), and one disclaimer from the organization.
1746      *
1747      * <p> Call {@link Bundle#putParcelableArray(String, Parcelable[])} to put the {@link Bundle}[]
1748      *
1749      * <p> Maximum 3 key-value pairs can be specified. The rest will be ignored.
1750      *
1751      * <p> Can be used in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}. This
1752      * extra can also be returned by the admin app when performing the admin-integrated
1753      * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity.
1754      */
1755     public static final String EXTRA_PROVISIONING_DISCLAIMERS =
1756             "android.app.extra.PROVISIONING_DISCLAIMERS";
1757 
1758     /**
1759      * A String extra of localized disclaimer header.
1760      *
1761      * <p>The extra is typically the company name of mobile device management application (MDM)
1762      * or the organization name.
1763      *
1764      * <p>{@link ApplicationInfo#FLAG_SYSTEM System apps} can also insert a disclaimer by declaring
1765      * an application-level meta-data in {@code AndroidManifest.xml}.
1766      *
1767      * <p>For example:
1768      * <pre>
1769      *  &lt;meta-data
1770      *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_HEADER"
1771      *      android:resource="@string/disclaimer_header"
1772      * /&gt;</pre>
1773      *
1774      * <p>This must be accompanied with another extra using the key
1775      * {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT}.
1776      */
1777     public static final String EXTRA_PROVISIONING_DISCLAIMER_HEADER =
1778             "android.app.extra.PROVISIONING_DISCLAIMER_HEADER";
1779 
1780     /**
1781      * A {@link Uri} extra pointing to disclaimer content.
1782      *
1783      * <h5>The following URI schemes are accepted:</h5>
1784      * <ul>
1785      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1786      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1787      * </ul>
1788      *
1789      * <p>Styled text is supported. This is parsed by {@link android.text.Html#fromHtml(String)}
1790      * and displayed in a {@link android.widget.TextView}.
1791      *
1792      * <p>If a <code>content:</code> URI is passed, the intent should also have the
1793      * flag {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1794      * {@link android.content.ClipData} of the intent.
1795      *
1796      * <p>{@link ApplicationInfo#FLAG_SYSTEM System apps} can also insert a
1797      * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
1798      *
1799      * <p>For example:
1800      *
1801      * <pre>
1802      *  &lt;meta-data
1803      *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_CONTENT"
1804      *      android:resource="@string/disclaimer_content"
1805      * /&gt;</pre>
1806      *
1807      * <p>This must be accompanied with another extra using the key
1808      * {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}.
1809      */
1810     public static final String EXTRA_PROVISIONING_DISCLAIMER_CONTENT =
1811             "android.app.extra.PROVISIONING_DISCLAIMER_CONTENT";
1812 
1813     /**
1814      * A boolean extra indicating if the user consent steps from the
1815      * <a href="#managed-provisioning">provisioning flow</a> should be skipped.
1816      *
1817      * <p>If unspecified, defaults to {@code false}.
1818      *
1819      * @deprecated this extra is no longer relevant as device owners cannot create managed profiles
1820      */
1821     @Deprecated
1822     public static final String EXTRA_PROVISIONING_SKIP_USER_CONSENT =
1823             "android.app.extra.PROVISIONING_SKIP_USER_CONSENT";
1824 
1825     /**
1826      * A boolean extra indicating if the education screens from the provisioning flow should be
1827      * skipped. If unspecified, defaults to {@code false}.
1828      *
1829      * <p>This extra can be set in the following ways:
1830      * <ul>
1831      * <li>By the admin app when performing the admin-integrated
1832      * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity</li>
1833      * <li>For managed account enrollment</li>
1834      * </ul>
1835      *
1836      * <p>If the education screens are skipped, it is the admin application's responsibility
1837      * to display its own user education screens.
1838      */
1839     public static final String EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS =
1840             "android.app.extra.PROVISIONING_SKIP_EDUCATION_SCREENS";
1841 
1842     /**
1843      * A boolean extra indicating if mobile data should be used during the provisioning flow
1844      * for downloading the admin app. If {@link #EXTRA_PROVISIONING_WIFI_SSID} is also specified,
1845      * wifi network will be used instead.
1846      *
1847      * <p>Default value is {@code false}.
1848      *
1849      * <p>If this extra is set to {@code true} and {@link #EXTRA_PROVISIONING_WIFI_SSID} is not
1850      * specified, this extra has different behaviour depending on the way provisioning is triggered:
1851      * <ul>
1852      * <li>
1853      *     For provisioning started via a QR code or an NFC tag, mobile data is always used for
1854      *     downloading the admin app.
1855      * </li>
1856      * <li>
1857      *     For all other provisioning methods, a mobile data connection check is made at the start
1858      *     of provisioning. If mobile data is connected at that point, the admin app download will
1859      *     happen using mobile data. If mobile data is not connected at that point, the end-user
1860      *     will be asked to pick a wifi network and the admin app download will proceed over wifi.
1861      * </li>
1862      * </ul>
1863      */
1864     public static final String EXTRA_PROVISIONING_USE_MOBILE_DATA =
1865             "android.app.extra.PROVISIONING_USE_MOBILE_DATA";
1866 
1867     /**
1868      * Possible values for {@link #EXTRA_PROVISIONING_TRIGGER}.
1869      *
1870      * @hide
1871      */
1872     @IntDef(prefix = { "PROVISIONING_TRIGGER_" }, value = {
1873             PROVISIONING_TRIGGER_UNSPECIFIED,
1874             PROVISIONING_TRIGGER_CLOUD_ENROLLMENT,
1875             PROVISIONING_TRIGGER_QR_CODE,
1876             PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER,
1877             PROVISIONING_TRIGGER_MANAGED_ACCOUNT,
1878             PROVISIONING_TRIGGER_NFC
1879     })
1880     @Retention(RetentionPolicy.SOURCE)
1881     public @interface ProvisioningTrigger {}
1882 
1883     /**
1884      * Flags for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES}.
1885      *
1886      * @hide
1887      */
1888     @IntDef(flag = true, prefix = { "FLAG_SUPPORTED_MODES_" }, value = {
1889             FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED,
1890             FLAG_SUPPORTED_MODES_PERSONALLY_OWNED,
1891             FLAG_SUPPORTED_MODES_DEVICE_OWNER
1892     })
1893     @Retention(RetentionPolicy.SOURCE)
1894     public @interface ProvisioningConfiguration {}
1895 
1896     /**
1897      * An int extra holding the provisioning trigger. It could be one of
1898      * {@link #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT}, {@link #PROVISIONING_TRIGGER_QR_CODE},
1899      * {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} or {@link
1900      * #PROVISIONING_TRIGGER_UNSPECIFIED}.
1901      *
1902      * <p>Use in an intent with action {@link
1903      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}.
1904      * @hide
1905      */
1906     @SystemApi
1907     public static final String EXTRA_PROVISIONING_TRIGGER =
1908             "android.app.extra.PROVISIONING_TRIGGER";
1909 
1910     /**
1911      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1912      * trigger has not been specified.
1913      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1914      * @see #PROVISIONING_TRIGGER_QR_CODE
1915      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1916      * @see #PROVISIONING_TRIGGER_NFC
1917      * @hide
1918      */
1919     @SystemApi
1920     public static final int PROVISIONING_TRIGGER_UNSPECIFIED = 0;
1921 
1922     /**
1923      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1924      * trigger is cloud enrollment.
1925      * @see #PROVISIONING_TRIGGER_QR_CODE
1926      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1927      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1928      * @see #PROVISIONING_TRIGGER_NFC
1929      * @hide
1930      */
1931     @SystemApi
1932     public static final int PROVISIONING_TRIGGER_CLOUD_ENROLLMENT = 1;
1933 
1934     /**
1935      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1936      * trigger is the QR code scanner.
1937      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1938      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1939      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1940      * @see #PROVISIONING_TRIGGER_NFC
1941      * @hide
1942      */
1943     @SystemApi
1944     public static final int PROVISIONING_TRIGGER_QR_CODE = 2;
1945 
1946     /**
1947      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1948      * trigger is persistent device owner enrollment.
1949      * <p>This constant is meant to represent a specific type of managed account provisioning which
1950      * provisions a device to a device owner by invoking the standard provisioning flow (where
1951      * the ManagedProvisioning component downloads and installs the admin app), as opposed to
1952      * relying on the provisioning trigger to handle download and install of the admin app.
1953      * <p>As of {@link android.os.Build.VERSION_CODES#S}, this constant is no longer used in favor
1954      * of the more general {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} which handles all managed
1955      * account provisioning types.
1956      * @deprecated Use the broader {@link #PROVISIONING_TRIGGER_MANAGED_ACCOUNT} instead
1957      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1958      * @see #PROVISIONING_TRIGGER_QR_CODE
1959      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1960      * @see #PROVISIONING_TRIGGER_NFC
1961      * @hide
1962      */
1963     @SystemApi
1964     @Deprecated
1965     public static final int PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER = 3;
1966 
1967     /**
1968      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1969      * trigger is managed account enrollment.
1970      * <p>
1971      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1972      * @see #PROVISIONING_TRIGGER_QR_CODE
1973      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1974      * @see #PROVISIONING_TRIGGER_NFC
1975      * @hide
1976      */
1977     @SystemApi
1978     public static final int PROVISIONING_TRIGGER_MANAGED_ACCOUNT = 4;
1979 
1980     /**
1981      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning is
1982      * triggered by tapping an NFC tag.
1983      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1984      * @see #PROVISIONING_TRIGGER_QR_CODE
1985      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1986      * @see #PROVISIONING_TRIGGER_MANAGED_ACCOUNT
1987      * @hide
1988      */
1989     @SystemApi
1990     public static final int PROVISIONING_TRIGGER_NFC = 5;
1991 
1992     /**
1993      * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that provisioning is
1994      * organization-owned.
1995      *
1996      * <p>Using this value indicates the admin app can only be provisioned in either a
1997      * fully-managed device or a corporate-owned work profile. This will cause the admin app's
1998      * {@link #ACTION_GET_PROVISIONING_MODE} activity to have the {@link
1999      * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
2000      * #PROVISIONING_MODE_MANAGED_PROFILE} and {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}.
2001      *
2002      * <p>This flag can be combined with {@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}. In
2003      * that case, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity will have
2004      * the {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
2005      * #PROVISIONING_MODE_MANAGED_PROFILE}, {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE} and
2006      * {@link #PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE}.
2007      *
2008      * @hide
2009      */
2010     @SystemApi
2011     public static final int FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED = 1;
2012 
2013     /**
2014      * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that provisioning
2015      * is personally-owned.
2016      *
2017      * <p>Using this flag will cause the admin app's {@link #ACTION_GET_PROVISIONING_MODE}
2018      * activity to have the {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra
2019      * contain only {@link #PROVISIONING_MODE_MANAGED_PROFILE}.
2020      *
2021      * <p>Also, if this flag is set, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity
2022      * will not receive the {@link #EXTRA_PROVISIONING_IMEI} and {@link
2023      * #EXTRA_PROVISIONING_SERIAL_NUMBER} extras.
2024      *
2025      * <p>This flag can be combined with {@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}. In
2026      * that case, the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity will have the
2027      * {@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array extra contain {@link
2028      * #PROVISIONING_MODE_MANAGED_PROFILE}, {@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE} and
2029      * {@link #PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE}.
2030      *
2031      * @hide
2032      */
2033     @SystemApi
2034     public static final int FLAG_SUPPORTED_MODES_PERSONALLY_OWNED = 1 << 1;
2035 
2036     /**
2037      * Flag for {@link #EXTRA_PROVISIONING_SUPPORTED_MODES} indicating that the only
2038      * supported provisioning mode is device owner.
2039      *
2040      * @hide
2041      */
2042     @SystemApi
2043     public static final int FLAG_SUPPORTED_MODES_DEVICE_OWNER = 1 << 2;
2044 
2045     /**
2046      * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and
2047      * {@link #setMinimumRequiredWifiSecurityLevel(int)}: no minimum security level.
2048      *
2049      * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant
2050      * represents the current minimum security level required.
2051      * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the
2052      * minimum security level a Wi-Fi network must meet.
2053      *
2054      * @see #WIFI_SECURITY_PERSONAL
2055      * @see #WIFI_SECURITY_ENTERPRISE_EAP
2056      * @see #WIFI_SECURITY_ENTERPRISE_192
2057      */
2058     public static final int WIFI_SECURITY_OPEN = 0;
2059 
2060     /**
2061      * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and
2062      * {@link #setMinimumRequiredWifiSecurityLevel(int)}: personal network such as WEP, WPA2-PSK.
2063      *
2064      * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant
2065      * represents the current minimum security level required.
2066      * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the
2067      * minimum security level a Wi-Fi network must meet.
2068      *
2069      * @see #WIFI_SECURITY_OPEN
2070      * @see #WIFI_SECURITY_ENTERPRISE_EAP
2071      * @see #WIFI_SECURITY_ENTERPRISE_192
2072      */
2073     public static final int WIFI_SECURITY_PERSONAL = 1;
2074 
2075     /**
2076      * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and
2077      * {@link #setMinimumRequiredWifiSecurityLevel(int)}: enterprise EAP network.
2078      *
2079      * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant
2080      * represents the current minimum security level required.
2081      * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the
2082      * minimum security level a Wi-Fi network must meet.
2083      *
2084      * @see #WIFI_SECURITY_OPEN
2085      * @see #WIFI_SECURITY_PERSONAL
2086      * @see #WIFI_SECURITY_ENTERPRISE_192
2087      */
2088     public static final int WIFI_SECURITY_ENTERPRISE_EAP = 2;
2089 
2090     /**
2091      * Constant for {@link #getMinimumRequiredWifiSecurityLevel()} and
2092      * {@link #setMinimumRequiredWifiSecurityLevel(int)}: enterprise 192 bit network.
2093      *
2094      * <p> When returned from {@link #getMinimumRequiredWifiSecurityLevel()}, the constant
2095      * represents the current minimum security level required.
2096      * When passed to {@link #setMinimumRequiredWifiSecurityLevel(int)}, it sets the
2097      * minimum security level a Wi-Fi network must meet.
2098      *
2099      * @see #WIFI_SECURITY_OPEN
2100      * @see #WIFI_SECURITY_PERSONAL
2101      * @see #WIFI_SECURITY_ENTERPRISE_EAP
2102      */
2103     public static final int WIFI_SECURITY_ENTERPRISE_192 = 3;
2104 
2105     /**
2106      * Possible Wi-Fi minimum security levels
2107      *
2108      * @hide */
2109     @Retention(RetentionPolicy.SOURCE)
2110     @IntDef(prefix = {"WIFI_SECURITY_"}, value = {
2111             WIFI_SECURITY_OPEN,
2112             WIFI_SECURITY_PERSONAL,
2113             WIFI_SECURITY_ENTERPRISE_EAP,
2114             WIFI_SECURITY_ENTERPRISE_192})
2115     public @interface WifiSecurity {}
2116 
2117     /**
2118      * This MIME type is used for starting the device owner provisioning.
2119      *
2120      * <p>During device owner provisioning a device admin app is set as the owner of the device.
2121      * A device owner has full control over the device. The device owner can not be modified by the
2122      * user and the only way of resetting the device is if the device owner app calls a factory
2123      * reset.
2124      *
2125      * <p> A typical use case would be a device that is owned by a company, but used by either an
2126      * employee or client.
2127      *
2128      * <p> The NFC message must be sent to an unprovisioned device.
2129      *
2130      * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
2131      * contains the following properties:
2132      * <ul>
2133      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
2134      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
2135      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
2136      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
2137      * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
2138      * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
2139      * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
2140      * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
2141      * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
2142      * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
2143      * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
2144      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
2145      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
2146      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
2147      * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
2148      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional, supported from {@link
2149      * android.os.Build.VERSION_CODES#M} </li>
2150      * <li>{@link #EXTRA_PROVISIONING_WIFI_EAP_METHOD}, optional, supported from {@link
2151      * android.os.Build.VERSION_CODES#Q}</li>
2152      * <li>{@link #EXTRA_PROVISIONING_WIFI_PHASE2_AUTH}, optional, supported from {@link
2153      * android.os.Build.VERSION_CODES#Q}</li>
2154      * <li>{@link #EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE}, optional, supported from {@link
2155      * android.os.Build.VERSION_CODES#Q}</li>
2156      * <li>{@link #EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE}, optional, supported from {@link
2157      * android.os.Build.VERSION_CODES#Q}</li>
2158      * <li>{@link #EXTRA_PROVISIONING_WIFI_IDENTITY}, optional, supported from {@link
2159      * android.os.Build.VERSION_CODES#Q}</li>
2160      * <li>{@link #EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY}, optional, supported from {@link
2161      * android.os.Build.VERSION_CODES#Q}</li>
2162      * <li>{@link #EXTRA_PROVISIONING_WIFI_DOMAIN}, optional, supported from {@link
2163      * android.os.Build.VERSION_CODES#Q}</li></ul>
2164      *
2165      * <p>
2166      * As of {@link android.os.Build.VERSION_CODES#M}, the properties should contain
2167      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of
2168      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only
2169      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported).
2170      */
2171     public static final String MIME_TYPE_PROVISIONING_NFC
2172         = "application/com.android.managedprovisioning";
2173 
2174     /**
2175      * Activity action: ask the user to add a new device administrator to the system.
2176      * The desired policy is the ComponentName of the policy in the
2177      * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
2178      * bring the user through adding the device administrator to the system (or
2179      * allowing them to reject it).
2180      *
2181      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
2182      * field to provide the user with additional explanation (in addition
2183      * to your component's description) about what is being added.
2184      *
2185      * <p>If your administrator is already active, this will ordinarily return immediately (without
2186      * user intervention).  However, if your administrator has been updated and is requesting
2187      * additional uses-policy flags, the user will be presented with the new list.  New policies
2188      * will not be available to the updated administrator until the user has accepted the new list.
2189      */
2190     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
2191     public static final String ACTION_ADD_DEVICE_ADMIN
2192             = "android.app.action.ADD_DEVICE_ADMIN";
2193 
2194     /**
2195      * @hide
2196      * Activity action: ask the user to add a new device administrator as the profile owner
2197      * for this user. Only system apps can launch this intent.
2198      *
2199      * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN}
2200      * extra field. This will invoke a UI to bring the user through adding the profile owner admin
2201      * to remotely control restrictions on the user.
2202      *
2203      * <p>The intent must be invoked via {@link Activity#startActivityForResult} to receive the
2204      * result of whether or not the user approved the action. If approved, the result will
2205      * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well
2206      * as a profile owner.
2207      *
2208      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
2209      * field to provide the user with additional explanation (in addition
2210      * to your component's description) about what is being added.
2211      *
2212      * <p>If there is already a profile owner active or the caller is not a system app, the
2213      * operation will return a failure result.
2214      */
2215     @SystemApi
2216     public static final String ACTION_SET_PROFILE_OWNER
2217             = "android.app.action.SET_PROFILE_OWNER";
2218 
2219     /**
2220      * @hide
2221      * Name of the profile owner admin that controls the user.
2222      */
2223     @SystemApi
2224     public static final String EXTRA_PROFILE_OWNER_NAME
2225             = "android.app.extra.PROFILE_OWNER_NAME";
2226 
2227     /**
2228      * Broadcast action: send when any policy admin changes a policy.
2229      * This is generally used to find out when a new policy is in effect.
2230      *
2231      * If the profile owner of an organization-owned managed profile changes some user
2232      * restriction explicitly on the parent user, this broadcast will <em>not</em> be
2233      * sent to the parent user.
2234      * @hide
2235      */
2236     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2237     public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
2238             = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
2239 
2240     /**
2241      * Broadcast action: sent when the device owner is set, changed or cleared.
2242      *
2243      * This broadcast is sent only to the primary user.
2244      * @see #ACTION_PROVISION_MANAGED_DEVICE
2245      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
2246      */
2247     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2248     public static final String ACTION_DEVICE_OWNER_CHANGED
2249             = "android.app.action.DEVICE_OWNER_CHANGED";
2250 
2251     /**
2252      * Broadcast action: sent when the factory reset protection (FRP) policy is changed.
2253      *
2254      * @see #setFactoryResetProtectionPolicy
2255      * @hide
2256      */
2257     @RequiresPermission(android.Manifest.permission.MANAGE_FACTORY_RESET_PROTECTION)
2258     @SystemApi
2259     public static final String ACTION_RESET_PROTECTION_POLICY_CHANGED =
2260             "android.app.action.RESET_PROTECTION_POLICY_CHANGED";
2261 
2262     /**
2263      * Broadcast action: sent when there is a location update on a device in lost mode. This
2264      * broadcast is explicitly sent to the device policy controller app only.
2265      *
2266      * @see DevicePolicyManager#sendLostModeLocationUpdate
2267      * @hide
2268      */
2269     @SystemApi
2270     public static final String ACTION_LOST_MODE_LOCATION_UPDATE =
2271             "android.app.action.LOST_MODE_LOCATION_UPDATE";
2272 
2273     /**
2274      * Extra used with {@link #ACTION_LOST_MODE_LOCATION_UPDATE} to send the location of a device
2275      * in lost mode. Value is {@code Location}.
2276      *
2277      * @see DevicePolicyManager#sendLostModeLocationUpdate
2278      * @hide
2279      */
2280     @SystemApi
2281     public static final String EXTRA_LOST_MODE_LOCATION =
2282             "android.app.extra.LOST_MODE_LOCATION";
2283 
2284     /**
2285      * The ComponentName of the administrator component.
2286      *
2287      * @see #ACTION_ADD_DEVICE_ADMIN
2288      */
2289     public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
2290 
2291     /**
2292      * An optional CharSequence providing additional explanation for why the
2293      * admin is being added.
2294      *
2295      * @see #ACTION_ADD_DEVICE_ADMIN
2296      */
2297     public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
2298 
2299     /**
2300      * Constant to indicate the feature of disabling the camera. Used as argument to
2301      * {@link #createAdminSupportIntent(String)}.
2302      * @see #setCameraDisabled(ComponentName, boolean)
2303      */
2304     public static final String POLICY_DISABLE_CAMERA = "policy_disable_camera";
2305 
2306     /**
2307      * Constant to indicate the feature of disabling screen captures. Used as argument to
2308      * {@link #createAdminSupportIntent(String)}.
2309      * @see #setScreenCaptureDisabled(ComponentName, boolean)
2310      */
2311     public static final String POLICY_DISABLE_SCREEN_CAPTURE = "policy_disable_screen_capture";
2312 
2313     /**
2314      * Constant to indicate the feature of suspending app. Use it as the value of
2315      * {@link #EXTRA_RESTRICTION}.
2316      * @hide
2317      */
2318     public static final String POLICY_SUSPEND_PACKAGES = "policy_suspend_packages";
2319 
2320     /**
2321      * A String indicating a specific restricted feature. Can be a user restriction from the
2322      * {@link UserManager}, e.g. {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the values
2323      * {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
2324      * @see #createAdminSupportIntent(String)
2325      * @hide
2326      */
2327     @SystemApi
2328     public static final String EXTRA_RESTRICTION = "android.app.extra.RESTRICTION";
2329 
2330     /**
2331      * Activity action: have the user enter a new password.
2332      *
2333      * <p>For admin apps, this activity should be launched after using {@link
2334      * #setPasswordQuality(ComponentName, int)}, or {@link
2335      * #setPasswordMinimumLength(ComponentName, int)} to have the user enter a new password that
2336      * meets the current requirements. You can use {@link #isActivePasswordSufficient()} to
2337      * determine whether you need to have the user select a new password in order to meet the
2338      * current constraints. Upon being resumed from this activity, you can check the new
2339      * password characteristics to see if they are sufficient.
2340      *
2341      * <p>Non-admin apps can use {@link #getPasswordComplexity()} to check the current screen lock
2342      * complexity, and use this activity with extra {@link #EXTRA_PASSWORD_COMPLEXITY} to suggest
2343      * to users how complex the app wants the new screen lock to be. Note that both {@link
2344      * #getPasswordComplexity()} and the extra {@link #EXTRA_PASSWORD_COMPLEXITY} require the
2345      * calling app to have the permission {@link permission#REQUEST_PASSWORD_COMPLEXITY}.
2346      *
2347      * <p>If the intent is launched from within a managed profile with a profile
2348      * owner built against {@link android.os.Build.VERSION_CODES#M} or before,
2349      * this will trigger entering a new password for the parent of the profile.
2350      * For all other cases it will trigger entering a new password for the user
2351      * or profile it is launched from.
2352      *
2353      * @see #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
2354      */
2355     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
2356     public static final String ACTION_SET_NEW_PASSWORD
2357             = "android.app.action.SET_NEW_PASSWORD";
2358 
2359     /**
2360      * An integer indicating the complexity level of the new password an app would like the user to
2361      * set when launching the action {@link #ACTION_SET_NEW_PASSWORD}.
2362      *
2363      * <p>Must be one of
2364      * <ul>
2365      *     <li>{@link #PASSWORD_COMPLEXITY_HIGH}
2366      *     <li>{@link #PASSWORD_COMPLEXITY_MEDIUM}
2367      *     <li>{@link #PASSWORD_COMPLEXITY_LOW}
2368      *     <li>{@link #PASSWORD_COMPLEXITY_NONE}
2369      * </ul>
2370      *
2371      * <p>If an invalid value is used, it will be treated as {@link #PASSWORD_COMPLEXITY_NONE}.
2372      */
2373     @RequiresPermission(REQUEST_PASSWORD_COMPLEXITY)
2374     public static final String EXTRA_PASSWORD_COMPLEXITY =
2375             "android.app.extra.PASSWORD_COMPLEXITY";
2376 
2377     /**
2378      * Constant for {@link #getPasswordComplexity()} and
2379      * {@link #setRequiredPasswordComplexity(int)}: no password.
2380      *
2381      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
2382      * the exact complexity band the password is in.
2383      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
2384      * band which the password must meet.
2385      */
2386     public static final int PASSWORD_COMPLEXITY_NONE = 0;
2387 
2388     /**
2389      * Constant for {@link #getPasswordComplexity()} and
2390      * {@link #setRequiredPasswordComplexity(int)}.
2391      * Define the low password complexity band as:
2392      * <ul>
2393      * <li>pattern
2394      * <li>PIN with repeating (4444) or ordered (1234, 4321, 2468) sequences
2395      * </ul>
2396      *
2397      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
2398      * the exact complexity band the password is in.
2399      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
2400      * band which the password must meet.
2401      *
2402      * @see #PASSWORD_QUALITY_SOMETHING
2403      * @see #PASSWORD_QUALITY_NUMERIC
2404      */
2405     public static final int PASSWORD_COMPLEXITY_LOW = 0x10000;
2406 
2407     /**
2408      * Constant for {@link #getPasswordComplexity()} and
2409      * {@link #setRequiredPasswordComplexity(int)}.
2410      * Define the medium password complexity band as:
2411      * <ul>
2412      * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
2413      * least 4
2414      * <li>alphabetic, length at least 4
2415      * <li>alphanumeric, length at least 4
2416      * </ul>
2417      *
2418      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
2419      * the exact complexity band the password is in.
2420      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
2421      * band which the password must meet.
2422      *
2423      * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX
2424      * @see #PASSWORD_QUALITY_ALPHABETIC
2425      * @see #PASSWORD_QUALITY_ALPHANUMERIC
2426      */
2427     public static final int PASSWORD_COMPLEXITY_MEDIUM = 0x30000;
2428 
2429     /**
2430      * Constant for {@link #getPasswordComplexity()} and
2431      * {@link #setRequiredPasswordComplexity(int)}.
2432      * Define the high password complexity band as:
2433      * <ul>
2434      * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
2435      * least 8
2436      * <li>alphabetic, length at least 6
2437      * <li>alphanumeric, length at least 6
2438      * </ul>
2439      *
2440      * <p> When returned from {@link #getPasswordComplexity()}, the constant represents
2441      * the exact complexity band the password is in.
2442      * When passed to {@link #setRequiredPasswordComplexity(int), it sets the minimum complexity
2443      * band which the password must meet.
2444      *
2445      * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX
2446      * @see #PASSWORD_QUALITY_ALPHABETIC
2447      * @see #PASSWORD_QUALITY_ALPHANUMERIC
2448      */
2449     public static final int PASSWORD_COMPLEXITY_HIGH = 0x50000;
2450 
2451     /**
2452      * A boolean extra for {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} requesting that only
2453      * device password requirement is enforced during the parent profile password enrolment flow.
2454      * <p> Normally when enrolling password for the parent profile, both the device-wide password
2455      * requirement (requirement set via {@link #getParentProfileInstance(ComponentName)} instance)
2456      * and the profile password requirement are enforced, if the profile currently does not have a
2457      * separate work challenge. By setting this to {@code true}, profile password requirement is
2458      * explicitly disregarded.
2459      *
2460      * @see #isActivePasswordSufficientForDeviceRequirement()
2461      */
2462     public static final String EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY =
2463             "android.app.extra.DEVICE_PASSWORD_REQUIREMENT_ONLY";
2464 
2465     /**
2466      * @hide
2467      */
2468     @Retention(RetentionPolicy.SOURCE)
2469     @IntDef(prefix = {"PASSWORD_COMPLEXITY_"}, value = {
2470             PASSWORD_COMPLEXITY_NONE,
2471             PASSWORD_COMPLEXITY_LOW,
2472             PASSWORD_COMPLEXITY_MEDIUM,
2473             PASSWORD_COMPLEXITY_HIGH,
2474     })
2475     public @interface PasswordComplexity {}
2476 
2477     /**
2478      * Indicates that nearby streaming is not controlled by policy, which means nearby streaming is
2479      * allowed.
2480      */
2481     public static final int NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY = 0;
2482 
2483     /** Indicates that nearby streaming is disabled. */
2484     public static final int NEARBY_STREAMING_DISABLED = 1;
2485 
2486     /** Indicates that nearby streaming is enabled. */
2487     public static final int NEARBY_STREAMING_ENABLED = 2;
2488 
2489     /**
2490      * Indicates that nearby streaming is enabled only to devices offering a comparable level of
2491      * security, with the same authenticated managed account.
2492      */
2493     public static final int NEARBY_STREAMING_SAME_MANAGED_ACCOUNT_ONLY = 3;
2494 
2495     /**
2496      * @hide
2497      */
2498     @Retention(RetentionPolicy.SOURCE)
2499     @IntDef(prefix = {"NEARBY_STREAMING_"}, value = {
2500         NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY,
2501         NEARBY_STREAMING_DISABLED,
2502         NEARBY_STREAMING_ENABLED,
2503         NEARBY_STREAMING_SAME_MANAGED_ACCOUNT_ONLY,
2504     })
2505     public @interface NearbyStreamingPolicy {}
2506 
2507     /**
2508      * Activity action: have the user enter a new password for the parent profile.
2509      * If the intent is launched from within a managed profile, this will trigger
2510      * entering a new password for the parent of the profile. The caller can optionally
2511      * set {@link #EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY} to only enforce device-wide
2512      * password requirement. In all other cases the behaviour is identical to
2513      * {@link #ACTION_SET_NEW_PASSWORD}.
2514      */
2515     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
2516     public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
2517             = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD";
2518 
2519     /**
2520      * Broadcast action: Tell the status bar to open the device monitoring dialog, e.g. when
2521      * Network logging was enabled and the user tapped the notification.
2522      * <p class="note">This is a protected intent that can only be sent by the system.</p>
2523      * @hide
2524      */
2525     public static final String ACTION_SHOW_DEVICE_MONITORING_DIALOG
2526             = "android.app.action.SHOW_DEVICE_MONITORING_DIALOG";
2527 
2528     /**
2529      * Broadcast Action: Sent after application delegation scopes are changed. The new delegation
2530      * scopes will be sent in an {@code ArrayList<String>} extra identified by the
2531      * {@link #EXTRA_DELEGATION_SCOPES} key.
2532      *
2533      * <p class="note"><b>Note:</b> This is a protected intent that can only be sent by the
2534      * system.</p>
2535      */
2536     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2537     public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED =
2538             "android.app.action.APPLICATION_DELEGATION_SCOPES_CHANGED";
2539 
2540     /**
2541      * An {@code ArrayList<String>} corresponding to the delegation scopes given to an app in the
2542      * {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} broadcast.
2543      */
2544     public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES";
2545 
2546     /**
2547      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
2548      * the parent profile to access intents sent from the managed profile.
2549      * That is, when an app in the managed profile calls
2550      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
2551      * matching activity in the parent profile.
2552      */
2553     public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
2554 
2555     /**
2556      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
2557      * the managed profile to access intents sent from the parent profile.
2558      * That is, when an app in the parent profile calls
2559      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
2560      * matching activity in the managed profile.
2561      */
2562     public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
2563 
2564     /**
2565      * Broadcast action: notify that a new local system update policy has been set by the device
2566      * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
2567      */
2568     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2569     public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
2570             = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
2571 
2572     /**
2573      * Broadcast action from ManagedProvisioning to notify that the latest change to
2574      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has been successfully
2575      * applied (cross profile intent filters updated). Only usesd for CTS tests.
2576      * @hide
2577      */
2578     @SuppressLint("ActionValue")
2579     @TestApi
2580     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2581     public static final String ACTION_DATA_SHARING_RESTRICTION_APPLIED =
2582             "android.app.action.DATA_SHARING_RESTRICTION_APPLIED";
2583 
2584     /**
2585      * Broadcast action: notify that a value of {@link Settings.Global#DEVICE_POLICY_CONSTANTS}
2586      * has been changed.
2587      * @hide
2588      */
2589     @SuppressLint("ActionValue")
2590     @TestApi
2591     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2592     public static final String ACTION_DEVICE_POLICY_CONSTANTS_CHANGED =
2593             "android.app.action.DEVICE_POLICY_CONSTANTS_CHANGED";
2594 
2595     /**
2596      * Permission policy to prompt user for new permission requests for runtime permissions.
2597      * Already granted or denied permissions are not affected by this.
2598      */
2599     public static final int PERMISSION_POLICY_PROMPT = 0;
2600 
2601     /**
2602      * Permission policy to always grant new permission requests for runtime permissions.
2603      * Already granted or denied permissions are not affected by this.
2604      */
2605     public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
2606 
2607     /**
2608      * Permission policy to always deny new permission requests for runtime permissions.
2609      * Already granted or denied permissions are not affected by this.
2610      */
2611     public static final int PERMISSION_POLICY_AUTO_DENY = 2;
2612 
2613     /**
2614      * Possible policy values for permissions.
2615      *
2616      * @hide
2617      */
2618     @IntDef(prefix = { "PERMISSION_GRANT_STATE_" }, value = {
2619             PERMISSION_GRANT_STATE_DEFAULT,
2620             PERMISSION_GRANT_STATE_GRANTED,
2621             PERMISSION_GRANT_STATE_DENIED
2622     })
2623     @Retention(RetentionPolicy.SOURCE)
2624     public @interface PermissionGrantState {}
2625 
2626     /**
2627      * Runtime permission state: The user can manage the permission
2628      * through the UI.
2629      */
2630     public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
2631 
2632     /**
2633      * Runtime permission state: The permission is granted to the app
2634      * and the user cannot manage the permission through the UI.
2635      */
2636     public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
2637 
2638     /**
2639      * Runtime permission state: The permission is denied to the app
2640      * and the user cannot manage the permission through the UI.
2641      */
2642     public static final int PERMISSION_GRANT_STATE_DENIED = 2;
2643 
2644     /**
2645      * Delegation of certificate installation and management. This scope grants access to the
2646      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
2647      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair} APIs.
2648      * This scope also grants the ability to read identifiers that the delegating device owner or
2649      * profile owner can obtain. See {@link #getEnrollmentSpecificId()}.
2650      */
2651     public static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
2652 
2653     /**
2654      * Delegation of application restrictions management. This scope grants access to the
2655      * {@link #setApplicationRestrictions} and {@link #getApplicationRestrictions} APIs.
2656      */
2657     public static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions";
2658 
2659     /**
2660      * Delegation of application uninstall block. This scope grants access to the
2661      * {@link #setUninstallBlocked} API.
2662      */
2663     public static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall";
2664 
2665     /**
2666      * Delegation of permission policy and permission grant state. This scope grants access to the
2667      * {@link #setPermissionPolicy}, {@link #getPermissionGrantState},
2668      * and {@link #setPermissionGrantState} APIs.
2669      */
2670     public static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant";
2671 
2672     /**
2673      * Delegation of package access state. This scope grants access to the
2674      * {@link #isApplicationHidden}, {@link #setApplicationHidden}, {@link #isPackageSuspended}, and
2675      * {@link #setPackagesSuspended} APIs.
2676      */
2677     public static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
2678 
2679     /**
2680      * Delegation for enabling system apps. This scope grants access to the {@link #enableSystemApp}
2681      * API.
2682      */
2683     public static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app";
2684 
2685     /**
2686      * Delegation for installing existing packages. This scope grants access to the
2687      * {@link #installExistingPackage} API.
2688      */
2689     public static final String DELEGATION_INSTALL_EXISTING_PACKAGE =
2690             "delegation-install-existing-package";
2691 
2692     /**
2693      * Delegation of management of uninstalled packages. This scope grants access to the
2694      * {@link #setKeepUninstalledPackages} and {@link #getKeepUninstalledPackages} APIs.
2695      */
2696     public static final String DELEGATION_KEEP_UNINSTALLED_PACKAGES =
2697             "delegation-keep-uninstalled-packages";
2698 
2699     /**
2700      * Grants access to {@link #setNetworkLoggingEnabled}, {@link #isNetworkLoggingEnabled} and
2701      * {@link #retrieveNetworkLogs}. Once granted the delegated app will start receiving
2702      * DelegatedAdminReceiver.onNetworkLogsAvailable() callback, and Device owner or Profile Owner
2703      * will no longer receive the DeviceAdminReceiver.onNetworkLogsAvailable() callback.
2704      * There can be at most one app that has this delegation.
2705      * If another app already had delegated network logging access,
2706      * it will lose the delegation when a new app is delegated.
2707      *
2708      * <p> Device Owner can grant this access since Android 10. Profile Owner of a managed profile
2709      * can grant this access since Android 12.
2710      */
2711     public static final String DELEGATION_NETWORK_LOGGING = "delegation-network-logging";
2712 
2713     /**
2714      * Grants access to selection of KeyChain certificates on behalf of requesting apps.
2715      * Once granted the app will start receiving
2716      * {@link DelegatedAdminReceiver#onChoosePrivateKeyAlias}. The caller (PO/DO) will
2717      * no longer receive {@link DeviceAdminReceiver#onChoosePrivateKeyAlias}.
2718      * There can be at most one app that has this delegation.
2719      * If another app already had delegated certificate selection access,
2720      * it will lose the delegation when a new app is delegated.
2721      * <p> The delegated app can also call {@link #grantKeyPairToApp} and
2722      * {@link #revokeKeyPairFromApp} to directly grant KeyChain keys to other apps.
2723      * <p> Can be granted by Device Owner or Profile Owner.
2724      */
2725     public static final String DELEGATION_CERT_SELECTION = "delegation-cert-selection";
2726 
2727     /**
2728      * Grants access to {@link #setSecurityLoggingEnabled}, {@link #isSecurityLoggingEnabled},
2729      * {@link #retrieveSecurityLogs}, and {@link #retrievePreRebootSecurityLogs}. Once granted the
2730      * delegated app will start receiving {@link DelegatedAdminReceiver#onSecurityLogsAvailable}
2731      * callback, and Device owner or Profile Owner will no longer receive the
2732      * {@link DeviceAdminReceiver#onSecurityLogsAvailable} callback. There can be at most one app
2733      * that has this delegation. If another app already had delegated security logging access, it
2734      * will lose the delegation when a new app is delegated.
2735      *
2736      * <p> Can only be granted by Device Owner or Profile Owner of an organization-owned
2737      * managed profile.
2738      */
2739     public static final String DELEGATION_SECURITY_LOGGING = "delegation-security-logging";
2740 
2741     /**
2742      * No management for current user in-effect. This is the default.
2743      * @hide
2744      */
2745     @SystemApi
2746     public static final int STATE_USER_UNMANAGED = 0;
2747 
2748     /**
2749      * Management partially setup, user setup needs to be completed.
2750      * @hide
2751      */
2752     @SystemApi
2753     public static final int STATE_USER_SETUP_INCOMPLETE = 1;
2754 
2755     /**
2756      * Management partially setup, user setup completed.
2757      * @hide
2758      */
2759     @SystemApi
2760     public static final int STATE_USER_SETUP_COMPLETE = 2;
2761 
2762     /**
2763      * Management setup and active on current user.
2764      * @hide
2765      */
2766     @SystemApi
2767     public static final int STATE_USER_SETUP_FINALIZED = 3;
2768 
2769     /**
2770      * Management partially setup on a managed profile.
2771      * @hide
2772      */
2773     @SystemApi
2774     public static final int STATE_USER_PROFILE_COMPLETE = 4;
2775 
2776     /**
2777      * Management setup on a managed profile.
2778      * <p>This is used as an intermediate state after {@link #STATE_USER_PROFILE_COMPLETE} once the
2779      * work profile has been created.
2780      * @hide
2781      */
2782     @SystemApi
2783     public static final int STATE_USER_PROFILE_FINALIZED = 5;
2784 
2785     /**
2786      * @hide
2787      */
2788     @IntDef(prefix = { "STATE_USER_" }, value = {
2789             STATE_USER_UNMANAGED,
2790             STATE_USER_SETUP_INCOMPLETE,
2791             STATE_USER_SETUP_COMPLETE,
2792             STATE_USER_SETUP_FINALIZED,
2793             STATE_USER_PROFILE_COMPLETE,
2794             STATE_USER_PROFILE_FINALIZED
2795     })
2796     @Retention(RetentionPolicy.SOURCE)
2797     public @interface UserProvisioningState {}
2798 
2799     /**
2800      * Result code for {@link #checkProvisioningPrecondition}.
2801      *
2802      * <p>Unknown error code returned  for {@link #ACTION_PROVISION_MANAGED_DEVICE},
2803      * {@link #ACTION_PROVISION_MANAGED_PROFILE} and {@link #ACTION_PROVISION_MANAGED_USER}.
2804      *
2805      * @hide
2806      */
2807     @SystemApi
2808     public static final int STATUS_UNKNOWN_ERROR = -1;
2809 
2810     /**
2811      * Result code for {@link #checkProvisioningPrecondition}.
2812      *
2813      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
2814      * {@link #ACTION_PROVISION_MANAGED_PROFILE} and {@link #ACTION_PROVISION_MANAGED_USER}
2815      * when provisioning is allowed.
2816      *
2817      * @hide
2818      */
2819     @SystemApi
2820     public static final int STATUS_OK = 0;
2821 
2822     /**
2823      * Result code for {@link #checkProvisioningPrecondition}.
2824      *
2825      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the device already has a
2826      * device owner.
2827      *
2828      * @hide
2829      */
2830     @SystemApi
2831     public static final int STATUS_HAS_DEVICE_OWNER = 1;
2832 
2833     /**
2834      * Result code for {@link #checkProvisioningPrecondition}.
2835      *
2836      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the user has a profile owner
2837      *  and for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the profile owner is already set.
2838      *
2839      * @hide
2840      */
2841     @SystemApi
2842     public static final int STATUS_USER_HAS_PROFILE_OWNER = 2;
2843 
2844     /**
2845      * Result code for {@link #checkProvisioningPrecondition}.
2846      *
2847      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when the user isn't running.
2848      *
2849      * @hide
2850      */
2851     @SystemApi
2852     public static final int STATUS_USER_NOT_RUNNING = 3;
2853 
2854     /**
2855      * Result code for {@link #checkProvisioningPrecondition}.
2856      *
2857      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} if the device has already been
2858      * setup and for {@link #ACTION_PROVISION_MANAGED_USER} if the user has already been setup.
2859      *
2860      * @hide
2861      */
2862     @SystemApi
2863     public static final int STATUS_USER_SETUP_COMPLETED = 4;
2864 
2865     /**
2866      * Code used to indicate that the device also has a user other than the system user.
2867      *
2868      * @hide
2869      */
2870     @SystemApi
2871     public static final int STATUS_NONSYSTEM_USER_EXISTS = 5;
2872 
2873     /**
2874      * Code used to indicate that device has an account that prevents provisioning.
2875      *
2876      * @hide
2877      */
2878     @SystemApi
2879     public static final int STATUS_ACCOUNTS_NOT_EMPTY = 6;
2880 
2881     /**
2882      * Result code for {@link #checkProvisioningPrecondition}.
2883      *
2884      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} if the user is not a system user.
2885      *
2886      * @hide
2887      */
2888     @SystemApi
2889     public static final int STATUS_NOT_SYSTEM_USER = 7;
2890 
2891     /**
2892      * Result code for {@link #checkProvisioningPrecondition}.
2893      *
2894      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
2895      * {@link #ACTION_PROVISION_MANAGED_USER} when the device is a watch and is already paired.
2896      *
2897      * @hide
2898      */
2899     @SystemApi
2900     public static final int STATUS_HAS_PAIRED = 8;
2901 
2902     /**
2903      * Result code for {@link #checkProvisioningPrecondition}.
2904      *
2905      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} and
2906      * {@link #ACTION_PROVISION_MANAGED_USER} on devices which do not support managed users.
2907      *
2908      * @see {@link PackageManager#FEATURE_MANAGED_USERS}
2909      * @hide
2910      */
2911     @SystemApi
2912     public static final int STATUS_MANAGED_USERS_NOT_SUPPORTED = 9;
2913 
2914     /**
2915      * Result code for {@link #checkProvisioningPrecondition}.
2916      *
2917      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} if the user is a system user and
2918      * for {@link #ACTION_PROVISION_MANAGED_DEVICE} on devices running headless system user mode
2919      * and the user is a system user.
2920      *
2921      * @hide
2922      */
2923     @SystemApi
2924     public static final int STATUS_SYSTEM_USER = 10;
2925 
2926     /**
2927      * Result code for {@link #checkProvisioningPrecondition}.
2928      *
2929      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the user cannot have more
2930      * managed profiles.
2931      *
2932      * @hide
2933      */
2934     @SystemApi
2935     public static final int STATUS_CANNOT_ADD_MANAGED_PROFILE = 11;
2936 
2937     /**
2938      * Result code for {@link #checkProvisioningPrecondition}.
2939      *
2940      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
2941      * {@link #ACTION_PROVISION_MANAGED_PROFILE} on devices which do not support device
2942      * admins.
2943      *
2944      * @hide
2945      */
2946     @SystemApi
2947     public static final int STATUS_DEVICE_ADMIN_NOT_SUPPORTED = 13;
2948 
2949     /**
2950      * TODO (b/137101239): clean up split system user codes
2951      * Result code for {@link #checkProvisioningPrecondition}.
2952      *
2953      * @hide
2954      * @deprecated not used anymore but can't be removed since it's a @TestApi.
2955      */
2956     @Deprecated
2957     @TestApi
2958     public static final int STATUS_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER = 14;
2959 
2960     /**
2961      * Result code for {@link #checkProvisioningPrecondition}.
2962      *
2963      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
2964      * {@link #ACTION_PROVISION_MANAGED_PROFILE} on devices which do not support provisioning.
2965      *
2966      * @hide
2967      */
2968     @SystemApi
2969     public static final int STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS = 15;
2970 
2971     /**
2972      * Result code for {@link #checkProvisioningPrecondition}.
2973      *
2974      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when provisioning a DPC which does
2975      * not support headless system user mode on a headless system user mode device.
2976      *
2977      * @hide
2978      */
2979     @SystemApi
2980     public static final int STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED = 16;
2981 
2982     /**
2983      * Result code for {@link #checkProvisioningPrecondition}.
2984      *
2985      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} when provisioning a DPC into the
2986      * {@link DeviceAdminInfo#HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER} mode but only the system
2987      * user exists on the device.
2988      *
2989      * @hide
2990      */
2991     @SystemApi
2992     @FlaggedApi(FLAG_HEADLESS_DEVICE_OWNER_SINGLE_USER_ENABLED)
2993     public static final int STATUS_HEADLESS_ONLY_SYSTEM_USER = 17;
2994 
2995     /**
2996      * Result codes for {@link #checkProvisioningPrecondition} indicating all the provisioning pre
2997      * conditions.
2998      *
2999      * @hide
3000      */
3001     @Retention(RetentionPolicy.SOURCE)
3002     @IntDef(prefix = { "STATUS_" }, value = {
3003             STATUS_UNKNOWN_ERROR, STATUS_OK, STATUS_HAS_DEVICE_OWNER, STATUS_USER_HAS_PROFILE_OWNER,
3004             STATUS_USER_NOT_RUNNING, STATUS_USER_SETUP_COMPLETED, STATUS_NOT_SYSTEM_USER,
3005             STATUS_HAS_PAIRED, STATUS_MANAGED_USERS_NOT_SUPPORTED, STATUS_SYSTEM_USER,
3006             STATUS_CANNOT_ADD_MANAGED_PROFILE, STATUS_DEVICE_ADMIN_NOT_SUPPORTED,
3007             STATUS_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER,
3008             STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS,
3009             STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED, STATUS_HEADLESS_ONLY_SYSTEM_USER
3010     })
3011     public @interface ProvisioningPrecondition {}
3012 
3013     /**
3014      * Disable all configurable SystemUI features during LockTask mode. This includes,
3015      * <ul>
3016      *     <li>system info area in the status bar (connectivity icons, clock, etc.)
3017      *     <li>notifications (including alerts, icons, and the notification shade)
3018      *     <li>Home button
3019      *     <li>Recents button and UI
3020      *     <li>global actions menu (i.e. power button menu)
3021      *     <li>keyguard
3022      * </ul>
3023      *
3024      * @see #setLockTaskFeatures(ComponentName, int)
3025      */
3026     public static final int LOCK_TASK_FEATURE_NONE = 0;
3027 
3028     /**
3029      * Enable the system info area in the status bar during LockTask mode. The system info area
3030      * usually occupies the right side of the status bar (although this can differ across OEMs). It
3031      * includes all system information indicators, such as date and time, connectivity, battery,
3032      * vibration mode, etc.
3033      *
3034      * @see #setLockTaskFeatures(ComponentName, int)
3035      */
3036     public static final int LOCK_TASK_FEATURE_SYSTEM_INFO = 1;
3037 
3038     /**
3039      * Enable notifications during LockTask mode. This includes notification icons on the status
3040      * bar, heads-up notifications, and the expandable notification shade. Note that the Quick
3041      * Settings panel remains disabled. This feature flag can only be used in combination with
3042      * {@link #LOCK_TASK_FEATURE_HOME}. {@link #setLockTaskFeatures(ComponentName, int)}
3043      * throws an {@link IllegalArgumentException} if this feature flag is defined without
3044      * {@link #LOCK_TASK_FEATURE_HOME}.
3045      *
3046      * @see #setLockTaskFeatures(ComponentName, int)
3047      */
3048     public static final int LOCK_TASK_FEATURE_NOTIFICATIONS = 1 << 1;
3049 
3050     /**
3051      * Enable the Home button during LockTask mode. Note that if a custom launcher is used, it has
3052      * to be registered as the default launcher with
3053      * {@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}, and its
3054      * package needs to be allowlisted for LockTask with
3055      * {@link #setLockTaskPackages(ComponentName, String[])}.
3056      *
3057      * @see #setLockTaskFeatures(ComponentName, int)
3058      */
3059     public static final int LOCK_TASK_FEATURE_HOME = 1 << 2;
3060 
3061     /**
3062      * Enable the Overview button and the Overview screen during LockTask mode. This feature flag
3063      * can only be used in combination with {@link #LOCK_TASK_FEATURE_HOME}, and
3064      * {@link #setLockTaskFeatures(ComponentName, int)} will throw an
3065      * {@link IllegalArgumentException} if this feature flag is defined without
3066      * {@link #LOCK_TASK_FEATURE_HOME}.
3067      *
3068      * @see #setLockTaskFeatures(ComponentName, int)
3069      */
3070     public static final int LOCK_TASK_FEATURE_OVERVIEW = 1 << 3;
3071 
3072     /**
3073      * Enable the global actions dialog during LockTask mode. This is the dialog that shows up when
3074      * the user long-presses the power button, for example. Note that the user may not be able to
3075      * power off the device if this flag is not set.
3076      *
3077      * <p>This flag is enabled by default until {@link #setLockTaskFeatures(ComponentName, int)} is
3078      * called for the first time.
3079      *
3080      * @see #setLockTaskFeatures(ComponentName, int)
3081      */
3082     public static final int LOCK_TASK_FEATURE_GLOBAL_ACTIONS = 1 << 4;
3083 
3084     /**
3085      * Enable the keyguard during LockTask mode. Note that if the keyguard is already disabled with
3086      * {@link #setKeyguardDisabled(ComponentName, boolean)}, setting this flag will have no effect.
3087      * If this flag is not set, the keyguard will not be shown even if the user has a lock screen
3088      * credential.
3089      *
3090      * @see #setLockTaskFeatures(ComponentName, int)
3091      */
3092     public static final int LOCK_TASK_FEATURE_KEYGUARD = 1 << 5;
3093 
3094     /**
3095      * Enable blocking of non-allowlisted activities from being started into a locked task.
3096      *
3097      * @see #setLockTaskFeatures(ComponentName, int)
3098      */
3099     public static final int LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK = 1 << 6;
3100 
3101     /**
3102      * Flags supplied to {@link #setLockTaskFeatures(ComponentName, int)}.
3103      *
3104      * @hide
3105      */
3106     @Retention(RetentionPolicy.SOURCE)
3107     @IntDef(flag = true, prefix = { "LOCK_TASK_FEATURE_" }, value = {
3108             LOCK_TASK_FEATURE_NONE,
3109             LOCK_TASK_FEATURE_SYSTEM_INFO,
3110             LOCK_TASK_FEATURE_NOTIFICATIONS,
3111             LOCK_TASK_FEATURE_HOME,
3112             LOCK_TASK_FEATURE_OVERVIEW,
3113             LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
3114             LOCK_TASK_FEATURE_KEYGUARD,
3115             LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK
3116     })
3117     public @interface LockTaskFeature {}
3118 
3119     /**
3120      * Service action: Action for a service that device owner and profile owner can optionally
3121      * own.  If a device owner or a profile owner has such a service, the system tries to keep
3122      * a bound connection to it, in order to keep their process always running.
3123      * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN}
3124      * permission.
3125      */
3126     @SdkConstant(SdkConstantType.SERVICE_ACTION)
3127     public static final String ACTION_DEVICE_ADMIN_SERVICE
3128             = "android.app.action.DEVICE_ADMIN_SERVICE";
3129 
3130     /** @hide */
3131     @Retention(RetentionPolicy.SOURCE)
3132     @IntDef(flag = true, prefix = {"ID_TYPE_"}, value = {
3133         ID_TYPE_BASE_INFO,
3134         ID_TYPE_SERIAL,
3135         ID_TYPE_IMEI,
3136         ID_TYPE_MEID,
3137         ID_TYPE_INDIVIDUAL_ATTESTATION
3138     })
3139     public @interface AttestationIdType {}
3140 
3141     /**
3142      * Specifies that the device should attest its manufacturer details. For use with
3143      * {@link #generateKeyPair}.
3144      *
3145      * @see #generateKeyPair
3146      */
3147     public static final int ID_TYPE_BASE_INFO = 1;
3148 
3149     /**
3150      * Specifies that the device should attest its serial number. For use with
3151      * {@link #generateKeyPair}.
3152      *
3153      * @see #generateKeyPair
3154      */
3155     public static final int ID_TYPE_SERIAL = 2;
3156 
3157     /**
3158      * Specifies that the device should attest its IMEI. For use with {@link #generateKeyPair}.
3159      *
3160      * @see #generateKeyPair
3161      */
3162     public static final int ID_TYPE_IMEI = 4;
3163 
3164     /**
3165      * Specifies that the device should attest its MEID. For use with {@link #generateKeyPair}.
3166      *
3167      * @see #generateKeyPair
3168      */
3169     public static final int ID_TYPE_MEID = 8;
3170 
3171     /**
3172      * Specifies that the device should attest using an individual attestation certificate.
3173      * For use with {@link #generateKeyPair}.
3174      *
3175      * @see #generateKeyPair
3176      */
3177     public static final int ID_TYPE_INDIVIDUAL_ATTESTATION = 16;
3178 
3179     /**
3180      * Service-specific error code for {@link #generateKeyPair}:
3181      * Indicates the call has failed due to StrongBox unavailability.
3182      * @hide
3183      */
3184     public static final int KEY_GEN_STRONGBOX_UNAVAILABLE = 1;
3185 
3186     /**
3187      * Specifies that the calling app should be granted access to the installed credentials
3188      * immediately. Otherwise, access to the credentials will be gated by user approval.
3189      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
3190      *
3191      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
3192      */
3193     public static final int INSTALLKEY_REQUEST_CREDENTIALS_ACCESS = 1;
3194 
3195     /**
3196      * Specifies that a user can select the key via the Certificate Selection prompt.
3197      * If this flag is not set when calling {@link #installKeyPair}, the key can only be granted
3198      * access by implementing {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
3199      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
3200      *
3201      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
3202      */
3203     public static final int INSTALLKEY_SET_USER_SELECTABLE = 2;
3204 
3205     /**
3206      * Broadcast action: sent when the profile owner is set, changed or cleared.
3207      *
3208      * This broadcast is sent only to the user managed by the new profile owner.
3209      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
3210      */
3211     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
3212     public static final String ACTION_PROFILE_OWNER_CHANGED =
3213             "android.app.action.PROFILE_OWNER_CHANGED";
3214 
3215     /** @hide */
3216     @Retention(RetentionPolicy.SOURCE)
3217     @IntDef(prefix = {"PRIVATE_DNS_MODE_"}, value = {
3218             PRIVATE_DNS_MODE_UNKNOWN,
3219             PRIVATE_DNS_MODE_OFF,
3220             PRIVATE_DNS_MODE_OPPORTUNISTIC,
3221             PRIVATE_DNS_MODE_PROVIDER_HOSTNAME
3222     })
3223     public @interface PrivateDnsMode {}
3224 
3225     /**
3226      * Specifies that the Private DNS setting is in an unknown state.
3227      */
3228     public static final int PRIVATE_DNS_MODE_UNKNOWN = 0;
3229 
3230     /**
3231      * Specifies that Private DNS was turned off completely.
3232      */
3233     public static final int PRIVATE_DNS_MODE_OFF = 1;
3234 
3235     /**
3236      * Specifies that the device owner requested opportunistic DNS over TLS
3237      */
3238     public static final int PRIVATE_DNS_MODE_OPPORTUNISTIC = 2;
3239 
3240     /**
3241      * Specifies that the device owner configured a specific host to use for Private DNS.
3242      */
3243     public static final int PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = 3;
3244 
3245     /**
3246      * Callback used in {@link #installSystemUpdate} to indicate that there was an error while
3247      * trying to install an update.
3248      */
3249     public abstract static class InstallSystemUpdateCallback {
3250         /** Represents an unknown error while trying to install an update. */
3251         public static final int UPDATE_ERROR_UNKNOWN = 1;
3252 
3253         /** Represents the update file being intended for different OS version. */
3254         public static final int UPDATE_ERROR_INCORRECT_OS_VERSION = 2;
3255 
3256         /**
3257          * Represents the update file being wrong; e.g. payloads are mismatched, or the wrong
3258          * compression method is used.
3259          */
3260         public static final int UPDATE_ERROR_UPDATE_FILE_INVALID = 3;
3261 
3262         /** Represents that the file could not be found. */
3263         public static final int UPDATE_ERROR_FILE_NOT_FOUND = 4;
3264 
3265         /** Represents the battery being too low to apply an update. */
3266         public static final int UPDATE_ERROR_BATTERY_LOW = 5;
3267 
3268         /**
3269          * Method invoked when there was an error while installing an update.
3270          *
3271          * <p>The given error message is not intended to be user-facing. It is intended to be
3272          * reported back to the IT admin to be read.
3273          */
onInstallUpdateError( @nstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage)3274         public void onInstallUpdateError(
3275                 @InstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage) {
3276         }
3277     }
3278 
3279     /**
3280      * @hide
3281      */
3282     @IntDef(prefix = { "UPDATE_ERROR_" }, value = {
3283             InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN,
3284             InstallSystemUpdateCallback.UPDATE_ERROR_INCORRECT_OS_VERSION,
3285             InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
3286             InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
3287             InstallSystemUpdateCallback.UPDATE_ERROR_BATTERY_LOW
3288     })
3289     @Retention(RetentionPolicy.SOURCE)
3290     public @interface InstallUpdateCallbackErrorConstants {}
3291 
3292     /**
3293      * The selected mode has been set successfully. If the mode is
3294      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} then it implies the supplied host is valid
3295      * and reachable.
3296      */
3297     public static final int PRIVATE_DNS_SET_NO_ERROR = 0;
3298 
3299     /**
3300      * If the {@code privateDnsHost} provided was of a valid hostname but that host was found
3301      * to not support DNS-over-TLS.
3302      */
3303     public static final int PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING = 1;
3304 
3305     /**
3306      * General failure to set the Private DNS mode, not due to one of the reasons listed above.
3307      */
3308     public static final int PRIVATE_DNS_SET_ERROR_FAILURE_SETTING = 2;
3309 
3310     /**
3311      * @hide
3312      */
3313     @IntDef(prefix = {"PRIVATE_DNS_SET_"}, value = {
3314             PRIVATE_DNS_SET_NO_ERROR,
3315             PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING,
3316             PRIVATE_DNS_SET_ERROR_FAILURE_SETTING
3317     })
3318     @Retention(RetentionPolicy.SOURCE)
3319     public @interface PrivateDnsModeErrorCodes {}
3320 
3321     /**
3322      * Activity action: Starts the administrator to get the mode for the provisioning.
3323      * This intent may contain the following extras:
3324      * <ul>
3325      *     <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}</li>
3326      *     <li>{@link #EXTRA_PROVISIONING_IMEI}</li>
3327      *     <li>{@link #EXTRA_PROVISIONING_SERIAL_NUMBER}</li>
3328      *     <li>{@link #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES}</li>
3329      *     <li>{@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT}</li>
3330      * </ul>
3331      *
3332      * <p>The target activity should return one of the following values in
3333      * {@link #EXTRA_PROVISIONING_MODE} as result:
3334      * <ul>
3335      *     <li>{@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}</li>
3336      *     <li>{@link #PROVISIONING_MODE_MANAGED_PROFILE}</li>
3337      * </ul>
3338      *
3339      * <p>If performing fully-managed device provisioning and the admin app desires to show its
3340      * own education screens, the target activity can additionally return
3341      * {@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS} set to <code>true</code>.
3342      *
3343      * <p>The target activity may also return the account that needs to be migrated from primary
3344      * user to managed profile in case of a profile owner provisioning in
3345      * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE} as result.
3346      *
3347      * <p>The target activity may also include the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}
3348      * extra in the intent result. The values of this {@link android.os.PersistableBundle} will be
3349      * sent as an intent extra of the same name to the {@link #ACTION_ADMIN_POLICY_COMPLIANCE}
3350      * activity, along with the values of the {@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE} extra
3351      * that are already supplied to this activity.
3352      *
3353      * <p>Other extras the target activity may include in the intent result:
3354      * <ul>
3355      *     <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}</li>
3356      *     <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}</li>
3357      *     <li>{@link #EXTRA_PROVISIONING_KEEP_SCREEN_ON}</li>
3358      *     <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION} for work profile
3359      *     provisioning</li>
3360      *     <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED} for work profile
3361      *     provisioning</li>
3362      *     <li>{@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT} for fully-managed
3363      *     device provisioning</li>
3364      *     <li>{@link #EXTRA_PROVISIONING_LOCALE} for fully-managed device provisioning</li>
3365      *     <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} for fully-managed device provisioning</li>
3366      *     <li>{@link #EXTRA_PROVISIONING_TIME_ZONE} for fully-managed device provisioning</li>
3367      * </ul>
3368      *
3369      * @see #ACTION_ADMIN_POLICY_COMPLIANCE
3370      */
3371     public static final String ACTION_GET_PROVISIONING_MODE =
3372             "android.app.action.GET_PROVISIONING_MODE";
3373 
3374     /**
3375      * A string extra holding the IMEI (International Mobile Equipment Identity) of the device.
3376      */
3377     public static final String EXTRA_PROVISIONING_IMEI = "android.app.extra.PROVISIONING_IMEI";
3378 
3379     /**
3380      * A string extra holding the serial number of the device.
3381      */
3382     public static final String EXTRA_PROVISIONING_SERIAL_NUMBER =
3383             "android.app.extra.PROVISIONING_SERIAL_NUMBER";
3384 
3385     /**
3386      * An intent extra holding the provisioning mode returned by the administrator.
3387      * The value of this extra must be one of the values provided in {@link
3388      * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES}, which is provided as an intent extra to
3389      * the admin app's {@link #ACTION_GET_PROVISIONING_MODE} activity.
3390      *
3391      * @see #PROVISIONING_MODE_FULLY_MANAGED_DEVICE
3392      * @see #PROVISIONING_MODE_MANAGED_PROFILE
3393      */
3394     public static final String EXTRA_PROVISIONING_MODE =
3395             "android.app.extra.PROVISIONING_MODE";
3396 
3397     /**
3398      * An integer extra indication what provisioning modes should be available for the admin app
3399      * to pick.
3400      *
3401      * <p>The default value is {@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}.
3402      *
3403      * <p>The value of this extra will determine the contents of the {@link
3404      * #EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES} array that is passed to the admin app as an
3405      * extra to its {@link #ACTION_GET_PROVISIONING_MODE} activity.
3406      *
3407      * <p>If one of the possible admin app choices is a personally-owned work profile, then the
3408      * IMEI and serial number will not be passed to the admin app's {@link
3409      * #ACTION_GET_PROVISIONING_MODE} activity via the {@link #EXTRA_PROVISIONING_IMEI} and {@link
3410      * #EXTRA_PROVISIONING_SERIAL_NUMBER} respectively.
3411      *
3412      * <p>The allowed flag combinations are:
3413      * <ul>
3414      *     <li>{@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}</li>
3415      *     <li>{@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}</li>
3416      *     <li>{@link #FLAG_SUPPORTED_MODES_DEVICE_OWNER}</li>
3417      *     <li>{@link #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED}
3418      *             | {@link #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED}</li>
3419      * </ul>
3420      *
3421      * <p>This extra is only respected when provided alongside the {@link
3422      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
3423      *
3424      * @see #FLAG_SUPPORTED_MODES_ORGANIZATION_OWNED
3425      * @see #FLAG_SUPPORTED_MODES_PERSONALLY_OWNED
3426      * @see #FLAG_SUPPORTED_MODES_DEVICE_OWNER
3427      * @hide
3428      */
3429     @SystemApi
3430     public static final String EXTRA_PROVISIONING_SUPPORTED_MODES =
3431             "android.app.extra.PROVISIONING_SUPPORTED_MODES";
3432 
3433     /**
3434      * A boolean extra which determines whether to skip the ownership disclaimer screen during the
3435      * provisioning flow. The default value is {@code false}.
3436      *
3437      * If the value is {@code true}, the provisioning initiator must display a device ownership
3438      * disclaimer screen similar to that provided in AOSP.
3439      *
3440      * <p>This extra is only respected when provided alongside the {@link
3441      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
3442      *
3443      * @hide
3444      */
3445     @SystemApi
3446     public static final String EXTRA_PROVISIONING_SKIP_OWNERSHIP_DISCLAIMER =
3447             "android.app.extra.PROVISIONING_SKIP_OWNERSHIP_DISCLAIMER";
3448 
3449     /**
3450      * An {@link ArrayList} of {@link Integer} extra specifying the allowed provisioning modes.
3451      * <p>This extra will be passed to the admin app's {@link #ACTION_GET_PROVISIONING_MODE}
3452      * activity, whose result intent must contain {@link #EXTRA_PROVISIONING_MODE} set to one of
3453      * the values in this array.
3454      * <p>If the value set to {@link #EXTRA_PROVISIONING_MODE} is not in the array,
3455      * provisioning will fail.
3456      * @see #PROVISIONING_MODE_MANAGED_PROFILE
3457      * @see #PROVISIONING_MODE_FULLY_MANAGED_DEVICE
3458      */
3459     public static final String EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES =
3460             "android.app.extra.PROVISIONING_ALLOWED_PROVISIONING_MODES";
3461 
3462     /**
3463      * The provisioning mode for fully managed device.
3464      */
3465     public static final int PROVISIONING_MODE_FULLY_MANAGED_DEVICE = 1;
3466 
3467     /**
3468      * The provisioning mode for managed profile.
3469      */
3470     public static final int PROVISIONING_MODE_MANAGED_PROFILE = 2;
3471 
3472     /**
3473      * The provisioning mode for a managed profile on a personal device.
3474      * <p>This mode is only available when the provisioning initiator has explicitly instructed the
3475      * provisioning flow to support managed profile on a personal device provisioning. In that case,
3476      * {@link #PROVISIONING_MODE_MANAGED_PROFILE} corresponds to an organization-owned managed
3477      * profile, whereas this constant corresponds to a personally-owned managed profile.
3478      *
3479      * @see #EXTRA_PROVISIONING_MODE
3480      */
3481     public static final int PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE = 3;
3482 
3483     /**
3484      * A {@code boolean} flag that indicates whether the provisioning flow should return before
3485      * starting the admin app's {@link #ACTION_ADMIN_POLICY_COMPLIANCE} handler. The default value
3486      * is {@code true}.
3487      *
3488      * <p>If this extra is set to {@code true}, then when the provisioning flow returns back to the
3489      * provisioning initiator, provisioning will not be complete. The provisioning initiator can
3490      * use this opportunity to do its own preparatory steps prior to the launch of the admin app's
3491      * {@link #ACTION_ADMIN_POLICY_COMPLIANCE} handler. It is the responsibility of the
3492      * provisioning initiator to ensure that the provisioning flow is then resumed and completed.
3493      *
3494      * <p>If this extra is set to {@code false}, then when the provisioning flow returns back to
3495      * the provisioning initiator, provisioning will be complete. Note that device owner
3496      * provisioning is not currently supported for the this scenario.
3497      *
3498      * <p>This extra is only respected when provided alongside the {@link
3499      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent action.
3500      *
3501      * @hide
3502      */
3503     @SystemApi
3504     public static final String EXTRA_PROVISIONING_RETURN_BEFORE_POLICY_COMPLIANCE =
3505             "android.app.extra.PROVISIONING_RETURN_BEFORE_POLICY_COMPLIANCE";
3506 
3507     /**
3508      * A {@code boolean} flag that indicates whether the screen should be on throughout the
3509      * provisioning flow.
3510      *
3511      * <p>This extra can either be passed as an extra to the {@link
3512      * #ACTION_PROVISION_MANAGED_PROFILE} intent, or it can be returned by the
3513      * admin app when performing the admin-integrated provisioning flow as a result of the
3514      * {@link #ACTION_GET_PROVISIONING_MODE} activity.
3515      *
3516      * @deprecated from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the flag wouldn't
3517      * be functional. The screen is kept on throughout the provisioning flow.
3518      */
3519 
3520     @Deprecated
3521     public static final String EXTRA_PROVISIONING_KEEP_SCREEN_ON =
3522             "android.app.extra.PROVISIONING_KEEP_SCREEN_ON";
3523 
3524     /**
3525      * Activity action: Starts the administrator to show policy compliance for the provisioning.
3526      * This action is used any time that the administrator has an opportunity to show policy
3527      * compliance before the end of setup wizard. This could happen as part of the admin-integrated
3528      * provisioning flow (in which case this gets sent after {@link #ACTION_GET_PROVISIONING_MODE}),
3529      * or it could happen during provisioning finalization if the administrator supports
3530      * finalization during setup wizard.
3531      *
3532      * <p>Intents with this action may also be supplied with the {@link
3533      * #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE} extra.
3534      *
3535      * @see #ACTION_GET_PROVISIONING_MODE
3536      */
3537     public static final String ACTION_ADMIN_POLICY_COMPLIANCE =
3538             "android.app.action.ADMIN_POLICY_COMPLIANCE";
3539 
3540     /**
3541      * Activity action: Starts the device policy management role holder updater.
3542      *
3543      * <p>The activity must handle the device policy management role holder update and set the
3544      * intent result. This can include {@link Activity#RESULT_OK} if the update was successful,
3545      * {@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_RECOVERABLE_ERROR} if
3546      * it encounters a problem that may be solved by relaunching it again, {@link
3547      * #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_PROVISIONING_DISABLED} if role holder
3548      * provisioning is disabled, or {@link
3549      * #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR} if it encounters
3550      * any other problem that will not be solved by relaunching it again.
3551      *
3552      * <p>If this activity has additional internal conditions which are not met, it should return
3553      * {@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR}.
3554      *
3555      * @hide
3556      */
3557     @RequiresPermission(android.Manifest.permission.LAUNCH_DEVICE_MANAGER_SETUP)
3558     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3559     @SystemApi
3560     public static final String ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER =
3561             "android.app.action.UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER";
3562 
3563     /**
3564      * Result code that can be returned by the {@link
3565      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} handler if it encounters a problem
3566      * that may be solved by relaunching it again.
3567      *
3568      * @hide
3569      */
3570     @SystemApi
3571     public static final int RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_RECOVERABLE_ERROR =
3572             1;
3573 
3574     /**
3575      * Result code that can be returned by the {@link
3576      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} handler if it encounters a problem that
3577      * will not be solved by relaunching it again.
3578      *
3579      * @hide
3580      */
3581     @SystemApi
3582     public static final int RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR =
3583             2;
3584 
3585     /**
3586      * Result code that can be returned by the {@link
3587      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} handler if role holder provisioning
3588      * is disabled.
3589      *
3590      * @hide
3591      */
3592     @SystemApi
3593     public static final int
3594             RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_PROVISIONING_DISABLED = 3;
3595 
3596     /**
3597      * An {@code int} extra that specifies one of {@link
3598      * #ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING} or {@link
3599      * #ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FALLBACK_TO_PLATFORM_PROVISIONING}.
3600      *
3601      * <p>The failure strategy specifies how the platform should handle a failed device policy
3602      * management role holder update via {@link
3603      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} when {@link
3604      * #EXTRA_PROVISIONING_ALLOW_OFFLINE} is not set or set to {@code false}.
3605      *
3606      * <p>This extra may be supplied as part of the {@link
3607      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER} result intent.
3608      *
3609      * <p>Default value is {@link #ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING}.
3610      *
3611      * @hide
3612      */
3613     public static final String EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY =
3614             "android.app.extra.ROLE_HOLDER_UPDATE_FAILURE_STRATEGY";
3615 
3616     /**
3617      * Possible values for {@link #EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY}.
3618      *
3619      * @hide
3620      */
3621     @IntDef(prefix = { "ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_" }, value = {
3622             ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING,
3623             ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FALLBACK_TO_PLATFORM_PROVISIONING
3624     })
3625     @Retention(RetentionPolicy.SOURCE)
3626     public @interface RoleHolderUpdateFailureStrategy {}
3627 
3628     /**
3629      * A value for {@link #EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY} indicating that upon
3630      * failure to update the role holder, provisioning should fail.
3631      *
3632      * @hide
3633      */
3634     public static final int ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FAIL_PROVISIONING = 1;
3635 
3636     /**
3637      * A value for {@link #EXTRA_ROLE_HOLDER_UPDATE_FAILURE_STRATEGY} indicating that upon
3638      * failure to update the role holder, provisioning should fallback to be platform-driven.
3639      *
3640      * @hide
3641      */
3642     public static final int ROLE_HOLDER_UPDATE_FAILURE_STRATEGY_FALLBACK_TO_PLATFORM_PROVISIONING =
3643             2;
3644 
3645     /**
3646      * An {@code int} extra which contains the result code of the last attempt to update
3647      * the device policy management role holder via {@link
3648      * #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER}.
3649      *
3650      * <p>This extra is provided to the device policy management role holder via either {@link
3651      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link
3652      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE} when started after the role holder
3653      * had previously returned {@link #RESULT_UPDATE_ROLE_HOLDER}.
3654      *
3655      * <p>If the role holder update had failed, the role holder can use the value of this extra to
3656      * make a decision whether to fail the provisioning flow or to carry on with the older version
3657      * of the role holder.
3658      *
3659      * <p>Possible values can be:
3660      * <ul>
3661      *    <li>{@link Activity#RESULT_OK} if the update was successful
3662      *    <li>{@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_RECOVERABLE_ERROR} if it
3663      *    encounters a problem that may be solved by relaunching it again.
3664      *    <li>{@link #RESULT_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER_UNRECOVERABLE_ERROR} if
3665      *    it encounters a problem that will not be solved by relaunching it again.
3666      *    <li>Any other value returned by {@link
3667      *    #ACTION_UPDATE_DEVICE_POLICY_MANAGEMENT_ROLE_HOLDER}
3668      * </ul>
3669      *
3670      * @hide
3671      */
3672     @SystemApi
3673     public static final String EXTRA_ROLE_HOLDER_UPDATE_RESULT_CODE =
3674             "android.app.extra.ROLE_HOLDER_UPDATE_RESULT_CODE";
3675 
3676     /**
3677      * An {@link Intent} extra which resolves to a custom user consent screen.
3678      *
3679      * <p>If this extra is provided to the device policy management role holder via either {@link
3680      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} or {@link
3681      * #ACTION_ROLE_HOLDER_PROVISION_MANAGED_PROFILE}, the device policy management role holder must
3682      * launch this intent which shows the custom user consent screen, replacing its own standard
3683      * consent screen.
3684      *
3685      * <p>If this extra is provided, it is the responsibility of the intent handler to show the
3686      * list of disclaimers which are normally shown by the standard consent screen:
3687      * <ul>
3688      *     <li>Disclaimers set by the IT admin via the {@link #EXTRA_PROVISIONING_DISCLAIMERS}
3689      *     provisioning extra</li>
3690      *     <li>For fully-managed device provisioning, disclaimers defined in system apps via the
3691      *     {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER} and {@link
3692      *     #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} metadata in their manifests</li>
3693      *     <li>General disclaimer relevant to the provisioning mode</li>
3694      * </ul>
3695      *
3696      * <p>When this {@link Intent} is started, the following intent extras will be supplied:
3697      * <ul>
3698      *     <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}</li>
3699      *     <li>{@link #EXTRA_PROVISIONING_MODE}</li>
3700      *     <li>{@link #EXTRA_PROVISIONING_LOCALE}</li>
3701      *     <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME}</li>
3702      *     <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}</li>
3703      *     <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}</li>
3704      * </ul>
3705      *
3706      * <p>If the custom consent screens are granted by the user {@link Activity#RESULT_OK} is
3707      * returned, otherwise {@link Activity#RESULT_CANCELED} is returned. The device policy
3708      * management role holder should ensure that the provisioning flow terminates immediately if
3709      * consent is not granted by the user.
3710      *
3711      * @hide
3712      */
3713     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3714     @SystemApi
3715     public static final String EXTRA_PROVISIONING_ROLE_HOLDER_CUSTOM_USER_CONSENT_INTENT =
3716             "android.app.extra.PROVISIONING_ROLE_HOLDER_CUSTOM_USER_CONSENT_INTENT";
3717 
3718     /**
3719      * Activity action: attempts to establish network connection
3720      *
3721      * <p>This intent can be accompanied by any of the relevant provisioning extras related to
3722      * network connectivity, such as:
3723      * <ul>
3724      *     <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}</li>
3725      *     <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN}</li>
3726      *     <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}</li>
3727      *     <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}</li>
3728      *     <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}</li>
3729      *     <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT}</li>
3730      *     <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}</li>
3731      *     <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}</li>
3732      *     <li>{@code #EXTRA_PROVISIONING_WIFI_EAP_METHOD}</li>
3733      *     <li>{@code #EXTRA_PROVISIONING_WIFI_PHASE2_AUTH}</li>
3734      *     <li>{@code #EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE}</li>
3735      *     <li>{@code #EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE}</li>
3736      *     <li>{@code #EXTRA_PROVISIONING_WIFI_IDENTITY}</li>
3737      *     <li>{@code #EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY}</li>
3738      *     <li>{@code #EXTRA_PROVISIONING_WIFI_DOMAIN}</li>
3739      * </ul>
3740      *
3741      * <p>If there are provisioning extras related to network connectivity, this activity
3742      * attempts to connect to the specified network. Otherwise it prompts the end-user to connect.
3743      *
3744      * <p>This activity is meant to be started by the provisioning initiator prior to starting
3745      * {@link #ACTION_PROVISION_MANAGED_PROFILE} or {@link
3746      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}.
3747      *
3748      * <p>Note that network connectivity is still also handled when provisioning via {@link
3749      * #ACTION_PROVISION_MANAGED_PROFILE} or {@link
3750      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}. {@link
3751      * #ACTION_ESTABLISH_NETWORK_CONNECTION} should only be used in cases when the provisioning
3752      * initiator would like to do some additional logic after the network connectivity step and
3753      * before the start of provisioning.
3754      *
3755      * If network connection is established, {@link Activity#RESULT_OK} will be returned. Otherwise
3756      * the result will be {@link Activity#RESULT_CANCELED}.
3757      *
3758      * @hide
3759      */
3760     @RequiresPermission(android.Manifest.permission.DISPATCH_PROVISIONING_MESSAGE)
3761     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
3762     @SystemApi
3763     public static final String ACTION_ESTABLISH_NETWORK_CONNECTION =
3764             "android.app.action.ESTABLISH_NETWORK_CONNECTION";
3765 
3766     /**
3767      * Maximum supported password length. Kind-of arbitrary.
3768      * @hide
3769      */
3770     public static final int MAX_PASSWORD_LENGTH = 16;
3771 
3772     /**
3773      * Service Action: Service implemented by a device owner or profile owner supervision app to
3774      * provide a secondary lockscreen.
3775      * @hide
3776      */
3777     @SystemApi
3778     public static final String ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE =
3779             "android.app.action.BIND_SECONDARY_LOCKSCREEN_SERVICE";
3780 
3781     /**
3782      * Return value for {@link #getPersonalAppsSuspendedReasons} when personal apps are not
3783      * suspended.
3784      */
3785     public static final int PERSONAL_APPS_NOT_SUSPENDED = 0;
3786 
3787     /**
3788      * Flag for {@link #getPersonalAppsSuspendedReasons} return value. Set when personal
3789      * apps are suspended by an admin explicitly via {@link #setPersonalAppsSuspended}.
3790      */
3791     public static final int PERSONAL_APPS_SUSPENDED_EXPLICITLY = 1 << 0;
3792 
3793     /**
3794      * Flag for {@link #getPersonalAppsSuspendedReasons} return value. Set when personal apps are
3795      * suspended by framework because managed profile was off for longer than allowed by policy.
3796      * @see #setManagedProfileMaximumTimeOff
3797      */
3798     public static final int PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT = 1 << 1;
3799 
3800     /**
3801      * @hide
3802      */
3803     @IntDef(flag = true, prefix = { "PERSONAL_APPS_" }, value = {
3804             PERSONAL_APPS_NOT_SUSPENDED,
3805             PERSONAL_APPS_SUSPENDED_EXPLICITLY,
3806             PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT
3807     })
3808     @Retention(RetentionPolicy.SOURCE)
3809     public @interface PersonalAppsSuspensionReason {}
3810 
3811     /**
3812      * The default device owner type for a managed device.
3813      *
3814      * @hide
3815      */
3816     @TestApi
3817     public static final int DEVICE_OWNER_TYPE_DEFAULT = 0;
3818 
3819     /**
3820      * The device owner type for a financed device.
3821      *
3822      * @hide
3823      */
3824     @TestApi
3825     public static final int DEVICE_OWNER_TYPE_FINANCED = 1;
3826 
3827     /**
3828      * Different device owner types for a managed device.
3829      *
3830      * @hide
3831      */
3832     @Retention(RetentionPolicy.SOURCE)
3833     @IntDef(prefix = { "DEVICE_OWNER_TYPE_" }, value = {
3834             DEVICE_OWNER_TYPE_DEFAULT,
3835             DEVICE_OWNER_TYPE_FINANCED
3836     })
3837     public @interface DeviceOwnerType {}
3838 
3839     /** @hide */
3840     @TestApi
3841     public static final int OPERATION_LOCK_NOW = 1;
3842     /** @hide */
3843     @TestApi
3844     public static final int OPERATION_SWITCH_USER = 2;
3845     /** @hide */
3846     @TestApi
3847     public static final int OPERATION_START_USER_IN_BACKGROUND = 3;
3848     /** @hide */
3849     @TestApi
3850     public static final int OPERATION_STOP_USER = 4;
3851     /** @hide */
3852     @TestApi
3853     public static final int OPERATION_CREATE_AND_MANAGE_USER = 5;
3854     /** @hide */
3855     @TestApi
3856     public static final int OPERATION_REMOVE_USER = 6;
3857     /** @hide */
3858     @TestApi
3859     public static final int OPERATION_REBOOT = 7;
3860     /** @hide */
3861     @TestApi
3862     public static final int OPERATION_WIPE_DATA = 8;
3863     /** @hide */
3864     @TestApi
3865     public static final int OPERATION_LOGOUT_USER = 9;
3866     /** @hide */
3867     @TestApi
3868     public static final int OPERATION_SET_USER_RESTRICTION = 10;
3869     /** @hide */
3870     @TestApi
3871     public static final int OPERATION_SET_SYSTEM_SETTING = 11;
3872     /** @hide */
3873     @TestApi
3874     public static final int OPERATION_SET_KEYGUARD_DISABLED = 12;
3875     /** @hide */
3876     @TestApi
3877     public static final int OPERATION_SET_STATUS_BAR_DISABLED = 13;
3878     /** @hide */
3879     @TestApi
3880     public static final int OPERATION_SET_SYSTEM_UPDATE_POLICY = 14;
3881     /** @hide */
3882     @TestApi
3883     public static final int OPERATION_SET_APPLICATION_HIDDEN = 15;
3884     /** @hide */
3885     @TestApi
3886     public static final int OPERATION_SET_APPLICATION_RESTRICTIONS = 16;
3887     /** @hide */
3888     @TestApi
3889     public static final int OPERATION_SET_KEEP_UNINSTALLED_PACKAGES = 17;
3890     /** @hide */
3891     @TestApi
3892     public static final int OPERATION_SET_LOCK_TASK_FEATURES = 18;
3893     /** @hide */
3894     @TestApi
3895     public static final int OPERATION_SET_LOCK_TASK_PACKAGES = 19;
3896     /** @hide */
3897     @TestApi
3898     public static final int OPERATION_SET_PACKAGES_SUSPENDED = 20;
3899     /** @hide */
3900     @TestApi
3901     public static final int OPERATION_SET_TRUST_AGENT_CONFIGURATION = 21;
3902     /** @hide */
3903     @TestApi
3904     public static final int OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES = 22;
3905     /** @hide */
3906     @TestApi
3907     public static final int OPERATION_CLEAR_APPLICATION_USER_DATA = 23;
3908     /** @hide */
3909     @TestApi
3910     public static final int OPERATION_INSTALL_CA_CERT = 24;
3911     /** @hide */
3912     @TestApi
3913     public static final int OPERATION_INSTALL_KEY_PAIR = 25;
3914     /** @hide */
3915     @TestApi
3916     public static final int OPERATION_INSTALL_SYSTEM_UPDATE = 26;
3917     /** @hide */
3918     @TestApi
3919     public static final int OPERATION_REMOVE_ACTIVE_ADMIN = 27;
3920     /** @hide */
3921     @TestApi
3922     public static final int OPERATION_REMOVE_KEY_PAIR = 28;
3923     /** @hide */
3924     @TestApi
3925     public static final int OPERATION_REQUEST_BUGREPORT = 29;
3926     /** @hide */
3927     @TestApi
3928     public static final int OPERATION_SET_ALWAYS_ON_VPN_PACKAGE = 30;
3929     /** @hide */
3930     @TestApi
3931     public static final int OPERATION_SET_CAMERA_DISABLED = 31;
3932     /** @hide */
3933     @TestApi
3934     public static final int OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY = 32;
3935     /** @hide */
3936     @TestApi
3937     public static final int OPERATION_SET_GLOBAL_PRIVATE_DNS = 33;
3938     /** @hide */
3939     @TestApi
3940     public static final int OPERATION_SET_LOGOUT_ENABLED = 34;
3941     /** @hide */
3942     @TestApi
3943     public static final int OPERATION_SET_MASTER_VOLUME_MUTED = 35;
3944     /** @hide */
3945     @TestApi
3946     public static final int OPERATION_SET_OVERRIDE_APNS_ENABLED = 36;
3947     /** @hide */
3948     @TestApi
3949     public static final int OPERATION_SET_PERMISSION_GRANT_STATE = 37;
3950     /** @hide */
3951     @TestApi
3952     public static final int OPERATION_SET_PERMISSION_POLICY = 38;
3953     /** @hide */
3954     @TestApi
3955     public static final int OPERATION_SET_RESTRICTIONS_PROVIDER = 39;
3956     /** @hide */
3957     @TestApi
3958     public static final int OPERATION_UNINSTALL_CA_CERT = 40;
3959     /** @hide */
3960     @TestApi
3961     @FlaggedApi(android.view.contentprotection.flags.Flags.FLAG_MANAGE_DEVICE_POLICY_ENABLED)
3962     public static final int OPERATION_SET_CONTENT_PROTECTION_POLICY = 41;
3963 
3964     private static final String PREFIX_OPERATION = "OPERATION_";
3965 
3966     /** @hide */
3967     @IntDef(prefix = PREFIX_OPERATION, value = {
3968             OPERATION_LOCK_NOW,
3969             OPERATION_SWITCH_USER,
3970             OPERATION_START_USER_IN_BACKGROUND,
3971             OPERATION_STOP_USER,
3972             OPERATION_CREATE_AND_MANAGE_USER,
3973             OPERATION_REMOVE_USER,
3974             OPERATION_REBOOT,
3975             OPERATION_WIPE_DATA,
3976             OPERATION_LOGOUT_USER,
3977             OPERATION_SET_USER_RESTRICTION,
3978             OPERATION_SET_SYSTEM_SETTING,
3979             OPERATION_SET_KEYGUARD_DISABLED,
3980             OPERATION_SET_STATUS_BAR_DISABLED,
3981             OPERATION_SET_SYSTEM_UPDATE_POLICY,
3982             OPERATION_SET_APPLICATION_HIDDEN,
3983             OPERATION_SET_APPLICATION_RESTRICTIONS,
3984             OPERATION_SET_KEEP_UNINSTALLED_PACKAGES,
3985             OPERATION_SET_LOCK_TASK_FEATURES,
3986             OPERATION_SET_LOCK_TASK_PACKAGES,
3987             OPERATION_SET_PACKAGES_SUSPENDED,
3988             OPERATION_SET_TRUST_AGENT_CONFIGURATION,
3989             OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES,
3990             OPERATION_CLEAR_APPLICATION_USER_DATA,
3991             OPERATION_INSTALL_CA_CERT,
3992             OPERATION_INSTALL_KEY_PAIR,
3993             OPERATION_INSTALL_SYSTEM_UPDATE,
3994             OPERATION_REMOVE_ACTIVE_ADMIN,
3995             OPERATION_REMOVE_KEY_PAIR,
3996             OPERATION_REQUEST_BUGREPORT,
3997             OPERATION_SET_ALWAYS_ON_VPN_PACKAGE,
3998             OPERATION_SET_CAMERA_DISABLED,
3999             OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY,
4000             OPERATION_SET_GLOBAL_PRIVATE_DNS,
4001             OPERATION_SET_LOGOUT_ENABLED,
4002             OPERATION_SET_MASTER_VOLUME_MUTED,
4003             OPERATION_SET_OVERRIDE_APNS_ENABLED,
4004             OPERATION_SET_PERMISSION_GRANT_STATE,
4005             OPERATION_SET_PERMISSION_POLICY,
4006             OPERATION_SET_RESTRICTIONS_PROVIDER,
4007             OPERATION_UNINSTALL_CA_CERT,
4008             OPERATION_SET_CONTENT_PROTECTION_POLICY
4009     })
4010     @Retention(RetentionPolicy.SOURCE)
4011     public static @interface DevicePolicyOperation {
4012     }
4013 
4014     /** @hide */
4015     @TestApi
4016     @NonNull
operationToString(@evicePolicyOperation int operation)4017     public static String operationToString(@DevicePolicyOperation int operation) {
4018         return DebugUtils.constantToString(DevicePolicyManager.class, PREFIX_OPERATION, operation);
4019     }
4020 
4021     private static final String PREFIX_OPERATION_SAFETY_REASON = "OPERATION_SAFETY_REASON_";
4022 
4023     /** @hide */
4024     @IntDef(prefix = PREFIX_OPERATION_SAFETY_REASON, value = {
4025             OPERATION_SAFETY_REASON_NONE,
4026             OPERATION_SAFETY_REASON_DRIVING_DISTRACTION
4027     })
4028     @Retention(RetentionPolicy.SOURCE)
4029     public static @interface OperationSafetyReason {
4030     }
4031 
4032     /** @hide */
4033     @TestApi
4034     public static final int OPERATION_SAFETY_REASON_NONE = -1;
4035 
4036     /**
4037      * Indicates that a {@link UnsafeStateException} was thrown because the operation would distract
4038      * the driver of the vehicle.
4039      */
4040     public static final int OPERATION_SAFETY_REASON_DRIVING_DISTRACTION = 1;
4041 
4042     /**
4043      * Prevent an app from being suspended.
4044      *
4045      * @hide
4046      */
4047     @SystemApi
4048     public static final int EXEMPT_FROM_SUSPENSION =  0;
4049 
4050     /**
4051      * Prevent an app from dismissible notifications. Starting from Android U, notifications with
4052      * the ongoing parameter can be dismissed by a user on an unlocked device. An app with
4053      * this exemption can create non-dismissible notifications.
4054      *
4055      * @hide
4056      */
4057     @SystemApi
4058     public static final int EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS =  1;
4059 
4060     /**
4061      * Allows an application to start an activity while running in the background.
4062      *
4063      * @hide
4064      */
4065     @SystemApi
4066     public static final int EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION = 2;
4067 
4068     /**
4069      * Prevent an app from entering hibernation.
4070      *
4071      * @hide
4072      */
4073     @SystemApi
4074     public static final int EXEMPT_FROM_HIBERNATION =  3;
4075 
4076     /**
4077      * Exempt an app from all power-related restrictions, including app standby and doze.
4078      * In addition, the app will be able to start foreground services from the background,
4079      * and the user will not be able to stop foreground services run by the app.
4080      *
4081      * @hide
4082      */
4083     @SystemApi
4084     public static final int EXEMPT_FROM_POWER_RESTRICTIONS =  4;
4085 
4086     /**
4087      * Exemptions to platform restrictions, given to an application through
4088      * {@link #setApplicationExemptions(String, Set)}.
4089      *
4090      * @hide
4091      */
4092     @IntDef(prefix = { "EXEMPT_FROM_"}, value = {
4093             EXEMPT_FROM_SUSPENSION,
4094             EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS,
4095             EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION,
4096             EXEMPT_FROM_HIBERNATION,
4097             EXEMPT_FROM_POWER_RESTRICTIONS
4098     })
4099     @Retention(RetentionPolicy.SOURCE)
4100     public @interface ApplicationExemptionConstants {}
4101 
4102     /**
4103      * Broadcast action: notify system apps (e.g. settings, SysUI, etc) that the device management
4104      * resources with IDs {@link #EXTRA_RESOURCE_IDS} has been updated, the updated resources can be
4105      * retrieved using {@link DevicePolicyResourcesManager#getDrawable} and
4106      * {@link DevicePolicyResourcesManager#getString}.
4107      *
4108      * <p>This broadcast is sent to registered receivers only.
4109      *
4110      * <p> {@link #EXTRA_RESOURCE_TYPE} will be included to identify the type of resource being
4111      * updated.
4112      */
4113     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4114     public static final String ACTION_DEVICE_POLICY_RESOURCE_UPDATED =
4115             "android.app.action.DEVICE_POLICY_RESOURCE_UPDATED";
4116 
4117     /**
4118      * An {@code int} extra for {@link #ACTION_DEVICE_POLICY_RESOURCE_UPDATED} to indicate the type
4119      * of the resource being updated, the type can be {@link #EXTRA_RESOURCE_TYPE_DRAWABLE} or
4120      * {@link #EXTRA_RESOURCE_TYPE_STRING}
4121      */
4122     public static final String EXTRA_RESOURCE_TYPE =
4123             "android.app.extra.RESOURCE_TYPE";
4124 
4125     /**
4126      * A {@code int} value for {@link #EXTRA_RESOURCE_TYPE} to indicate that a resource of type
4127      * {@link Drawable} is being updated.
4128      */
4129     public static final int EXTRA_RESOURCE_TYPE_DRAWABLE = 1;
4130 
4131     /**
4132      * A {@code int} value for {@link #EXTRA_RESOURCE_TYPE} to indicate that a resource of type
4133      * {@link String} is being updated.
4134      */
4135     public static final int EXTRA_RESOURCE_TYPE_STRING = 2;
4136 
4137     /**
4138      * An integer array extra for {@link #ACTION_DEVICE_POLICY_RESOURCE_UPDATED} to indicate which
4139      * resource IDs (i.e. strings and drawables) have been updated.
4140      */
4141     public static final String EXTRA_RESOURCE_IDS =
4142             "android.app.extra.RESOURCE_IDS";
4143 
4144     /**
4145      * Broadcast Action: Broadcast sent to indicate that the device financing state has changed.
4146      *
4147      * <p>This occurs when, for example, a financing kiosk app has been added or removed.
4148      *
4149      * <p>To query the current device financing state see {@link #isDeviceFinanced}.
4150      *
4151      * <p>This will be delivered to the following apps if they include a receiver for this action
4152      * in their manifest:
4153      * <ul>
4154      *     <li>Device owner admins.
4155      *     <li>Organization-owned profile owner admins
4156      *     <li>The supervision app
4157      *     <li>The device management role holder
4158      * </ul>
4159      */
4160     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
4161     @BroadcastBehavior(explicitOnly = true, includeBackground = true)
4162     public static final String ACTION_DEVICE_FINANCING_STATE_CHANGED =
4163             "android.app.admin.action.DEVICE_FINANCING_STATE_CHANGED";
4164 
4165     /** Allow the user to choose whether to enable MTE on the device. */
4166     public static final int MTE_NOT_CONTROLLED_BY_POLICY = 0;
4167 
4168     /**
4169      * Require that MTE be enabled on the device, if supported. Can be set by a device owner or a
4170      * profile owner of an organization-owned managed profile.
4171      */
4172     public static final int MTE_ENABLED = 1;
4173 
4174     /** Require that MTE be disabled on the device. Can be set by a device owner. */
4175     public static final int MTE_DISABLED = 2;
4176 
4177     /** @hide */
4178     @IntDef(
4179             prefix = {"MTE_"},
4180             value = {MTE_ENABLED, MTE_DISABLED, MTE_NOT_CONTROLLED_BY_POLICY})
4181     @Retention(RetentionPolicy.SOURCE)
4182     public static @interface MtePolicy {}
4183 
4184     /**
4185      * Called by a device owner, profile owner of an organization-owned device, to set the Memory
4186      * Tagging Extension (MTE) policy. MTE is a CPU extension that allows to protect against certain
4187      * classes of security problems at a small runtime performance cost overhead.
4188      *
4189      * <p>The MTE policy can only be set to {@link #MTE_DISABLED} if called by a device owner.
4190      * Otherwise a {@link SecurityException} will be thrown.
4191      *
4192      * <p>The device needs to be rebooted to apply changes to the MTE policy.
4193      *
4194      * @throws SecurityException if caller is not permitted to set Mte policy
4195      * @throws UnsupportedOperationException if the device does not support MTE
4196      * @param policy the MTE policy to be set
4197      */
4198     @RequiresPermission(value = MANAGE_DEVICE_POLICY_MTE, conditional = true)
setMtePolicy(@tePolicy int policy)4199     public void setMtePolicy(@MtePolicy int policy) {
4200         throwIfParentInstance("setMtePolicy");
4201         if (mService != null) {
4202             try {
4203                 mService.setMtePolicy(policy, mContext.getPackageName());
4204             } catch (RemoteException e) {
4205                 throw e.rethrowFromSystemServer();
4206             }
4207         }
4208     }
4209 
4210     /**
4211      * Called by a device owner, profile owner of an organization-owned device to
4212      * get the Memory Tagging Extension (MTE) policy
4213      *
4214      * <a href="https://source.android.com/docs/security/test/memory-safety/arm-mte">
4215      * Learn more about MTE</a>
4216      *
4217      * @throws SecurityException if caller is not permitted to set Mte policy
4218      * @return the currently set MTE policy
4219      */
4220     @RequiresPermission(value = MANAGE_DEVICE_POLICY_MTE, conditional = true)
getMtePolicy()4221     public @MtePolicy int getMtePolicy() {
4222         throwIfParentInstance("setMtePolicy");
4223         if (mService != null) {
4224             try {
4225                 return mService.getMtePolicy(mContext.getPackageName());
4226             } catch (RemoteException e) {
4227                 throw e.rethrowFromSystemServer();
4228             }
4229         }
4230         return MTE_NOT_CONTROLLED_BY_POLICY;
4231     }
4232 
4233     /**
4234      * Get the current MTE state of the device.
4235      *
4236      * <a href="https://source.android.com/docs/security/test/memory-safety/arm-mte">
4237      * Learn more about MTE</a>
4238      *
4239      * @return whether MTE is currently enabled on the device.
4240      */
4241     @FlaggedApi(FLAG_IS_MTE_POLICY_ENFORCED)
isMtePolicyEnforced()4242     public static boolean isMtePolicyEnforced() {
4243         return Zygote.nativeSupportsMemoryTagging();
4244     }
4245 
4246     /** Indicates that content protection is not controlled by policy, allowing user to choose. */
4247     @FlaggedApi(android.view.contentprotection.flags.Flags.FLAG_MANAGE_DEVICE_POLICY_ENABLED)
4248     public static final int CONTENT_PROTECTION_NOT_CONTROLLED_BY_POLICY = 0;
4249 
4250     /** Indicates that content protection is controlled and disabled by a policy (default). */
4251     @FlaggedApi(android.view.contentprotection.flags.Flags.FLAG_MANAGE_DEVICE_POLICY_ENABLED)
4252     public static final int CONTENT_PROTECTION_DISABLED = 1;
4253 
4254     /** Indicates that content protection is controlled and enabled by a policy. */
4255     @FlaggedApi(android.view.contentprotection.flags.Flags.FLAG_MANAGE_DEVICE_POLICY_ENABLED)
4256     public static final int CONTENT_PROTECTION_ENABLED = 2;
4257 
4258     /** @hide */
4259     @IntDef(
4260             prefix = {"CONTENT_PROTECTION_"},
4261             value = {
4262                 CONTENT_PROTECTION_NOT_CONTROLLED_BY_POLICY,
4263                 CONTENT_PROTECTION_DISABLED,
4264                 CONTENT_PROTECTION_ENABLED,
4265             })
4266     @Retention(RetentionPolicy.SOURCE)
4267     public @interface ContentProtectionPolicy {}
4268 
4269     /**
4270      * Sets the content protection policy which controls scanning for deceptive apps.
4271      * <p>
4272      * This function can only be called by the device owner, a profile owner of an affiliated user
4273      * or profile, or the profile owner when no device owner is set or holders of the permission
4274      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CONTENT_PROTECTION}. See
4275      * {@link #isAffiliatedUser}.
4276      * Any policy set via this method will be cleared if the user becomes unaffiliated.
4277      * <p>
4278      * After the content protection policy has been set,
4279      * {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, Bundle, TargetUser,
4280      * PolicyUpdateResult)} will notify the admin on whether the policy was successfully set or not.
4281      * This callback will contain:
4282      * <ul>
4283      * <li> The policy identifier {@link DevicePolicyIdentifiers#CONTENT_PROTECTION_POLICY}
4284      * <li> The {@link TargetUser} that this policy relates to
4285      * <li> The {@link PolicyUpdateResult}, which will be
4286      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
4287      * reason the policy failed to be set
4288      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
4289      * </ul>
4290      * If there has been a change to the policy,
4291      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
4292      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
4293      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
4294      * will contain the reason why the policy changed.
4295      *
4296      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
4297      *               caller is not a device admin.
4298      * @param policy The content protection policy to set. One of {@link
4299      *               #CONTENT_PROTECTION_NOT_CONTROLLED_BY_POLICY},
4300      *               {@link #CONTENT_PROTECTION_DISABLED} or {@link #CONTENT_PROTECTION_ENABLED}.
4301      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
4302      * affiliated user or profile, or the profile owner when no device owner is set or holder of the
4303      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CONTENT_PROTECTION}.
4304      * @see #isAffiliatedUser
4305      */
4306     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CONTENT_PROTECTION, conditional = true)
4307     @SupportsCoexistence
4308     @FlaggedApi(android.view.contentprotection.flags.Flags.FLAG_MANAGE_DEVICE_POLICY_ENABLED)
setContentProtectionPolicy( @ullable ComponentName admin, @ContentProtectionPolicy int policy)4309     public void setContentProtectionPolicy(
4310             @Nullable ComponentName admin, @ContentProtectionPolicy int policy) {
4311         throwIfParentInstance("setContentProtectionPolicy");
4312         if (mService != null) {
4313             try {
4314                 mService.setContentProtectionPolicy(admin, mContext.getPackageName(), policy);
4315             } catch (RemoteException e) {
4316                 throw e.rethrowFromSystemServer();
4317             }
4318         }
4319     }
4320 
4321     /**
4322      * Returns the current content protection policy.
4323      * <p>
4324      * The returned policy will be the current resolved policy rather than the policy set by the
4325      * calling admin.
4326      *
4327      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
4328      *              caller is not a device admin.
4329      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
4330      * affiliated user or profile, or the profile owner when no device owner is set or holder of the
4331      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CONTENT_PROTECTION}.
4332      * @see #isAffiliatedUser
4333      * @see #setContentProtectionPolicy
4334      */
4335     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CONTENT_PROTECTION, conditional = true)
4336     @FlaggedApi(android.view.contentprotection.flags.Flags.FLAG_MANAGE_DEVICE_POLICY_ENABLED)
getContentProtectionPolicy(@ullable ComponentName admin)4337     public @ContentProtectionPolicy int getContentProtectionPolicy(@Nullable ComponentName admin) {
4338         throwIfParentInstance("getContentProtectionPolicy");
4339         if (mService != null) {
4340             try {
4341                 return mService.getContentProtectionPolicy(admin, mContext.getPackageName());
4342             } catch (RemoteException e) {
4343                 throw e.rethrowFromSystemServer();
4344             }
4345         }
4346         return CONTENT_PROTECTION_DISABLED;
4347     }
4348 
4349     /**
4350      * This object is a single place to tack on invalidation and disable calls.  All
4351      * binder caches in this class derive from this Config, so all can be invalidated or
4352      * disabled through this Config.
4353      */
4354     private static final IpcDataCache.Config sDpmCaches =
4355             new IpcDataCache.Config(8, IpcDataCache.MODULE_SYSTEM, "DevicePolicyManagerCaches");
4356 
4357     /** @hide */
invalidateBinderCaches()4358     public static void invalidateBinderCaches() {
4359         sDpmCaches.invalidateCache();
4360     }
4361 
4362     /** @hide */
disableLocalCaches()4363     public static void disableLocalCaches() {
4364         sDpmCaches.disableAllForCurrentProcess();
4365     }
4366 
4367     /** @hide */
4368     @NonNull
4369     @TestApi
operationSafetyReasonToString(@perationSafetyReason int reason)4370     public static String operationSafetyReasonToString(@OperationSafetyReason int reason) {
4371         return DebugUtils.constantToString(DevicePolicyManager.class,
4372                 PREFIX_OPERATION_SAFETY_REASON, reason);
4373     }
4374 
4375     /** @hide */
isValidOperationSafetyReason(@perationSafetyReason int reason)4376     public static boolean isValidOperationSafetyReason(@OperationSafetyReason int reason) {
4377         return reason == OPERATION_SAFETY_REASON_DRIVING_DISTRACTION;
4378     }
4379 
4380     /**
4381      * Checks if it's safe to run operations that can be affected by the given {@code reason}.
4382      *
4383      * <p><b>Note:</b> notice that the operation safety state might change between the time this
4384      * method returns and the operation's method is called, so calls to the latter could still throw
4385      * a {@link UnsafeStateException} even when this method returns {@code true}.
4386      *
4387      * @param reason currently, only supported reason is
4388      * {@link #OPERATION_SAFETY_REASON_DRIVING_DISTRACTION}.
4389      *
4390      * @return whether it's safe to run operations that can be affected by the given {@code reason}.
4391      */
4392     // TODO(b/173541467): should it throw SecurityException if caller is not admin?
isSafeOperation(@perationSafetyReason int reason)4393     public boolean isSafeOperation(@OperationSafetyReason int reason) {
4394         throwIfParentInstance("isSafeOperation");
4395         if (mService == null) return false;
4396 
4397         try {
4398             return mService.isSafeOperation(reason);
4399         } catch (RemoteException e) {
4400             throw e.rethrowFromSystemServer();
4401         }
4402     }
4403 
4404     /**
4405      * Acknoledges that the new managed user disclaimer was viewed by the (human) user
4406      * so that {@link #ACTION_SHOW_NEW_USER_DISCLAIMER broadcast} is not sent again the next time
4407      * this user is switched to.
4408      *
4409      * @hide
4410      */
4411     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
4412             android.Manifest.permission.INTERACT_ACROSS_USERS})
4413     @UserHandleAware
4414     @TestApi
4415     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
acknowledgeNewUserDisclaimer()4416     public void acknowledgeNewUserDisclaimer() {
4417         if (mService != null) {
4418             try {
4419                 mService.acknowledgeNewUserDisclaimer(mContext.getUserId());
4420             } catch (RemoteException e) {
4421                 throw e.rethrowFromSystemServer();
4422             }
4423         }
4424     }
4425 
4426     /**
4427      * Checks whether the new managed user disclaimer was viewed by the user.
4428      *
4429      * @hide
4430      */
4431     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
4432             android.Manifest.permission.INTERACT_ACROSS_USERS})
4433     @TestApi
4434     @UserHandleAware
isNewUserDisclaimerAcknowledged()4435     public boolean isNewUserDisclaimerAcknowledged() {
4436         if (mService != null) {
4437             try {
4438                 return mService.isNewUserDisclaimerAcknowledged(mContext.getUserId());
4439             } catch (RemoteException e) {
4440                 throw e.rethrowFromSystemServer();
4441             }
4442         }
4443         return false;
4444     }
4445 
4446     /**
4447      * Return true if the given administrator component is currently active (enabled) in the system.
4448      *
4449      * @param admin The administrator component to check for.
4450      * @return {@code true} if {@code admin} is currently enabled in the system, {@code false}
4451      *         otherwise
4452      */
isAdminActive(@onNull ComponentName admin)4453     public boolean isAdminActive(@NonNull ComponentName admin) {
4454         throwIfParentInstance("isAdminActive");
4455         return isAdminActiveAsUser(admin, myUserId());
4456     }
4457 
4458     /**
4459      * @see #isAdminActive(ComponentName)
4460      * @hide
4461      */
isAdminActiveAsUser(@onNull ComponentName admin, int userId)4462     public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
4463         if (mService != null) {
4464             try {
4465                 return mService.isAdminActive(admin, userId);
4466             } catch (RemoteException e) {
4467                 throw e.rethrowFromSystemServer();
4468             }
4469         }
4470         return false;
4471     }
4472 
4473     /**
4474      * Return true if the given administrator component is currently being removed
4475      * for the user.
4476      * @hide
4477      */
4478     @TestApi
isRemovingAdmin(@onNull ComponentName admin, int userId)4479     public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
4480         if (mService != null) {
4481             try {
4482                 return mService.isRemovingAdmin(admin, userId);
4483             } catch (RemoteException e) {
4484                 throw e.rethrowFromSystemServer();
4485             }
4486         }
4487         return false;
4488     }
4489 
4490     /**
4491      * Return a list of all currently active device administrators' component
4492      * names.  If there are no administrators {@code null} may be
4493      * returned.
4494      */
getActiveAdmins()4495     public @Nullable List<ComponentName> getActiveAdmins() {
4496         throwIfParentInstance("getActiveAdmins");
4497         return getActiveAdminsAsUser(myUserId());
4498     }
4499 
4500     /**
4501      * @see #getActiveAdmins()
4502      * @hide
4503      */
4504     @UnsupportedAppUsage
getActiveAdminsAsUser(int userId)4505     public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) {
4506         if (mService != null) {
4507             try {
4508                 return mService.getActiveAdmins(userId);
4509             } catch (RemoteException e) {
4510                 throw e.rethrowFromSystemServer();
4511             }
4512         }
4513         return null;
4514     }
4515 
4516     /**
4517      * Used by package administration code to determine if a package can be stopped
4518      * or uninstalled.
4519      * @hide
4520      */
4521     @SystemApi
4522     @RequiresPermission(INTERACT_ACROSS_USERS_FULL)
packageHasActiveAdmins(String packageName)4523     public boolean packageHasActiveAdmins(String packageName) {
4524         return packageHasActiveAdmins(packageName, myUserId());
4525     }
4526 
4527     /**
4528      * Used by package administration code to determine if a package can be stopped
4529      * or uninstalled.
4530      * @hide
4531      */
4532     @UnsupportedAppUsage
packageHasActiveAdmins(String packageName, int userId)4533     public boolean packageHasActiveAdmins(String packageName, int userId) {
4534         if (mService != null) {
4535             try {
4536                 return mService.packageHasActiveAdmins(packageName, userId);
4537             } catch (RemoteException e) {
4538                 throw e.rethrowFromSystemServer();
4539             }
4540         }
4541         return false;
4542     }
4543 
4544     /**
4545      * Remove a current administration component.  This can only be called
4546      * by the application that owns the administration component; if you
4547      * try to remove someone else's component, a security exception will be
4548      * thrown.
4549      *
4550      * <p>Note that the operation is not synchronous and the admin might still be active (as
4551      * indicated by {@link #getActiveAdmins()}) by the time this method returns.
4552      *
4553      * @param admin The administration compononent to remove.
4554      * @throws SecurityException if the caller is not in the owner application of {@code admin}.
4555      */
removeActiveAdmin(@onNull ComponentName admin)4556     public void removeActiveAdmin(@NonNull ComponentName admin) {
4557         throwIfParentInstance("removeActiveAdmin");
4558         if (mService != null) {
4559             try {
4560                 mService.removeActiveAdmin(admin, myUserId());
4561             } catch (RemoteException e) {
4562                 throw e.rethrowFromSystemServer();
4563             }
4564         }
4565     }
4566 
4567     /**
4568      * Returns true if an administrator has been granted a particular device policy. This can be
4569      * used to check whether the administrator was activated under an earlier set of policies, but
4570      * requires additional policies after an upgrade.
4571      *
4572      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be an
4573      *            active administrator, or an exception will be thrown.
4574      * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
4575      * @throws SecurityException if {@code admin} is not an active administrator.
4576      */
hasGrantedPolicy(@onNull ComponentName admin, int usesPolicy)4577     public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) {
4578         throwIfParentInstance("hasGrantedPolicy");
4579         if (mService != null) {
4580             try {
4581                 return mService.hasGrantedPolicy(admin, usesPolicy, myUserId());
4582             } catch (RemoteException e) {
4583                 throw e.rethrowFromSystemServer();
4584             }
4585         }
4586         return false;
4587     }
4588 
4589     /**
4590      * Constant for {@link #setPasswordQuality}: the policy has no requirements
4591      * for the password.  Note that quality constants are ordered so that higher
4592      * values are more restrictive.
4593      */
4594     public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
4595 
4596     /**
4597      * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
4598      * recognition technology.  This implies technologies that can recognize the identity of
4599      * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
4600      * Note that quality constants are ordered so that higher values are more restrictive.
4601      */
4602     public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
4603 
4604     /**
4605      * Constant for {@link #setPasswordQuality}: the policy requires some kind
4606      * of password or pattern, but doesn't care what it is. Note that quality constants
4607      * are ordered so that higher values are more restrictive.
4608      */
4609     public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
4610 
4611     /**
4612      * Constant for {@link #setPasswordQuality}: the user must have entered a
4613      * password containing at least numeric characters.  Note that quality
4614      * constants are ordered so that higher values are more restrictive.
4615      */
4616     public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
4617 
4618     /**
4619      * Constant for {@link #setPasswordQuality}: the user must have entered a
4620      * password containing at least numeric characters with no repeating (4444)
4621      * or ordered (1234, 4321, 2468) sequences.  Note that quality
4622      * constants are ordered so that higher values are more restrictive.
4623      */
4624     public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
4625 
4626     /**
4627      * Constant for {@link #setPasswordQuality}: the user must have entered a
4628      * password containing at least alphabetic (or other symbol) characters.
4629      * Note that quality constants are ordered so that higher values are more
4630      * restrictive.
4631      */
4632     public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
4633 
4634     /**
4635      * Constant for {@link #setPasswordQuality}: the user must have entered a
4636      * password containing at least <em>both></em> numeric <em>and</em>
4637      * alphabetic (or other symbol) characters.  Note that quality constants are
4638      * ordered so that higher values are more restrictive.
4639      */
4640     public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
4641 
4642     /**
4643      * Constant for {@link #setPasswordQuality}: allows the admin to set precisely how many
4644      * characters of various types the password should contain to satisfy the policy. The admin
4645      * should set these requirements via {@link #setPasswordMinimumLetters},
4646      * {@link #setPasswordMinimumNumeric}, {@link #setPasswordMinimumSymbols},
4647      * {@link #setPasswordMinimumUpperCase}, {@link #setPasswordMinimumLowerCase},
4648      * {@link #setPasswordMinimumNonLetter}, and {@link #setPasswordMinimumLength}.
4649      * Note that quality constants are ordered so that higher values are more restrictive.
4650      */
4651     public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
4652 
4653     /**
4654      * Constant for {@link #setPasswordQuality}: the user is not allowed to
4655      * modify password. In case this password quality is set, the password is
4656      * managed by a profile owner. The profile owner can set any password,
4657      * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note
4658      * that quality constants are ordered so that higher values are more
4659      * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is
4660      * the highest.
4661      * @hide
4662      */
4663     public static final int PASSWORD_QUALITY_MANAGED = 0x80000;
4664 
4665     /**
4666      * @hide
4667      *
4668      * adb shell dpm set-{device,profile}-owner will normally not allow installing an owner to
4669      * a user with accounts.  {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED}
4670      * and {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} are the account features
4671      * used by authenticator to exempt their accounts from this:
4672      *
4673      * <ul>
4674      *     <li>Non-test-only DO/PO still can't be installed when there are accounts.
4675      *     <p>In order to make an apk test-only, add android:testOnly="true" to the
4676      *     &lt;application&gt; tag in the manifest.
4677      *
4678      *     <li>Test-only DO/PO can be installed even when there are accounts, as long as all the
4679      *     accounts have the {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} feature.
4680      *     Some authenticators claim to have any features, so to detect it, we also check
4681      *     {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} and disallow installing
4682      *     if any of the accounts have it.
4683      * </ul>
4684      */
4685     @SystemApi
4686     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED =
4687             "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED";
4688 
4689     /** @hide See {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} */
4690     @SystemApi
4691     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED =
4692             "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED";
4693 
4694     /**
4695      * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
4696      * manifest element, which declares that the module should be considered a required app for
4697      * managed users.
4698      * <p>Being declared as a required app prevents removal of this package during the
4699      * provisioning process.
4700      * @hide
4701      */
4702     @SystemApi
4703     public static final String REQUIRED_APP_MANAGED_USER = "android.app.REQUIRED_APP_MANAGED_USER";
4704 
4705     /**
4706      * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
4707      * manifest element, which declares that the module should be considered a required app for
4708      * managed devices.
4709      * <p>Being declared as a required app prevents removal of this package during the
4710      * provisioning process.
4711      * @hide
4712      */
4713     @SystemApi
4714     public static final String REQUIRED_APP_MANAGED_DEVICE =
4715             "android.app.REQUIRED_APP_MANAGED_DEVICE";
4716 
4717     /**
4718      * A {@code boolean} metadata to be included in a mainline module's {@code <application>}
4719      * manifest element, which declares that the module should be considered a required app for
4720      * managed profiles.
4721      * <p>Being declared as a required app prevents removal of this package during the
4722      * provisioning process.
4723      * @hide
4724      */
4725     @SystemApi
4726     public static final String REQUIRED_APP_MANAGED_PROFILE =
4727             "android.app.REQUIRED_APP_MANAGED_PROFILE";
4728 
4729     /**
4730      * Called by an application that is administering the device to set the password restrictions it
4731      * is imposing. After setting this, the user will not be able to enter a new password that is
4732      * not at least as restrictive as what has been set. Note that the current password will remain
4733      * until the user has set a new one, so the change does not take place immediately. To prompt
4734      * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
4735      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after calling this method.
4736      * <p>
4737      * Quality constants are ordered so that higher values are more restrictive; thus the highest
4738      * requested quality constant (between the policy set here, the user's preference, and any other
4739      * considerations) is the one that is in effect.
4740      * <p>
4741      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4742      * password is always treated as empty.
4743      * <p>
4744      * The calling device admin must have requested
4745      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4746      * not, a security exception will be thrown.
4747      * <p>
4748      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4749      * {@link DevicePolicyManager} instance returned by
4750      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4751      * profile. Apps targeting {@link android.os.Build.VERSION_CODES#S} and above, with the
4752      * exception of a profile owner on an organization-owned device (as can be identified by
4753      * {@link #isOrganizationOwnedDeviceWithManagedProfile}), will get a
4754      * {@code IllegalArgumentException} when calling this method on the parent
4755      * {@link DevicePolicyManager} instance.
4756      *
4757      * <p><strong>Note:</strong> Specifying password requirements using this method clears the
4758      * password complexity requirements set using {@link #setRequiredPasswordComplexity(int)}.
4759      * If this method is called on the {@link DevicePolicyManager} instance returned by
4760      * {@link #getParentProfileInstance(ComponentName)}, then password complexity requirements
4761      * set on the primary {@link DevicePolicyManager} must be cleared first by calling
4762      * {@link #setRequiredPasswordComplexity} with {@link #PASSWORD_COMPLEXITY_NONE) first.
4763      *
4764      * <p><string>Note:</strong> this method is ignored on
4765      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4766      *
4767      * @deprecated Prefer using {@link #setRequiredPasswordComplexity(int)}, to require a password
4768      * that satisfies a complexity level defined by the platform, rather than specifying custom
4769      * password requirement.
4770      * Setting custom, overly-complicated password requirements leads to passwords that are hard
4771      * for users to remember and may not provide any security benefits given as Android uses
4772      * hardware-backed throttling to thwart online and offline brute-forcing of the device's
4773      * screen lock. Company-owned devices (fully-managed and organization-owned managed profile
4774      * devices) are able to continue using this method, though it is recommended that
4775      * {@link #setRequiredPasswordComplexity(int)} should be used instead.
4776      *
4777      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4778      * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED},
4779      *            {@link #PASSWORD_QUALITY_BIOMETRIC_WEAK},
4780      *            {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC},
4781      *            {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
4782      *            {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
4783      * @throws SecurityException if {@code admin} is not an active administrator, if {@code admin}
4784      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} or if the
4785      *             calling app is targeting {@link android.os.Build.VERSION_CODES#S} and above,
4786      *             and is calling the method the {@link DevicePolicyManager} instance returned by
4787      *             {@link #getParentProfileInstance(ComponentName)}.
4788      * @throws IllegalStateException if the caller is trying to set password quality on the parent
4789      *             {@link DevicePolicyManager} instance while password complexity was set on the
4790      *             primary {@link DevicePolicyManager} instance.
4791      */
4792     @Deprecated
setPasswordQuality(@onNull ComponentName admin, int quality)4793     public void setPasswordQuality(@NonNull ComponentName admin, int quality) {
4794         if (mService != null) {
4795             try {
4796                 mService.setPasswordQuality(admin, quality, mParentInstance);
4797             } catch (RemoteException e) {
4798                 throw e.rethrowFromSystemServer();
4799             }
4800         }
4801     }
4802 
4803     /**
4804      * Retrieve the current minimum password quality for a particular admin or all admins that set
4805      * restrictions on this user and its participating profiles. Restrictions on profiles that have
4806      * a separate challenge are not taken into account.
4807      *
4808      * <p>This method can be called on the {@link DevicePolicyManager} instance
4809      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4810      * restrictions on the parent profile.
4811      *
4812      * <p>Note: on devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
4813      * the password is always treated as empty.
4814      *
4815      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4816      *
4817      * @param admin The name of the admin component to check, or {@code null} to aggregate
4818      * all admins.
4819      */
4820     @Deprecated
getPasswordQuality(@ullable ComponentName admin)4821     public int getPasswordQuality(@Nullable ComponentName admin) {
4822         return getPasswordQuality(admin, myUserId());
4823     }
4824 
4825     /** @hide per-user version */
4826     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordQuality(@ullable ComponentName admin, int userHandle)4827     public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) {
4828         if (mService != null) {
4829             try {
4830                 return mService.getPasswordQuality(admin, userHandle, mParentInstance);
4831             } catch (RemoteException e) {
4832                 throw e.rethrowFromSystemServer();
4833             }
4834         }
4835         return PASSWORD_QUALITY_UNSPECIFIED;
4836     }
4837 
4838     /**
4839      * Called by an application that is administering the device to set the minimum allowed password
4840      * length. After setting this, the user will not be able to enter a new password that is not at
4841      * least as restrictive as what has been set. Note that the current password will remain until
4842      * the user has set a new one, so the change does not take place immediately. To prompt the user
4843      * for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
4844      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
4845      * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
4846      * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
4847      * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with
4848      * {@link #setPasswordQuality}. If an app targeting SDK level
4849      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
4850      * password quality to one of these values first, this method will throw
4851      * {@link IllegalStateException}.
4852      * <p>
4853      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4854      * password is always treated as empty.
4855      * <p>
4856      * The calling device admin must have requested
4857      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4858      * not, a security exception will be thrown.
4859      * <p>
4860      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4861      * {@link DevicePolicyManager} instance returned by
4862      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4863      * profile.
4864      *
4865      * <p><string>Note:</strong> this method is ignored on
4866      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4867      *
4868      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4869      *
4870      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4871      * @param length The new desired minimum password length. A value of 0 means there is no
4872      *     restriction.
4873      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4874      *     does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4875      * @throws IllegalStateException if the calling app is targeting SDK level
4876      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4877      *     quality requirement prior to calling this method.
4878      */
4879     @Deprecated
setPasswordMinimumLength(@onNull ComponentName admin, int length)4880     public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
4881         if (mService != null) {
4882             try {
4883                 mService.setPasswordMinimumLength(admin, length, mParentInstance);
4884             } catch (RemoteException e) {
4885                 throw e.rethrowFromSystemServer();
4886             }
4887         }
4888     }
4889 
4890     /**
4891      * Retrieve the current minimum password length for a particular admin or all admins that set
4892      * restrictions on this user and its participating profiles. Restrictions on profiles that have
4893      * a separate challenge are not taken into account.
4894      *
4895      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4896      * password is always treated as empty.
4897      *
4898      * <p>This method can be called on the {@link DevicePolicyManager} instance
4899      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4900      * restrictions on the parent profile.
4901      *
4902      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4903      *
4904      * @param admin The name of the admin component to check, or {@code null} to aggregate
4905      * all admins.
4906      */
4907     @Deprecated
getPasswordMinimumLength(@ullable ComponentName admin)4908     public int getPasswordMinimumLength(@Nullable ComponentName admin) {
4909         return getPasswordMinimumLength(admin, myUserId());
4910     }
4911 
4912     /** @hide per-user version */
4913     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLength(@ullable ComponentName admin, int userHandle)4914     public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) {
4915         if (mService != null) {
4916             try {
4917                 return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance);
4918             } catch (RemoteException e) {
4919                 throw e.rethrowFromSystemServer();
4920             }
4921         }
4922         return 0;
4923     }
4924 
4925     /**
4926      * Called by an application that is administering the device to set the minimum number of upper
4927      * case letters required in the password. After setting this, the user will not be able to enter
4928      * a new password that is not at least as restrictive as what has been set. Note that the
4929      * current password will remain until the user has set a new one, so the change does not take
4930      * place immediately. To prompt the user for a new password, use
4931      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
4932      * setting this value. This constraint is only imposed if the administrator has also requested
4933      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
4934      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
4935      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
4936      * {@link IllegalStateException}. The default value is 0.
4937      * <p>
4938      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4939      * password is always treated as empty.
4940      * <p>
4941      * The calling device admin must have requested
4942      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
4943      * not, a security exception will be thrown.
4944      * <p>
4945      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
4946      * {@link DevicePolicyManager} instance returned by
4947      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4948      * profile.
4949      *
4950      * <p><string>Note:</strong> this method is ignored on
4951      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
4952      *
4953      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4954      *
4955      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4956      * @param length The new desired minimum number of upper case letters required in the password.
4957      *            A value of 0 means there is no restriction.
4958      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
4959      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
4960      * @throws IllegalStateException if the calling app is targeting SDK level
4961      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
4962      *     quality requirement prior to calling this method.
4963      */
4964     @Deprecated
setPasswordMinimumUpperCase(@onNull ComponentName admin, int length)4965     public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
4966         if (mService != null) {
4967             try {
4968                 mService.setPasswordMinimumUpperCase(admin, length, mParentInstance);
4969             } catch (RemoteException e) {
4970                 throw e.rethrowFromSystemServer();
4971             }
4972         }
4973     }
4974 
4975     /**
4976      * Retrieve the current number of upper case letters required in the password
4977      * for a particular admin or all admins that set restrictions on this user and
4978      * its participating profiles. Restrictions on profiles that have a separate challenge
4979      * are not taken into account.
4980      * This is the same value as set by
4981      * {@link #setPasswordMinimumUpperCase(ComponentName, int)}
4982      * and only applies when the password quality is
4983      * {@link #PASSWORD_QUALITY_COMPLEX}.
4984      *
4985      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
4986      * password is always treated as empty.
4987      *
4988      * <p>This method can be called on the {@link DevicePolicyManager} instance
4989      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4990      * restrictions on the parent profile.
4991      *
4992      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
4993      *
4994      * @param admin The name of the admin component to check, or {@code null} to
4995      *            aggregate all admins.
4996      * @return The minimum number of upper case letters required in the
4997      *         password.
4998      */
4999     @Deprecated
getPasswordMinimumUpperCase(@ullable ComponentName admin)5000     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) {
5001         return getPasswordMinimumUpperCase(admin, myUserId());
5002     }
5003 
5004     /** @hide per-user version */
5005     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumUpperCase(@ullable ComponentName admin, int userHandle)5006     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) {
5007         if (mService != null) {
5008             try {
5009                 return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance);
5010             } catch (RemoteException e) {
5011                 throw e.rethrowFromSystemServer();
5012             }
5013         }
5014         return 0;
5015     }
5016 
5017     /**
5018      * Called by an application that is administering the device to set the minimum number of lower
5019      * case letters required in the password. After setting this, the user will not be able to enter
5020      * a new password that is not at least as restrictive as what has been set. Note that the
5021      * current password will remain until the user has set a new one, so the change does not take
5022      * place immediately. To prompt the user for a new password, use
5023      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
5024      * setting this value. This constraint is only imposed if the administrator has also requested
5025      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
5026      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
5027      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
5028      * {@link IllegalStateException}. The default value is 0.
5029      * <p>
5030      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5031      * password is always treated as empty.
5032      * <p>
5033      * The calling device admin must have requested
5034      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
5035      * not, a security exception will be thrown.
5036      * <p>
5037      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
5038      * {@link DevicePolicyManager} instance returned by
5039      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5040      * profile.
5041      *
5042      * <p><string>Note:</strong> this method is ignored on
5043      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
5044      *
5045      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
5046      *
5047      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5048      * @param length The new desired minimum number of lower case letters required in the password.
5049      *            A value of 0 means there is no restriction.
5050      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
5051      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
5052      * @throws IllegalStateException if the calling app is targeting SDK level
5053      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
5054      *     quality requirement prior to calling this method.
5055      */
5056     @Deprecated
setPasswordMinimumLowerCase(@onNull ComponentName admin, int length)5057     public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
5058         if (mService != null) {
5059             try {
5060                 mService.setPasswordMinimumLowerCase(admin, length, mParentInstance);
5061             } catch (RemoteException e) {
5062                 throw e.rethrowFromSystemServer();
5063             }
5064         }
5065     }
5066 
5067     /**
5068      * Retrieve the current number of lower case letters required in the password
5069      * for a particular admin or all admins that set restrictions on this user
5070      * and its participating profiles. Restrictions on profiles that have
5071      * a separate challenge are not taken into account.
5072      * This is the same value as set by
5073      * {@link #setPasswordMinimumLowerCase(ComponentName, int)}
5074      * and only applies when the password quality is
5075      * {@link #PASSWORD_QUALITY_COMPLEX}.
5076      *
5077      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5078      * password is always treated as empty.
5079      *
5080      * <p>This method can be called on the {@link DevicePolicyManager} instance
5081      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5082      * restrictions on the parent profile.
5083      *
5084      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
5085      *
5086      * @param admin The name of the admin component to check, or {@code null} to
5087      *            aggregate all admins.
5088      * @return The minimum number of lower case letters required in the
5089      *         password.
5090      */
5091     @Deprecated
getPasswordMinimumLowerCase(@ullable ComponentName admin)5092     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) {
5093         return getPasswordMinimumLowerCase(admin, myUserId());
5094     }
5095 
5096     /** @hide per-user version */
5097     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLowerCase(@ullable ComponentName admin, int userHandle)5098     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) {
5099         if (mService != null) {
5100             try {
5101                 return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance);
5102             } catch (RemoteException e) {
5103                 throw e.rethrowFromSystemServer();
5104             }
5105         }
5106         return 0;
5107     }
5108 
5109     /**
5110      * Called by an application that is administering the device to set the minimum number of
5111      * letters required in the password. After setting this, the user will not be able to enter a
5112      * new password that is not at least as restrictive as what has been set. Note that the current
5113      * password will remain until the user has set a new one, so the change does not take place
5114      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
5115      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
5116      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
5117      * {@link #setPasswordQuality}. If an app targeting SDK level
5118      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
5119      * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
5120      * {@link IllegalStateException}. The default value is 1.
5121      * <p>
5122      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5123      * password is always treated as empty.
5124      * <p>
5125      * The calling device admin must have requested
5126      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
5127      * not, a security exception will be thrown.
5128      * <p>
5129      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
5130      * {@link DevicePolicyManager} instance returned by
5131      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5132      * profile.
5133      *
5134      * <p><string>Note:</strong> this method is ignored on
5135      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
5136      *
5137      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
5138      *
5139      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5140      * @param length The new desired minimum number of letters required in the password. A value of
5141      *            0 means there is no restriction.
5142      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
5143      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
5144      * @throws IllegalStateException if the calling app is targeting SDK level
5145      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
5146      *     quality requirement prior to calling this method.
5147      */
5148     @Deprecated
setPasswordMinimumLetters(@onNull ComponentName admin, int length)5149     public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
5150         if (mService != null) {
5151             try {
5152                 mService.setPasswordMinimumLetters(admin, length, mParentInstance);
5153             } catch (RemoteException e) {
5154                 throw e.rethrowFromSystemServer();
5155             }
5156         }
5157     }
5158 
5159     /**
5160      * Retrieve the current number of letters required in the password
5161      * for a particular admin or all admins that set restrictions on this user
5162      * and its participating profiles. Restrictions on profiles that have
5163      * a separate challenge are not taken into account.
5164      * This is the same value as set by
5165      * {@link #setPasswordMinimumLetters(ComponentName, int)}
5166      * and only applies when the password quality is
5167      * {@link #PASSWORD_QUALITY_COMPLEX}.
5168      *
5169      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5170      * password is always treated as empty.
5171      *
5172      * <p>This method can be called on the {@link DevicePolicyManager} instance
5173      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5174      * restrictions on the parent profile.
5175      *
5176      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
5177      *
5178      * @param admin The name of the admin component to check, or {@code null} to
5179      *            aggregate all admins.
5180      * @return The minimum number of letters required in the password.
5181      */
5182     @Deprecated
getPasswordMinimumLetters(@ullable ComponentName admin)5183     public int getPasswordMinimumLetters(@Nullable ComponentName admin) {
5184         return getPasswordMinimumLetters(admin, myUserId());
5185     }
5186 
5187     /** @hide per-user version */
5188     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLetters(@ullable ComponentName admin, int userHandle)5189     public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) {
5190         if (mService != null) {
5191             try {
5192                 return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance);
5193             } catch (RemoteException e) {
5194                 throw e.rethrowFromSystemServer();
5195             }
5196         }
5197         return 0;
5198     }
5199 
5200     /**
5201      * Called by an application that is administering the device to set the minimum number of
5202      * numerical digits required in the password. After setting this, the user will not be able to
5203      * enter a new password that is not at least as restrictive as what has been set. Note that the
5204      * current password will remain until the user has set a new one, so the change does not take
5205      * place immediately. To prompt the user for a new password, use
5206      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
5207      * setting this value. This constraint is only imposed if the administrator has also requested
5208      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
5209      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
5210      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
5211      * {@link IllegalStateException}. The default value is 1.
5212      * <p>
5213      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5214      * password is always treated as empty.
5215      * <p>
5216      * The calling device admin must have requested
5217      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
5218      * not, a security exception will be thrown.
5219      * <p>
5220      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
5221      * {@link DevicePolicyManager} instance returned by
5222      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5223      * profile.
5224      *
5225      * <p><string>Note:</strong> this method is ignored on
5226      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
5227      *
5228      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
5229      *
5230      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5231      * @param length The new desired minimum number of numerical digits required in the password. A
5232      *            value of 0 means there is no restriction.
5233      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
5234      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
5235      * @throws IllegalStateException if the calling app is targeting SDK level
5236      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
5237      *     quality requirement prior to calling this method.
5238      */
5239     @Deprecated
setPasswordMinimumNumeric(@onNull ComponentName admin, int length)5240     public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
5241         if (mService != null) {
5242             try {
5243                 mService.setPasswordMinimumNumeric(admin, length, mParentInstance);
5244             } catch (RemoteException e) {
5245                 throw e.rethrowFromSystemServer();
5246             }
5247         }
5248     }
5249 
5250     /**
5251      * Retrieve the current number of numerical digits required in the password
5252      * for a particular admin or all admins that set restrictions on this user
5253      * and its participating profiles. Restrictions on profiles that have
5254      * a separate challenge are not taken into account.
5255      * This is the same value as set by
5256      * {@link #setPasswordMinimumNumeric(ComponentName, int)}
5257      * and only applies when the password quality is
5258      * {@link #PASSWORD_QUALITY_COMPLEX}.
5259      *
5260      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5261      * password is always treated as empty.
5262      *
5263      * <p>This method can be called on the {@link DevicePolicyManager} instance
5264      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5265      * restrictions on the parent profile.
5266      *
5267      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
5268      *
5269      * @param admin The name of the admin component to check, or {@code null} to
5270      *            aggregate all admins.
5271      * @return The minimum number of numerical digits required in the password.
5272      */
5273     @Deprecated
getPasswordMinimumNumeric(@ullable ComponentName admin)5274     public int getPasswordMinimumNumeric(@Nullable ComponentName admin) {
5275         return getPasswordMinimumNumeric(admin, myUserId());
5276     }
5277 
5278     /** @hide per-user version */
5279     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumNumeric(@ullable ComponentName admin, int userHandle)5280     public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) {
5281         if (mService != null) {
5282             try {
5283                 return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance);
5284             } catch (RemoteException e) {
5285                 throw e.rethrowFromSystemServer();
5286             }
5287         }
5288         return 0;
5289     }
5290 
5291     /**
5292      * Called by an application that is administering the device to set the minimum number of
5293      * symbols required in the password. After setting this, the user will not be able to enter a
5294      * new password that is not at least as restrictive as what has been set. Note that the current
5295      * password will remain until the user has set a new one, so the change does not take place
5296      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
5297      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
5298      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
5299      * {@link #setPasswordQuality}. If an app targeting SDK level
5300      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
5301      * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
5302      * {@link IllegalStateException}. The default value is 1.
5303      * <p>
5304      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5305      * password is always treated as empty.
5306      * <p>
5307      * The calling device admin must have requested
5308      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
5309      * not, a security exception will be thrown.
5310      * <p>
5311      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
5312      * {@link DevicePolicyManager} instance returned by
5313      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5314      * profile.
5315      *
5316      * <p><string>Note:</strong> this method is ignored on
5317      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
5318      *
5319      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
5320      *
5321      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5322      * @param length The new desired minimum number of symbols required in the password. A value of
5323      *            0 means there is no restriction.
5324      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
5325      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
5326      * @throws IllegalStateException if the calling app is targeting SDK level
5327      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
5328      *     quality requirement prior to calling this method.
5329      */
5330     @Deprecated
setPasswordMinimumSymbols(@onNull ComponentName admin, int length)5331     public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
5332         if (mService != null) {
5333             try {
5334                 mService.setPasswordMinimumSymbols(admin, length, mParentInstance);
5335             } catch (RemoteException e) {
5336                 throw e.rethrowFromSystemServer();
5337             }
5338         }
5339     }
5340 
5341     /**
5342      * Retrieve the current number of symbols required in the password
5343      * for a particular admin or all admins that set restrictions on this user
5344      * and its participating profiles. Restrictions on profiles that have
5345      * a separate challenge are not taken into account. This is the same value as
5346      * set by {@link #setPasswordMinimumSymbols(ComponentName, int)}
5347      * and only applies when the password quality is
5348      * {@link #PASSWORD_QUALITY_COMPLEX}.
5349      *
5350      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5351      * password is always treated as empty.
5352      *
5353      * <p>This method can be called on the {@link DevicePolicyManager} instance
5354      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5355      * restrictions on the parent profile.
5356      *
5357      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
5358      *
5359      * @param admin The name of the admin component to check, or {@code null} to
5360      *            aggregate all admins.
5361      * @return The minimum number of symbols required in the password.
5362      */
5363     @Deprecated
getPasswordMinimumSymbols(@ullable ComponentName admin)5364     public int getPasswordMinimumSymbols(@Nullable ComponentName admin) {
5365         return getPasswordMinimumSymbols(admin, myUserId());
5366     }
5367 
5368     /** @hide per-user version */
5369     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumSymbols(@ullable ComponentName admin, int userHandle)5370     public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) {
5371         if (mService != null) {
5372             try {
5373                 return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance);
5374             } catch (RemoteException e) {
5375                 throw e.rethrowFromSystemServer();
5376             }
5377         }
5378         return 0;
5379     }
5380 
5381     /**
5382      * Called by an application that is administering the device to set the minimum number of
5383      * non-letter characters (numerical digits or symbols) required in the password. After setting
5384      * this, the user will not be able to enter a new password that is not at least as restrictive
5385      * as what has been set. Note that the current password will remain until the user has set a new
5386      * one, so the change does not take place immediately. To prompt the user for a new password,
5387      * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
5388      * setting this value. This constraint is only imposed if the administrator has also requested
5389      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
5390      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
5391      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
5392      * {@link IllegalStateException}. The default value is 0.
5393      * <p>
5394      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5395      * password is always treated as empty.
5396      * <p>
5397      * The calling device admin must have requested
5398      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
5399      * not, a security exception will be thrown.
5400      * <p>
5401      * Apps targeting {@link android.os.Build.VERSION_CODES#R} and below can call this method on the
5402      * {@link DevicePolicyManager} instance returned by
5403      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5404      * profile.
5405      *
5406      * <p><string>Note:</strong> this method is ignored on
5407      * {PackageManager#FEATURE_AUTOMOTIVE automotive builds}.
5408      *
5409      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
5410      *
5411      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5412      * @param length The new desired minimum number of letters required in the password. A value of
5413      *            0 means there is no restriction.
5414      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
5415      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
5416      * @throws IllegalStateException if the calling app is targeting SDK level
5417      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
5418      *     quality requirement prior to calling this method.
5419      */
5420     @Deprecated
setPasswordMinimumNonLetter(@onNull ComponentName admin, int length)5421     public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
5422         if (mService != null) {
5423             try {
5424                 mService.setPasswordMinimumNonLetter(admin, length, mParentInstance);
5425             } catch (RemoteException e) {
5426                 throw e.rethrowFromSystemServer();
5427             }
5428         }
5429     }
5430 
5431     /**
5432      * Retrieve the current number of non-letter characters required in the password
5433      * for a particular admin or all admins that set restrictions on this user
5434      * and its participating profiles. Restrictions on profiles that have
5435      * a separate challenge are not taken into account.
5436      * This is the same value as set by
5437      * {@link #setPasswordMinimumNonLetter(ComponentName, int)}
5438      * and only applies when the password quality is
5439      * {@link #PASSWORD_QUALITY_COMPLEX}.
5440      *
5441      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5442      * password is always treated as empty.
5443      *
5444      * <p>This method can be called on the {@link DevicePolicyManager} instance
5445      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5446      * restrictions on the parent profile.
5447      *
5448      * @deprecated see {@link #setPasswordQuality(ComponentName, int)} for details.
5449      *
5450      * @param admin The name of the admin component to check, or {@code null} to
5451      *            aggregate all admins.
5452      * @return The minimum number of letters required in the password.
5453      */
5454     @Deprecated
getPasswordMinimumNonLetter(@ullable ComponentName admin)5455     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) {
5456         return getPasswordMinimumNonLetter(admin, myUserId());
5457     }
5458 
5459     /** @hide per-user version */
5460     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumNonLetter(@ullable ComponentName admin, int userHandle)5461     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) {
5462         if (mService != null) {
5463             try {
5464                 return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance);
5465             } catch (RemoteException e) {
5466                 throw e.rethrowFromSystemServer();
5467             }
5468         }
5469         return 0;
5470     }
5471 
5472     /**
5473      * Returns minimum PasswordMetrics that satisfies all admin policies.
5474      *
5475      * @hide
5476      */
getPasswordMinimumMetrics(@serIdInt int userHandle)5477     public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle) {
5478         return getPasswordMinimumMetrics(userHandle, false);
5479     }
5480 
5481     /**
5482      * Returns minimum PasswordMetrics that satisfies all admin policies.
5483      * If requested, only consider device-wide admin policies and ignore policies set on the
5484      * managed profile instance (as if the managed profile had separate work challenge).
5485      *
5486      * @hide
5487      */
getPasswordMinimumMetrics(@serIdInt int userHandle, boolean deviceWideOnly)5488     public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle,
5489             boolean deviceWideOnly) {
5490         if (mService != null) {
5491             try {
5492                 return mService.getPasswordMinimumMetrics(userHandle, deviceWideOnly);
5493             } catch (RemoteException e) {
5494                 throw e.rethrowFromSystemServer();
5495             }
5496         }
5497         return null;
5498     }
5499 
5500     /**
5501      * Called by an application that is administering the device to set the length of the password
5502      * history. After setting this, the user will not be able to enter a new password that is the
5503      * same as any password in the history. Note that the current password will remain until the
5504      * user has set a new one, so the change does not take place immediately. To prompt the user for
5505      * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
5506      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value.
5507      * <p>
5508      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5509      * password history length is always 0.
5510      * <p>
5511      * The calling device admin must have requested
5512      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
5513      * not, a security exception will be thrown.
5514      * <p>
5515      * This method can be called on the {@link DevicePolicyManager} instance returned by
5516      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5517      * profile.
5518      *
5519      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5520      * @param length The new desired length of password history. A value of 0 means there is no
5521      *            restriction.
5522      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
5523      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
5524      */
5525     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setPasswordHistoryLength(@onNull ComponentName admin, int length)5526     public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
5527         if (mService != null) {
5528             try {
5529                 mService.setPasswordHistoryLength(admin, length, mParentInstance);
5530             } catch (RemoteException e) {
5531                 throw e.rethrowFromSystemServer();
5532             }
5533         }
5534     }
5535 
5536     /**
5537      * Called by a device admin to set the password expiration timeout. Calling this method will
5538      * restart the countdown for password expiration for the given admin, as will changing the
5539      * device password (for all admins).
5540      * <p>
5541      * The provided timeout is the time delta in ms and will be added to the current time. For
5542      * example, to have the password expire 5 days from now, timeout would be 5 * 86400 * 1000 =
5543      * 432000000 ms for timeout.
5544      * <p>
5545      * To disable password expiration, a value of 0 may be used for timeout.
5546      * <p>
5547      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5548      * password expiration is always disabled.
5549      * <p>
5550      * A calling device admin must have requested
5551      * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this method; if it has
5552      * not, a security exception will be thrown.
5553      * <p>
5554      * Note that setting the password will automatically reset the expiration time for all active
5555      * admins. Active admins do not need to explicitly call this method in that case.
5556      * <p>
5557      * This method can be called on the {@link DevicePolicyManager} instance returned by
5558      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5559      * profile.
5560      *
5561      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
5562      *              caller is not a device admin
5563      * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 means
5564      *            there is no restriction (unlimited).
5565      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
5566      *             does not use {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD}
5567      */
5568     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
5569     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true)
setPasswordExpirationTimeout(@ullable ComponentName admin, long timeout)5570     public void setPasswordExpirationTimeout(@Nullable ComponentName admin, long timeout) {
5571         if (mService != null) {
5572             try {
5573                 mService.setPasswordExpirationTimeout(
5574                         admin, mContext.getPackageName(), timeout, mParentInstance);
5575             } catch (RemoteException e) {
5576                 throw e.rethrowFromSystemServer();
5577             }
5578         }
5579     }
5580 
5581     /**
5582      * Get the password expiration timeout for the given admin. The expiration timeout is the
5583      * recurring expiration timeout provided in the call to
5584      * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
5585      * aggregate of all participating policy administrators if {@code admin} is null. Admins that
5586      * have set restrictions on profiles that have a separate challenge are not taken into account.
5587      *
5588      * <p>This method can be called on the {@link DevicePolicyManager} instance
5589      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5590      * restrictions on the parent profile.
5591      *
5592      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5593      * password expiration is always disabled and this method always returns 0.
5594      *
5595      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
5596      * @return The timeout for the given admin or the minimum of all timeouts
5597      */
5598     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordExpirationTimeout(@ullable ComponentName admin)5599     public long getPasswordExpirationTimeout(@Nullable ComponentName admin) {
5600         if (mService != null) {
5601             try {
5602                 return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance);
5603             } catch (RemoteException e) {
5604                 throw e.rethrowFromSystemServer();
5605             }
5606         }
5607         return 0;
5608     }
5609 
5610     /**
5611      * Get the current password expiration time for a particular admin or all admins that set
5612      * restrictions on this user and its participating profiles. Restrictions on profiles that have
5613      * a separate challenge are not taken into account. If admin is {@code null}, then a composite
5614      * of all expiration times is returned - which will be the minimum of all of them.
5615      *
5616      * <p>This method can be called on the {@link DevicePolicyManager} instance
5617      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5618      * the password expiration for the parent profile.
5619      *
5620      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5621      * password expiration is always disabled and this method always returns 0.
5622      *
5623      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
5624      * @return The password expiration time, in milliseconds since epoch.
5625      */
5626     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordExpiration(@ullable ComponentName admin)5627     public long getPasswordExpiration(@Nullable ComponentName admin) {
5628         if (mService != null) {
5629             try {
5630                 return mService.getPasswordExpiration(admin, myUserId(), mParentInstance);
5631             } catch (RemoteException e) {
5632                 throw e.rethrowFromSystemServer();
5633             }
5634         }
5635         return 0;
5636     }
5637 
5638     /**
5639      * Retrieve the current password history length for a particular admin or all admins that
5640      * set restrictions on this user and its participating profiles. Restrictions on profiles that
5641      * have a separate challenge are not taken into account.
5642      *
5643      * <p>This method can be called on the {@link DevicePolicyManager} instance
5644      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5645      * restrictions on the parent profile.
5646      *
5647      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5648      * password history length is always 0.
5649      *
5650      * @param admin The name of the admin component to check, or {@code null} to aggregate
5651      * all admins.
5652      * @return The length of the password history
5653      */
5654     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordHistoryLength(@ullable ComponentName admin)5655     public int getPasswordHistoryLength(@Nullable ComponentName admin) {
5656         return getPasswordHistoryLength(admin, myUserId());
5657     }
5658 
5659     /** @hide per-user version */
5660     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
5661     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordHistoryLength(@ullable ComponentName admin, int userHandle)5662     public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) {
5663         if (mService != null) {
5664             try {
5665                 return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance);
5666             } catch (RemoteException e) {
5667                 throw e.rethrowFromSystemServer();
5668             }
5669         }
5670         return 0;
5671     }
5672 
5673     /**
5674      * Return the maximum password length that the device supports for a
5675      * particular password quality.
5676      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5677      * password is always empty and this method always returns 0.
5678      * @param quality The quality being interrogated.
5679      * @return Returns the maximum length that the user can enter.
5680      */
getPasswordMaximumLength(int quality)5681     public int getPasswordMaximumLength(int quality) {
5682         PackageManager pm = mContext.getPackageManager();
5683         if (!pm.hasSystemFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)) {
5684             return 0;
5685         }
5686         return MAX_PASSWORD_LENGTH;
5687     }
5688 
5689     /**
5690      * Determines whether the calling user's current password meets policy requirements
5691      * (e.g. quality, minimum length). The user must be unlocked to perform this check.
5692      *
5693      * <p>Policy requirements which affect this check can be set by admins of the user, but also
5694      * by the admin of a managed profile associated with the calling user (when the managed profile
5695      * doesn't have a separate work challenge). When a managed profile has a separate work
5696      * challenge, its policy requirements only affect the managed profile.
5697      *
5698      * <p>Depending on the user, this method checks the policy requirement against one of the
5699      * following passwords:
5700      * <ul>
5701      * <li>For the primary user or secondary users: the personal keyguard password.
5702      * <li>For managed profiles: a work challenge if set, otherwise the parent user's personal
5703      *     keyguard password.
5704      * <ul/>
5705      * In other words, it's always checking the requirement against the password that is protecting
5706      * the calling user.
5707      *
5708      * <p>Note that this method considers all policy requirements targeting the password in
5709      * question. For example a profile owner might set a requirement on the parent profile i.e.
5710      * personal keyguard but not on the profile itself. When the device has a weak personal keyguard
5711      * password and no separate work challenge, calling this method will return {@code false}
5712      * despite the profile owner not setting a policy on the profile itself. This is because the
5713      * profile's current password is the personal keyguard password, and it does not meet all policy
5714      * requirements.
5715      *
5716      * <p>Device admins must request {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} before
5717      * calling this method. Note, this policy type is deprecated for device admins in Android 9.0
5718      * (API level 28) or higher.
5719      *
5720      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
5721      * {@link #getParentProfileInstance(ComponentName)} in order to determine if the password set on
5722      * the parent profile is sufficient.
5723      *
5724      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
5725      * password is always treated as empty - i.e. this method will always return false on such
5726      * devices, provided any password requirements were set.
5727      *
5728      * @return {@code true} if the password meets the policy requirements, {@code false} otherwise
5729      * @throws SecurityException if the calling application isn't an active admin that uses
5730      *     {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
5731      * @throws IllegalStateException if the user isn't unlocked
5732      */
5733     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true)
isActivePasswordSufficient()5734     public boolean isActivePasswordSufficient() {
5735         if (mService != null) {
5736             try {
5737                 return mService.isActivePasswordSufficient(
5738                         mContext.getPackageName(), myUserId(), mParentInstance);
5739             } catch (RemoteException e) {
5740                 throw e.rethrowFromSystemServer();
5741             }
5742         }
5743         return false;
5744     }
5745 
5746     /**
5747      * Called by profile owner of a managed profile to determine whether the current device password
5748      * meets policy requirements set explicitly device-wide.
5749      * <p> This API is similar to {@link #isActivePasswordSufficient()}, with two notable
5750      * differences:
5751      * <ul>
5752      * <li>this API always targets the device password. As a result it should always be called on
5753      *   the {@link #getParentProfileInstance(ComponentName)} instance.</li>
5754      * <li>password policy requirement set on the managed profile is not taken into consideration
5755      *   by this API, even if the device currently does not have a separate work challenge set.</li>
5756      * </ul>
5757      *
5758      * <p>This API is designed to facilite progressive password enrollment flows when the DPC
5759      * imposes both device and profile password policies. DPC applies profile password policy by
5760      * calling {@link #setPasswordQuality(ComponentName, int)} or
5761      * {@link #setRequiredPasswordComplexity} on the regular {@link DevicePolicyManager} instance,
5762      * while it applies device-wide policy by calling {@link #setRequiredPasswordComplexity} on the
5763      * {@link #getParentProfileInstance(ComponentName)} instance. The DPC can utilize this check to
5764      * guide the user to set a device password first taking into consideration the device-wide
5765      * policy only, and then prompt the user to either upgrade it to be fully compliant, or enroll a
5766      * separate work challenge to satisfy the profile password policy only.
5767      *
5768      * <p>The device user must be unlocked (@link {@link UserManager#isUserUnlocked(UserHandle)})
5769      * to perform this check.
5770      *
5771      * @return {@code true} if the device password meets explicit requirement set on it,
5772      *   {@code false} otherwise.
5773      * @throws SecurityException if the calling application is not a profile owner of a managed
5774      *   profile, or if this API is not called on the parent DevicePolicyManager instance.
5775      * @throws IllegalStateException if the user isn't unlocked
5776      * @see #EXTRA_DEVICE_PASSWORD_REQUIREMENT_ONLY
5777      */
isActivePasswordSufficientForDeviceRequirement()5778     public boolean isActivePasswordSufficientForDeviceRequirement() {
5779         if (!mParentInstance) {
5780             throw new SecurityException("only callable on the parent instance");
5781         }
5782         if (mService != null) {
5783             try {
5784                 return mService.isActivePasswordSufficientForDeviceRequirement();
5785             } catch (RemoteException e) {
5786                 throw e.rethrowFromSystemServer();
5787             }
5788         }
5789         return false;
5790     }
5791 
5792     /**
5793      * Returns how complex the current user's screen lock is.
5794      *
5795      * <p>Note that when called from a profile which uses an unified challenge with its parent, the
5796      * screen lock complexity of the parent will be returned.
5797      *
5798      * <p>Apps need the {@link permission#REQUEST_PASSWORD_COMPLEXITY} permission to call this
5799      * method. On Android {@link android.os.Build.VERSION_CODES#S} and above, the calling
5800      * application does not need this permission if it is a device owner or a profile owner.
5801      *
5802      * <p>This method can be called on the {@link DevicePolicyManager} instance
5803      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5804      * restrictions on the parent profile.
5805      *
5806      * @throws IllegalStateException if the user is not unlocked.
5807      * @throws SecurityException     if the calling application does not have the permission
5808      *                               {@link permission#REQUEST_PASSWORD_COMPLEXITY}, and is not a
5809      *                               device owner or a profile owner.
5810      */
5811     @PasswordComplexity
5812     @RequiresPermission(anyOf={MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, REQUEST_PASSWORD_COMPLEXITY}, conditional = true)
getPasswordComplexity()5813     public int getPasswordComplexity() {
5814         if (mService == null) {
5815             return PASSWORD_COMPLEXITY_NONE;
5816         }
5817 
5818         try {
5819             return mService.getPasswordComplexity(mParentInstance);
5820         } catch (RemoteException e) {
5821             throw e.rethrowFromSystemServer();
5822         }
5823     }
5824 
5825     /**
5826      * Sets a minimum password complexity requirement for the user's screen lock.
5827      * The complexity level is one of the pre-defined levels, and the user is unable to set a
5828      * password with a lower complexity level.
5829      *
5830      * <p>Note that when called on a profile which uses an unified challenge with its parent, the
5831      * complexity would apply to the unified challenge.
5832      *
5833      * <p>This method can be called on the {@link DevicePolicyManager} instance
5834      * returned by {@link #getParentProfileInstance(ComponentName)} in order to set
5835      * restrictions on the parent profile.
5836      *
5837      * <p><strong>Note:</strong> Specifying password requirements using this method clears any
5838      * password requirements set using the obsolete {@link #setPasswordQuality(ComponentName, int)}
5839      * and any of its associated methods.
5840      * Additionally, if there are password requirements set using the obsolete
5841      * {@link #setPasswordQuality(ComponentName, int)} on the parent {@code DevicePolicyManager}
5842      * instance, they must be cleared by calling {@link #setPasswordQuality(ComponentName, int)}
5843      * with {@link #PASSWORD_QUALITY_UNSPECIFIED} on that instance prior to setting complexity
5844      * requirement for the managed profile.
5845      *
5846      * Starting from {@link Build.VERSION_CODES#VANILLA_ICE_CREAM}, after the password
5847      * requirement has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
5848      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
5849      * successfully set or not. This callback will contain:
5850      * <ul>
5851      * <li> The policy identifier {@link DevicePolicyIdentifiers#PASSWORD_COMPLEXITY_POLICY}
5852      * <li> The {@link TargetUser} that this policy relates to
5853      * <li> The {@link PolicyUpdateResult}, which will be
5854      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
5855      * reason the policy failed to be set
5856      * e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
5857      * </ul>
5858      * If there has been a change to the policy,
5859      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
5860      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
5861      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
5862      * will contain the reason why the policy changed.
5863      *
5864      * @throws SecurityException if the calling application is not a device owner or a profile
5865      * owner.
5866      * @throws IllegalArgumentException if the complexity level is not one of the four above.
5867      * @throws IllegalStateException if the caller is trying to set password complexity while there
5868      * are password requirements specified using {@link #setPasswordQuality(ComponentName, int)}
5869      * on the parent {@code DevicePolicyManager} instance.
5870      */
5871     @SupportsCoexistence
5872     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true)
setRequiredPasswordComplexity(@asswordComplexity int passwordComplexity)5873     public void setRequiredPasswordComplexity(@PasswordComplexity int passwordComplexity) {
5874         if (mService == null) {
5875             return;
5876         }
5877 
5878         try {
5879             mService.setRequiredPasswordComplexity(
5880                     mContext.getPackageName(), passwordComplexity, mParentInstance);
5881         } catch (RemoteException e) {
5882             throw e.rethrowFromSystemServer();
5883         }
5884     }
5885 
5886 
5887     /**
5888      * Gets the password complexity requirement set by {@link #setRequiredPasswordComplexity(int)},
5889      * for the current user.
5890      *
5891      * <p>The difference between this method and {@link #getPasswordComplexity()} is that this
5892      * method simply returns the value set by {@link #setRequiredPasswordComplexity(int)} while
5893      * {@link #getPasswordComplexity()} returns the complexity of the actual password.
5894      *
5895      * <p>This method can be called on the {@link DevicePolicyManager} instance
5896      * returned by {@link #getParentProfileInstance(ComponentName)} in order to get
5897      * restrictions on the parent profile.
5898      *
5899      * @throws SecurityException if the calling application is not a device owner or a profile
5900      * owner.
5901      */
5902     @PasswordComplexity
5903     @SupportsCoexistence
5904     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true)
getRequiredPasswordComplexity()5905     public int getRequiredPasswordComplexity() {
5906         if (mService == null) {
5907             return PASSWORD_COMPLEXITY_NONE;
5908         }
5909 
5910         try {
5911             return mService.getRequiredPasswordComplexity(
5912                     mContext.getPackageName(), mParentInstance);
5913         } catch (RemoteException e) {
5914             throw e.rethrowFromSystemServer();
5915         }
5916     }
5917 
5918     /**
5919      * Returns the password complexity that applies to this user, aggregated from other users if
5920      * necessary (for example, if the DPC has set password complexity requirements on the parent
5921      * profile DPM instance of a managed profile user, they would apply to the primary user on the
5922      * device).
5923      * @hide
5924      */
5925     @PasswordComplexity
getAggregatedPasswordComplexityForUser(int userId)5926     public int getAggregatedPasswordComplexityForUser(int userId) {
5927         return getAggregatedPasswordComplexityForUser(userId, false);
5928     }
5929 
5930     /**
5931      * Returns the password complexity that applies to this user, aggregated from other users if
5932      * necessary (for example, if the DPC has set password complexity requirements on the parent
5933      * profile DPM instance of a managed profile user, they would apply to the primary user on the
5934      * device). If {@code deviceWideOnly} is {@code true}, ignore policies set on the
5935      * managed profile DPM instance (as if the managed profile had separate work challenge).
5936      * @hide
5937      */
5938     @PasswordComplexity
getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly)5939     public int getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly) {
5940         if (mService == null) {
5941             return PASSWORD_COMPLEXITY_NONE;
5942         }
5943 
5944         try {
5945             return mService.getAggregatedPasswordComplexityForUser(userId, deviceWideOnly);
5946         } catch (RemoteException e) {
5947             throw e.rethrowFromSystemServer();
5948         }
5949     }
5950 
5951 
5952     /**
5953      * When called by a profile owner of a managed profile returns true if the profile uses unified
5954      * challenge with its parent user.
5955      *
5956      * <strong>Note</strong>: This method is not concerned with password quality and will return
5957      * false if the profile has empty password as a separate challenge.
5958      *
5959      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5960      * @throws SecurityException if {@code admin} is not a profile owner of a managed profile.
5961      * @see UserManager#DISALLOW_UNIFIED_PASSWORD
5962      */
isUsingUnifiedPassword(@onNull ComponentName admin)5963     public boolean isUsingUnifiedPassword(@NonNull ComponentName admin) {
5964         throwIfParentInstance("isUsingUnifiedPassword");
5965         if (mService != null) {
5966             try {
5967                 return mService.isUsingUnifiedPassword(admin);
5968             } catch (RemoteException e) {
5969                 throw e.rethrowFromSystemServer();
5970             }
5971         }
5972         return true;
5973     }
5974 
5975     /**
5976      * Returns whether the given user's credential will be sufficient for all password policy
5977      * requirement, once the user's profile has switched to unified challenge.
5978      *
5979      * <p>This is different from {@link #isActivePasswordSufficient()} since once the profile
5980      * switches to unified challenge, policies set explicitly on the profile will start to affect
5981      * the parent user.
5982      * @param userHandle the user whose password requirement will be checked
5983      * @param profileUser the profile user whose lockscreen challenge will be unified.
5984      * @hide
5985      */
isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser)5986     public boolean isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser) {
5987         if (mService != null) {
5988             try {
5989                 return mService.isPasswordSufficientAfterProfileUnification(userHandle,
5990                         profileUser);
5991             } catch (RemoteException e) {
5992                 throw e.rethrowFromSystemServer();
5993             }
5994         }
5995         return false;
5996     }
5997     /**
5998      * Retrieve the number of times the user has failed at entering a password since that last
5999      * successful password entry.
6000      * <p>
6001      * This method can be called on the {@link DevicePolicyManager} instance returned by
6002      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the number of failed
6003      * password attemts for the parent user.
6004      * <p>
6005      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
6006      * to be able to call this method; if it has not, a security exception will be thrown.
6007      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
6008      * password is always empty and this method always returns 0.
6009      *
6010      * @return The number of times user has entered an incorrect password since the last correct
6011      *         password entry.
6012      * @throws SecurityException if the calling application does not own an active administrator
6013      *             that uses {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
6014      */
6015     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
6016     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true)
getCurrentFailedPasswordAttempts()6017     public int getCurrentFailedPasswordAttempts() {
6018         return getCurrentFailedPasswordAttempts(myUserId());
6019     }
6020 
6021     /**
6022      * Retrieve the number of times the given user has failed at entering a
6023      * password since that last successful password entry.
6024      *
6025      * <p>The calling device admin must have requested
6026      * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call this method; if it has
6027      * not and it is not the system uid, a security exception will be thrown.
6028      *
6029      * @hide
6030      */
6031     @UnsupportedAppUsage
getCurrentFailedPasswordAttempts(int userHandle)6032     public int getCurrentFailedPasswordAttempts(int userHandle) {
6033         if (mService != null) {
6034             try {
6035                 return mService.getCurrentFailedPasswordAttempts(
6036                         mContext.getPackageName(), userHandle, mParentInstance);
6037             } catch (RemoteException e) {
6038                 throw e.rethrowFromSystemServer();
6039             }
6040         }
6041         return -1;
6042     }
6043 
6044     /**
6045      * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set.
6046      *
6047      * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set.
6048      * @hide
6049      */
getDoNotAskCredentialsOnBoot()6050     public boolean getDoNotAskCredentialsOnBoot() {
6051         if (mService != null) {
6052             try {
6053                 return mService.getDoNotAskCredentialsOnBoot();
6054             } catch (RemoteException e) {
6055                 throw e.rethrowFromSystemServer();
6056             }
6057         }
6058         return false;
6059     }
6060 
6061     /**
6062      * Setting this to a value greater than zero enables a policy that will perform a
6063      * device or profile wipe after too many incorrect device-unlock passwords have been entered.
6064      * This policy combines watching for failed passwords and wiping the device, and
6065      * requires that calling Device Admins request both
6066      * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
6067      * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
6068      * <p>
6069      * When this policy is set on the system or the main user, the device will be factory reset
6070      * after too many incorrect password attempts. When set on any other user, only the
6071      * corresponding user or profile will be wiped.
6072      * <p>
6073      * To implement any other policy (e.g. wiping data for a particular application only, erasing or
6074      * revoking credentials, or reporting the failure to a server), you should implement
6075      * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)} instead. Do not
6076      * use this API, because if the maximum count is reached, the device or profile will be wiped
6077      * immediately, and your callback will not be invoked.
6078      * <p>
6079      * This method can be called on the {@link DevicePolicyManager} instance returned by
6080      * {@link #getParentProfileInstance(ComponentName)} in order to set a value on the parent
6081      * profile. This allows a profile wipe after too many incorrect device-unlock password have
6082      * been entered on the parent profile even if each profile has a separate challenge.
6083      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
6084      * password is always empty and this method has no effect - i.e. the policy is not set.
6085      *
6086      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
6087      *              caller is not a device admin.
6088      * @param num The number of failed password attempts at which point the device or profile will
6089      *            be wiped.
6090      * @throws SecurityException if {@code admin} is not null, and {@code admin} is not an active
6091      *            administrator or does not use both
6092      *            {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
6093      *            {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}, or if {@code admin} is null and the
6094      *            caller does not have permission to wipe the device.
6095      */
6096     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIPE_DATA, conditional = true)
6097     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setMaximumFailedPasswordsForWipe(@ullable ComponentName admin, int num)6098     public void setMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int num) {
6099         if (mService != null) {
6100             try {
6101                 mService.setMaximumFailedPasswordsForWipe(
6102                         admin, mContext.getPackageName(), num, mParentInstance);
6103             } catch (RemoteException e) {
6104                 throw e.rethrowFromSystemServer();
6105             }
6106         }
6107     }
6108 
6109     /**
6110      * Retrieve the current maximum number of login attempts that are allowed before the device
6111      * or profile is wiped, for a particular admin or all admins that set restrictions on this user
6112      * and its participating profiles. Restrictions on profiles that have a separate challenge are
6113      * not taken into account.
6114      *
6115      * <p>This method can be called on the {@link DevicePolicyManager} instance
6116      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
6117      * the value for the parent profile.
6118      *
6119      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
6120      * password is always empty and this method returns a default value (0) indicating that the
6121      * policy is not set.
6122      *
6123      * @param admin The name of the admin component to check, or {@code null} to aggregate
6124      * all admins.
6125      */
6126     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin)6127     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) {
6128         return getMaximumFailedPasswordsForWipe(admin, myUserId());
6129     }
6130 
6131     /** @hide per-user version */
6132     @UnsupportedAppUsage
6133     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin, int userHandle)6134     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) {
6135         if (mService != null) {
6136             try {
6137                 return mService.getMaximumFailedPasswordsForWipe(
6138                         admin, userHandle, mParentInstance);
6139             } catch (RemoteException e) {
6140                 throw e.rethrowFromSystemServer();
6141             }
6142         }
6143         return 0;
6144     }
6145 
6146     /**
6147      * Returns the user that will be wiped first when too many failed attempts are made to unlock
6148      * user {@code userHandle}. That user is either the same as {@code userHandle} or belongs to the
6149      * same profile group. When there is no such policy, returns {@code UserHandle.USER_NULL}.
6150      * E.g. managed profile user may be wiped as a result of failed primary profile password
6151      * attempts when using unified challenge. Primary user may be wiped as a result of failed
6152      * password attempts on the managed profile on an organization-owned device.
6153      * @hide Used only by Keyguard
6154      */
6155     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getProfileWithMinimumFailedPasswordsForWipe(int userHandle)6156     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
6157         if (mService != null) {
6158             try {
6159                 return mService.getProfileWithMinimumFailedPasswordsForWipe(
6160                         userHandle, mParentInstance);
6161             } catch (RemoteException e) {
6162                 throw e.rethrowFromSystemServer();
6163             }
6164         }
6165         return UserHandle.USER_NULL;
6166     }
6167 
6168     /**
6169      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't allow other admins
6170      * to change the password again until the user has entered it.
6171      */
6172     public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
6173 
6174     /**
6175      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't ask for user
6176      * credentials on device boot.
6177      * If the flag is set, the device can be booted without asking for user password.
6178      * The absence of this flag does not change the current boot requirements. This flag
6179      * can be set by the device owner only. If the app is not the device owner, the flag
6180      * is ignored. Once the flag is set, it cannot be reverted back without resetting the
6181      * device to factory defaults.
6182      */
6183     public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
6184 
6185     /**
6186      * Force a new password for device unlock (the password needed to access the entire device) or
6187      * the work profile challenge on the current user. This takes effect immediately.
6188      *
6189      * <p> Before {@link android.os.Build.VERSION_CODES#N}, this API is available to device admin,
6190      * profile owner and device owner. Starting from {@link android.os.Build.VERSION_CODES#N},
6191      * legacy device admin (who is not also profile owner or device owner) can only call this
6192      * API to set a new password if there is currently no password set. Profile owner and device
6193      * owner can continue to force change an existing password as long as the target user is
6194      * unlocked, although device owner will not be able to call this API at all if there is also a
6195      * managed profile on the device.
6196      *
6197      * <p> Between {@link android.os.Build.VERSION_CODES#O},
6198      * {@link android.os.Build.VERSION_CODES#P} and {@link android.os.Build.VERSION_CODES#Q},
6199      * profile owner and devices owner targeting SDK level {@link android.os.Build.VERSION_CODES#O}
6200      * or above who attempt to call this API will receive {@link SecurityException}; they are
6201      * encouraged to migrate to the new {@link #resetPasswordWithToken} API instead.
6202      * Profile owner and device owner targeting older SDK levels are not affected: they continue
6203      * to experience the existing behaviour described in the previous paragraph.
6204      *
6205      * <p><em>Starting from {@link android.os.Build.VERSION_CODES#R}, this API is no longer
6206      * supported in most cases.</em> Device owner and profile owner calling
6207      * this API will receive {@link SecurityException} if they target SDK level
6208      * {@link android.os.Build.VERSION_CODES#O} or above, or they will receive a silent failure
6209      * (API returning {@code false}) if they target lower SDK level.
6210      * For legacy device admins, this API throws {@link SecurityException} if they target SDK level
6211      * {@link android.os.Build.VERSION_CODES#N} or above, and returns {@code false} otherwise. Only
6212      * privileged apps holding RESET_PASSWORD permission which are part of
6213      * the system factory image can still call this API to set a new password if there is currently
6214      * no password set. In this case, if the device already has a password, this API will throw
6215      * {@link SecurityException}.
6216      *
6217      * <p>
6218      * The given password must be sufficient for the current password quality and length constraints
6219      * as returned by {@link #getPasswordQuality(ComponentName)} and
6220      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
6221      * it will be rejected and false returned. Note that the password may be a stronger quality
6222      * (containing alphanumeric characters when the requested quality is only numeric), in which
6223      * case the currently active quality will be increased to match.
6224      *
6225      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
6226      * methods does nothing.
6227      * <p>
6228      * The calling device admin must have requested
6229      * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call this method; if it has
6230      * not, a security exception will be thrown.
6231      *
6232      * @param password The new password for the user. Null or empty clears the password.
6233      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
6234      *            {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
6235      * @return Returns true if the password was applied, or false if it is not acceptable for the
6236      *         current constraints.
6237      * @throws SecurityException if the calling application does not own an active administrator
6238      *             that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
6239      * @throws IllegalStateException if the calling user is locked or has a managed profile.
6240      * @deprecated Please use {@link #resetPasswordWithToken} instead.
6241      */
6242     @Deprecated
6243     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
resetPassword(String password, int flags)6244     public boolean resetPassword(String password, int flags) {
6245         throwIfParentInstance("resetPassword");
6246         if (mService != null) {
6247             try {
6248                 return mService.resetPassword(password, flags);
6249             } catch (RemoteException e) {
6250                 throw e.rethrowFromSystemServer();
6251             }
6252         }
6253         return false;
6254     }
6255 
6256     /**
6257      * Called by a profile or device owner to provision a token which can later be used to reset the
6258      * device lockscreen password (if called by device owner), or managed profile challenge (if
6259      * called by profile owner), via {@link #resetPasswordWithToken}.
6260      * <p>
6261      * If the user currently has a lockscreen password, the provisioned token will not be
6262      * immediately usable; it only becomes active after the user performs a confirm credential
6263      * operation, which can be triggered by {@link KeyguardManager#createConfirmDeviceCredentialIntent}.
6264      * If the user has no lockscreen password, the token is activated immediately. In all cases,
6265      * the active state of the current token can be checked by {@link #isResetPasswordTokenActive}.
6266      * For security reasons, un-activated tokens are only stored in memory and will be lost once
6267      * the device reboots. In this case a new token needs to be provisioned again.
6268      * <p>
6269      * Once provisioned and activated, the token will remain effective even if the user changes
6270      * or clears the lockscreen password.
6271      * <p>
6272      * <em>This token is highly sensitive and should be treated at the same level as user
6273      * credentials. In particular, NEVER store this token on device in plaintext. Do not store
6274      * the plaintext token in device-encrypted storage if it will be needed to reset password on
6275      * file-based encryption devices before user unlocks. Consider carefully how any password token
6276      * will be stored on your server and who will need access to them. Tokens may be the subject of
6277      * legal access requests.
6278      * </em>
6279      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
6280      * reset token is not set and this method returns false.
6281      *
6282      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
6283      *              caller is not a device admin.
6284      * @param token a secure token a least 32-byte long, which must be generated by a
6285      *        cryptographically strong random number generator.
6286      * @return true if the operation is successful, false otherwise.
6287      * @throws SecurityException if admin is not a device or profile owner.
6288      * @throws IllegalArgumentException if the supplied token is invalid.
6289      */
6290     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
6291     @RequiresPermission(value = MANAGE_DEVICE_POLICY_RESET_PASSWORD, conditional = true)
setResetPasswordToken(@ullable ComponentName admin, byte[] token)6292     public boolean setResetPasswordToken(@Nullable ComponentName admin, byte[] token) {
6293         throwIfParentInstance("setResetPasswordToken");
6294         if (mService != null) {
6295             try {
6296                 return mService.setResetPasswordToken(admin, mContext.getPackageName(), token);
6297             } catch (RemoteException e) {
6298                 throw e.rethrowFromSystemServer();
6299             }
6300         }
6301         return false;
6302     }
6303 
6304     /**
6305      * Called by a profile, device owner or holder of the permission
6306      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_RESET_PASSWORD}
6307      * to revoke the current password reset token.
6308      *
6309      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
6310      * method has no effect - the reset token should not have been set in the first place - and
6311      * false is returned.
6312      *
6313      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
6314      *              caller is not a device admin.
6315      * @return true if the operation is successful, false otherwise.
6316      * @throws SecurityException if admin is not a device or profile owner and if the caller does
6317      * not the permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_RESET_PASSWORD}.
6318      */
6319     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
6320     @RequiresPermission(value = MANAGE_DEVICE_POLICY_RESET_PASSWORD, conditional = true)
clearResetPasswordToken(@ullable ComponentName admin)6321     public boolean clearResetPasswordToken(@Nullable ComponentName admin) {
6322         throwIfParentInstance("clearResetPasswordToken");
6323         if (mService != null) {
6324             try {
6325                 return mService.clearResetPasswordToken(admin, mContext.getPackageName());
6326             } catch (RemoteException e) {
6327                 throw e.rethrowFromSystemServer();
6328             }
6329         }
6330         return false;
6331     }
6332 
6333     /**
6334      * Called by a profile, device owner or a holder of the permission
6335      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_RESET_PASSWORD}
6336      * to check if the current reset password token is active.
6337      *
6338      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
6339      * false is always returned.
6340      *
6341      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
6342      *              caller is not a device admin.
6343      * @return true if the token is active, false otherwise.
6344      * @throws SecurityException if admin is not a device or profile owner and not a holder of the
6345      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_RESET_PASSWORD}
6346      * @throws IllegalStateException if no token has been set.
6347      */
6348     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
6349     @RequiresPermission(value = MANAGE_DEVICE_POLICY_RESET_PASSWORD, conditional = true)
isResetPasswordTokenActive(@ullable ComponentName admin)6350     public boolean isResetPasswordTokenActive(@Nullable ComponentName admin) {
6351         throwIfParentInstance("isResetPasswordTokenActive");
6352         if (mService != null) {
6353             try {
6354                 return mService.isResetPasswordTokenActive(admin, mContext.getPackageName());
6355             } catch (RemoteException e) {
6356                 throw e.rethrowFromSystemServer();
6357             }
6358         }
6359         return false;
6360     }
6361 
6362     /**
6363      * Called by device or profile owner to force set a new device unlock password or a managed
6364      * profile challenge on current user. This takes effect immediately.
6365      * <p>
6366      * Unlike {@link #resetPassword}, this API can change the password even before the user or
6367      * device is unlocked or decrypted. The supplied token must have been previously provisioned via
6368      * {@link #setResetPasswordToken}, and in active state {@link #isResetPasswordTokenActive}.
6369      * <p>
6370      * The given password must be sufficient for the current password quality and length constraints
6371      * as returned by {@link #getPasswordQuality(ComponentName)} and
6372      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
6373      * it will be rejected and false returned. Note that the password may be a stronger quality, for
6374      * example, a password containing alphanumeric characters when the requested quality is only
6375      * numeric.
6376      * <p>
6377      * Calling with a {@code null} or empty password will clear any existing PIN, pattern or
6378      * password if the current password constraints allow it.
6379      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
6380      * calling this methods has no effect - the password is always empty - and false is returned.
6381      *
6382      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
6383      *              caller is not a device admin.
6384      * @param password The new password for the user. {@code null} or empty clears the password.
6385      * @param token the password reset token previously provisioned by
6386      *        {@link #setResetPasswordToken}.
6387      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
6388      *        {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
6389      * @return Returns true if the password was applied, or false if it is not acceptable for the
6390      *         current constraints.
6391      * @throws SecurityException if admin is not a device or profile owner.
6392      * @throws IllegalStateException if the provided token is not valid.
6393      */
6394     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
6395     @RequiresPermission(value = MANAGE_DEVICE_POLICY_RESET_PASSWORD, conditional = true)
resetPasswordWithToken(@ullable ComponentName admin, String password, byte[] token, int flags)6396     public boolean resetPasswordWithToken(@Nullable ComponentName admin, String password,
6397             byte[] token, int flags) {
6398         throwIfParentInstance("resetPassword");
6399         if (mService != null) {
6400             try {
6401                 return mService.resetPasswordWithToken(admin, mContext.getPackageName(), password,
6402                         token, flags);
6403             } catch (RemoteException e) {
6404                 throw e.rethrowFromSystemServer();
6405             }
6406         }
6407         return false;
6408     }
6409 
6410     /**
6411      * Called by an application that is administering the device to set the maximum time for user
6412      * activity until the device will lock. This limits the length that the user can set. It takes
6413      * effect immediately.
6414      * <p>
6415      * A calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
6416      * to be able to call this method; if it has not, a security exception will be thrown.
6417      * <p>
6418      * This method can be called on the {@link DevicePolicyManager} instance returned by
6419      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
6420      * profile.
6421      *
6422      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
6423      *              caller is not a device admin
6424      * @param timeMs The new desired maximum time to lock in milliseconds. A value of 0 means there
6425      *            is no restriction.
6426      * @throws SecurityException if {@code admin} is not an active administrator or it does not use
6427      *             {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
6428      */
6429     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK, conditional = true)
setMaximumTimeToLock(@ullable ComponentName admin, long timeMs)6430     public void setMaximumTimeToLock(@Nullable ComponentName admin, long timeMs) {
6431         if (mService != null) {
6432             try {
6433                 mService.setMaximumTimeToLock(admin, mContext.getPackageName(), timeMs, mParentInstance);
6434             } catch (RemoteException e) {
6435                 throw e.rethrowFromSystemServer();
6436             }
6437         }
6438     }
6439 
6440     /**
6441      * Retrieve the current maximum time to unlock for a particular admin or all admins that set
6442      * restrictions on this user and its participating profiles. Restrictions on profiles that have
6443      * a separate challenge are not taken into account.
6444      *
6445      * <p>This method can be called on the {@link DevicePolicyManager} instance
6446      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
6447      * restrictions on the parent profile.
6448      *
6449      * @param admin The name of the admin component to check, or {@code null} to aggregate
6450      * all admins.
6451      * @return time in milliseconds for the given admin or the minimum value (strictest) of
6452      * all admins if admin is null. Returns 0 if there are no restrictions.
6453      */
getMaximumTimeToLock(@ullable ComponentName admin)6454     public long getMaximumTimeToLock(@Nullable ComponentName admin) {
6455         return getMaximumTimeToLock(admin, myUserId());
6456     }
6457 
6458     /** @hide per-user version */
6459     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getMaximumTimeToLock(@ullable ComponentName admin, int userHandle)6460     public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) {
6461         if (mService != null) {
6462             try {
6463                 return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance);
6464             } catch (RemoteException e) {
6465                 throw e.rethrowFromSystemServer();
6466             }
6467         }
6468         return 0;
6469     }
6470 
6471     /**
6472      * Called by a device/profile owner to set the timeout after which unlocking with secondary, non
6473      * strong auth (e.g. fingerprint, face, trust agents) times out, i.e. the user has to use a
6474      * strong authentication method like password, pin or pattern.
6475      *
6476      * <p>This timeout is used internally to reset the timer to require strong auth again after
6477      * specified timeout each time it has been successfully used.
6478      *
6479      * <p>Fingerprint can also be disabled altogether using {@link #KEYGUARD_DISABLE_FINGERPRINT}.
6480      *
6481      * <p>Trust agents can also be disabled altogether using {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
6482      *
6483      * <p>A calling device admin can verify the value it has set by calling
6484      * {@link #getRequiredStrongAuthTimeout(ComponentName)} and passing in its instance.
6485      *
6486      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
6487      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
6488      * profile.
6489      *
6490      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
6491      * calling this methods has no effect - i.e. the timeout is not set.
6492      *
6493      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
6494      *              caller is not a device admin
6495      * @param timeoutMs The new timeout in milliseconds, after which the user will have to unlock
6496      *         with strong authentication method. A value of 0 means the admin is not participating
6497      *         in controlling the timeout.
6498      *         The minimum and maximum timeouts are platform-defined and are typically 1 hour and
6499      *         72 hours, respectively. Though discouraged, the admin may choose to require strong
6500      *         auth at all times using {@link #KEYGUARD_DISABLE_FINGERPRINT} and/or
6501      *         {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
6502      *
6503      * @throws SecurityException if {@code admin} is not a device or profile owner.
6504      */
6505     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
6506     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, conditional = true)
setRequiredStrongAuthTimeout(@ullable ComponentName admin, long timeoutMs)6507     public void setRequiredStrongAuthTimeout(@Nullable ComponentName admin,
6508             long timeoutMs) {
6509         if (mService != null) {
6510             try {
6511                 mService.setRequiredStrongAuthTimeout(
6512                         admin, mContext.getPackageName(), timeoutMs, mParentInstance);
6513             } catch (RemoteException e) {
6514                 throw e.rethrowFromSystemServer();
6515             }
6516         }
6517     }
6518 
6519     /**
6520      * Determine for how long the user will be able to use secondary, non strong auth for
6521      * authentication, since last strong method authentication (password, pin or pattern) was used.
6522      * After the returned timeout the user is required to use strong authentication method.
6523      *
6524      * <p>This method can be called on the {@link DevicePolicyManager} instance
6525      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
6526      * restrictions on the parent profile.
6527      *
6528      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
6529      * 0 is returned to indicate that no timeout is configured.
6530      *
6531      * @param admin The name of the admin component to check, or {@code null} to aggregate
6532      *         across all participating admins.
6533      * @return The timeout in milliseconds or 0 if not configured for the provided admin.
6534      */
6535     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getRequiredStrongAuthTimeout(@ullable ComponentName admin)6536     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin) {
6537         return getRequiredStrongAuthTimeout(admin, myUserId());
6538     }
6539 
6540     /** @hide per-user version */
6541     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
6542     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getRequiredStrongAuthTimeout(@ullable ComponentName admin, @UserIdInt int userId)6543     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin, @UserIdInt int userId) {
6544         if (mService != null) {
6545             try {
6546                 return mService.getRequiredStrongAuthTimeout(admin, userId, mParentInstance);
6547             } catch (RemoteException e) {
6548                 throw e.rethrowFromSystemServer();
6549             }
6550         }
6551         return DEFAULT_STRONG_AUTH_TIMEOUT_MS;
6552     }
6553 
6554     /**
6555      * Flag for {@link #lockNow(int)}: also evict the user's credential encryption key from the
6556      * keyring. The user's credential will need to be entered again in order to derive the
6557      * credential encryption key that will be stored back in the keyring for future use.
6558      * <p>
6559      * This flag can only be used by a profile owner when locking a managed profile when
6560      * {@link #getStorageEncryptionStatus} returns {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
6561      * <p>
6562      * In order to secure user data, the user will be stopped and restarted so apps should wait
6563      * until they are next run to perform further actions.
6564      */
6565     public static final int FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY = 1;
6566 
6567     /** @hide */
6568     @Retention(RetentionPolicy.SOURCE)
6569     @IntDef(flag = true, prefix = { "FLAG_EVICT_" }, value = {
6570             FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY
6571     })
6572     public @interface LockNowFlag {}
6573 
6574     /**
6575      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
6576      * this call.
6577      * <p>
6578      * This method secures the device in response to an urgent situation, such as a lost or stolen
6579      * device. After this method is called, the device must be unlocked using strong authentication
6580      * (PIN, pattern, or password). This API is intended for use only by device admins.
6581      * <p>
6582      * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have
6583      * the LOCK_DEVICE permission or the device must have the
6584      * device admin feature; if neither is true, then the method will return without completing
6585      * any action. Before version {@link android.os.Build.VERSION_CODES#R},
6586      * the device needed the device admin feature, regardless of the caller's permissions.
6587      * <p>
6588      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
6589      * to be able to call this method; if it has not, a security exception will be thrown.
6590      * <p>
6591      * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
6592      * the device. Device admins who find the device in this state can lock an otherwise-insecure
6593      * device by first calling {@link #resetPassword} to set the password and then lock the device.
6594      * <p>
6595      * This method can be called on the {@link DevicePolicyManager} instance returned by
6596      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
6597      * <p>
6598      * NOTE: on {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, this
6599      * method doesn't turn off the screen as it would be a driving safety distraction.
6600      * <p>
6601      * Equivalent to calling {@link #lockNow(int)} with no flags.
6602      *
6603      * @throws SecurityException if the calling application does not own an active administrator
6604      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
6605      */
6606     @SuppressLint("RequiresPermission")
6607     @RequiresPermission(value = LOCK_DEVICE, conditional = true)
lockNow()6608     public void lockNow() {
6609         lockNow(0);
6610     }
6611 
6612     /**
6613      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
6614      * this call.
6615      * <p>
6616      * This method secures the device in response to an urgent situation, such as a lost or stolen
6617      * device. After this method is called, the device must be unlocked using strong authentication
6618      * (PIN, pattern, or password). This API is intended for use only by device admins.
6619      * <p>
6620      * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have
6621      * the LOCK_DEVICE permission or the device must have the
6622      * device admin feature; if neither is true, then the method will return without completing any
6623      * action. Before version {@link android.os.Build.VERSION_CODES#R}, the device needed the device
6624      * admin feature, regardless of the caller's permissions.
6625      * <p>
6626      * A calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
6627      * to be able to call this method; if it has not, a security exception will be thrown.
6628      * <p>
6629      * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
6630      * the device. Device admins who find the device in this state can lock an otherwise-insecure
6631      * device by first calling {@link #resetPassword} to set the password and then lock the device.
6632      * <p>
6633      * This method can be called on the {@link DevicePolicyManager} instance returned by
6634      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile as
6635      * well as the managed profile.
6636      * <p>
6637      * NOTE: In order to lock the parent profile and evict the encryption key of the managed
6638      * profile, {@link #lockNow()} must be called twice: First, {@link #lockNow()} should be called
6639      * on the {@link DevicePolicyManager} instance returned by
6640      * {@link #getParentProfileInstance(ComponentName)}, then {@link #lockNow(int)} should be
6641      * called on the {@link DevicePolicyManager} instance associated with the managed profile,
6642      * with the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag.
6643      * Calling the method twice in this order ensures that all users are locked and does not
6644      * stop the device admin on the managed profile from issuing a second call to lock its own
6645      * profile.
6646      * <p>
6647      * NOTE: on {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, this
6648      * method doesn't turn off the screen as it would be a driving safety distraction.
6649      *
6650      * @param flags May be 0 or {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}.
6651      * @throws SecurityException if the calling application does not own an active administrator
6652      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} and the does not hold
6653      *             the {@link android.Manifest.permission#LOCK_DEVICE} permission, or
6654      *             the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is passed by an
6655      *             application that is not a profile owner of a managed profile.
6656      * @throws IllegalArgumentException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is
6657      *             passed when locking the parent profile.
6658      * @throws UnsupportedOperationException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}
6659      *             flag is passed when {@link #getStorageEncryptionStatus} does not return
6660      *             {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
6661      */
6662     @RequiresPermission(value = LOCK_DEVICE, conditional = true)
lockNow(@ockNowFlag int flags)6663     public void lockNow(@LockNowFlag int flags) {
6664         if (mService != null) {
6665             try {
6666                 mService.lockNow(flags, mContext.getPackageName(), mParentInstance);
6667             } catch (RemoteException e) {
6668                 throw e.rethrowFromSystemServer();
6669             }
6670         }
6671     }
6672 
6673     /**
6674      * Flag for {@link #wipeData(int)}: also erase the device's adopted external storage (such as
6675      * adopted SD cards).
6676      * @see <a href="{@docRoot}about/versions/marshmallow/android-6.0.html#adoptable-storage">
6677      *     Adoptable Storage Devices</a>
6678      */
6679     public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
6680 
6681     /**
6682      * Flag for {@link #wipeData(int)}: also erase the factory reset protection
6683      * data.
6684      *
6685      * <p>This flag may only be set by device owner admins; if it is set by
6686      * other admins a {@link SecurityException} will be thrown.
6687      */
6688     public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
6689 
6690     /**
6691      * Flag for {@link #wipeData(int)}: also erase the device's eUICC data.
6692      */
6693     public static final int WIPE_EUICC = 0x0004;
6694 
6695     /**
6696      * Flag for {@link #wipeData(int)}: won't show reason for wiping to the user.
6697      */
6698     public static final int WIPE_SILENTLY = 0x0008;
6699 
6700     /**
6701      * See {@link #wipeData(int, CharSequence)}
6702      *
6703      * @param flags Bit mask of additional options: currently supported flags are
6704      *              {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA},
6705      *              {@link #WIPE_EUICC} and {@link #WIPE_SILENTLY}.
6706      * @throws SecurityException if the calling application does not own an active
6707      *                           administrator
6708      *                           that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} and is
6709      *                           not granted the
6710      *                           {@link android.Manifest.permission#MASTER_CLEAR} or
6711      *                           {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_WIPE_DATA}
6712      *                            permissions.
6713      * @throws IllegalStateException if called on last full-user or system-user
6714      * @see #wipeDevice(int)
6715      * @see #wipeData(int, CharSequence)
6716      */
6717     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIPE_DATA, conditional = true)
wipeData(int flags)6718     public void wipeData(int flags) {
6719         wipeDataInternal(flags,
6720                 /* wipeReasonForUser= */ "",
6721                 /* factoryReset= */ false);
6722     }
6723 
6724     /**
6725      * Ask that all user data be wiped.
6726      *
6727      * <p>
6728      * If called as a secondary user or managed profile, the user itself and its associated user
6729      * data will be wiped. In particular, If the caller is a profile owner of an
6730      * organization-owned managed profile, calling this method will relinquish the device for
6731      * personal use, removing the managed profile and all policies set by the profile owner.
6732      * </p>
6733      *
6734      * <p> Calling this method from the primary user will only work if the calling app is
6735      * targeting SDK level {@link Build.VERSION_CODES#TIRAMISU} or below, in which case it will
6736      * cause the device to reboot, erasing all device data - including all the secondary users
6737      * and their data - while booting up. If an app targeting SDK level
6738      * {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE} and above is calling this method from the
6739      * primary user or last full user, {@link IllegalStateException} will be thrown. </p>
6740      *
6741      * If an app wants to wipe the entire device irrespective of which user they are from, they
6742      * should use {@link #wipeDevice} instead.
6743      *
6744      * @param flags Bit mask of additional options: currently supported flags are
6745      *            {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA} and
6746      *            {@link #WIPE_EUICC}.
6747      * @param reason a string that contains the reason for wiping data, which can be
6748      *            presented to the user.
6749      * @throws SecurityException if the calling application does not own an active administrator
6750      *            that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} and is not granted the
6751      *            {@link android.Manifest.permission#MASTER_CLEAR} or
6752      *            {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_WIPE_DATA} permissions.
6753      * @throws IllegalArgumentException if the input reason string is null or empty, or if
6754      *            {@link #WIPE_SILENTLY} is set.
6755      * @throws IllegalStateException if called on last full-user or system-user
6756      * @see #wipeDevice(int)
6757      * @see #wipeData(int)
6758      */
6759     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIPE_DATA, conditional = true)
wipeData(int flags, @NonNull CharSequence reason)6760     public void wipeData(int flags, @NonNull CharSequence reason) {
6761         Objects.requireNonNull(reason, "reason string is null");
6762         Preconditions.checkStringNotEmpty(reason, "reason string is empty");
6763         Preconditions.checkArgument((flags & WIPE_SILENTLY) == 0, "WIPE_SILENTLY cannot be set");
6764         wipeDataInternal(flags, reason.toString(), /* factoryReset= */ false);
6765     }
6766 
6767     /**
6768      * Ask that the device be wiped and factory reset.
6769      *
6770      * <p>
6771      * The calling Device Owner or Organization Owned Profile Owner must have requested
6772      * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to be able to call this method; if it has
6773      * not, a security exception will be thrown.
6774      *
6775      * @param flags Bit mask of additional options: currently supported flags are
6776      *              {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA},
6777      *              {@link #WIPE_EUICC} and {@link #WIPE_SILENTLY}.
6778      * @throws SecurityException if the calling application does not own an active administrator
6779      *                       that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} and is not
6780      *                       granted the {@link android.Manifest.permission#MASTER_CLEAR}
6781      *                       or both the
6782      *                       {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_WIPE_DATA} and
6783      *                       {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_ACROSS_USERS}
6784      *                       permissions.
6785      * @see #wipeData(int)
6786      * @see #wipeData(int, CharSequence)
6787      */
6788     // TODO(b/255323293) Add host-side tests
6789     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIPE_DATA, conditional = true)
wipeDevice(int flags)6790     public void wipeDevice(int flags) {
6791         wipeDataInternal(flags,
6792                 /* wipeReasonForUser= */ "",
6793                 /* factoryReset= */ true);
6794     }
6795 
6796     /**
6797      * Internal function for {@link #wipeData(int)}, {@link #wipeData(int, CharSequence)}
6798      * and {@link #wipeDevice(int)} to call.
6799      *
6800      * @hide
6801      * @see #wipeData(int)
6802      * @see #wipeData(int, CharSequence)
6803      * @see #wipeDevice(int)
6804      */
wipeDataInternal(int flags, @NonNull String wipeReasonForUser, boolean factoryReset)6805     private void wipeDataInternal(int flags, @NonNull String wipeReasonForUser,
6806             boolean factoryReset) {
6807         if (mService != null) {
6808             try {
6809                 mService.wipeDataWithReason(mContext.getPackageName(), flags, wipeReasonForUser,
6810                         mParentInstance, factoryReset);
6811             } catch (RemoteException e) {
6812                 throw e.rethrowFromSystemServer();
6813             }
6814         }
6815     }
6816 
6817     /**
6818      * Callable by device owner or profile owner of an organization-owned device, to set a
6819      * factory reset protection (FRP) policy. When a new policy is set, the system
6820      * notifies the FRP management agent of a policy change by broadcasting
6821      * {@code ACTION_RESET_PROTECTION_POLICY_CHANGED}.
6822      *
6823      * @param admin  Which {@link DeviceAdminReceiver} this request is associated with. Null if the
6824      *               caller is not a device admin
6825      * @param policy the new FRP policy, or {@code null} to clear the current policy.
6826      * @throws SecurityException if {@code admin} is not a device owner or a profile owner of
6827      *                           an organization-owned device.
6828      * @throws UnsupportedOperationException if factory reset protection is not
6829      *                           supported on the device.
6830      */
6831     @RequiresPermission(value = MANAGE_DEVICE_POLICY_FACTORY_RESET, conditional = true)
setFactoryResetProtectionPolicy(@ullable ComponentName admin, @Nullable FactoryResetProtectionPolicy policy)6832     public void setFactoryResetProtectionPolicy(@Nullable ComponentName admin,
6833             @Nullable FactoryResetProtectionPolicy policy) {
6834         throwIfParentInstance("setFactoryResetProtectionPolicy");
6835         if (mService != null) {
6836             try {
6837                 mService.setFactoryResetProtectionPolicy(admin, mContext.getPackageName(), policy);
6838             } catch (RemoteException e) {
6839                 throw e.rethrowFromSystemServer();
6840             }
6841         }
6842     }
6843 
6844     /**
6845      * Callable by device owner or profile owner of an organization-owned device, to retrieve
6846      * the current factory reset protection (FRP) policy set previously by
6847      * {@link #setFactoryResetProtectionPolicy}.
6848      * <p>
6849      * This method can also be called by the FRP management agent on device or with the permission
6850      * {@link android.Manifest.permission#MASTER_CLEAR}, in which case, it can pass {@code null}
6851      * as the ComponentName.
6852      *
6853      * @param admin Which {@link DeviceAdminReceiver} this request is associated with or
6854      *              {@code null} if the caller is not a device admin
6855      * @return The current FRP policy object or {@code null} if no policy is set.
6856      * @throws SecurityException if {@code admin} is not a device owner, a profile owner of
6857      *                           an organization-owned device or the FRP management agent.
6858      * @throws UnsupportedOperationException if factory reset protection is not
6859      *                           supported on the device.
6860      */
6861     @RequiresPermission(value = MANAGE_DEVICE_POLICY_FACTORY_RESET, conditional = true)
getFactoryResetProtectionPolicy( @ullable ComponentName admin)6862     public @Nullable FactoryResetProtectionPolicy getFactoryResetProtectionPolicy(
6863             @Nullable ComponentName admin) {
6864         throwIfParentInstance("getFactoryResetProtectionPolicy");
6865         if (mService != null) {
6866             try {
6867                 return mService.getFactoryResetProtectionPolicy(admin);
6868             } catch (RemoteException e) {
6869                 throw e.rethrowFromSystemServer();
6870             }
6871         }
6872         return null;
6873     }
6874 
6875     /**
6876      * Send a lost mode location update to the admin. This API is limited to organization-owned
6877      * devices, which includes devices with a device owner or devices with a profile owner on an
6878      * organization-owned managed profile.
6879      *
6880      * <p>The caller must hold the
6881      * {@link android.Manifest.permission#TRIGGER_LOST_MODE} permission.
6882      *
6883      * <p>Register a broadcast receiver to receive lost mode location updates. This receiver should
6884      * subscribe to the {@link #ACTION_LOST_MODE_LOCATION_UPDATE} action and receive the location
6885      * from an intent extra {@link #EXTRA_LOST_MODE_LOCATION}.
6886      *
6887      * <p> Not for use by third-party applications.
6888      *
6889      * @param executor The executor through which the callback should be invoked.
6890      * @param callback A callback object that will inform the caller whether a lost mode location
6891      *                 update was successfully sent
6892      * @hide
6893      */
6894     @SystemApi
6895     @RequiresPermission(android.Manifest.permission.TRIGGER_LOST_MODE)
sendLostModeLocationUpdate(@onNull @allbackExecutor Executor executor, @NonNull Consumer<Boolean> callback)6896     public void sendLostModeLocationUpdate(@NonNull @CallbackExecutor Executor executor,
6897             @NonNull Consumer<Boolean> callback) {
6898         throwIfParentInstance("sendLostModeLocationUpdate");
6899         if (mService == null) {
6900             executeCallback(AndroidFuture.completedFuture(false), executor, callback);
6901             return;
6902         }
6903         try {
6904             final AndroidFuture<Boolean> future = new AndroidFuture<>();
6905             mService.sendLostModeLocationUpdate(future);
6906             executeCallback(future, executor, callback);
6907         } catch (RemoteException e) {
6908             throw e.rethrowFromSystemServer();
6909         }
6910     }
6911 
executeCallback(AndroidFuture<Boolean> future, @CallbackExecutor @NonNull Executor executor, Consumer<Boolean> callback)6912     private void executeCallback(AndroidFuture<Boolean> future,
6913             @CallbackExecutor @NonNull Executor executor,
6914             Consumer<Boolean> callback) {
6915         future.whenComplete((result, error) -> executor.execute(() -> {
6916             final long token = Binder.clearCallingIdentity();
6917             try {
6918                 if (error != null) {
6919                     callback.accept(false);
6920                 } else {
6921                     callback.accept(result);
6922                 }
6923             } finally {
6924                 Binder.restoreCallingIdentity(token);
6925             }
6926         }));
6927     }
6928 
6929     /**
6930      * Called by an application that is administering the device to set the
6931      * global proxy and exclusion list.
6932      * <p>
6933      * The calling device admin must have requested
6934      * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
6935      * this method; if it has not, a security exception will be thrown.
6936      * Only the first device admin can set the proxy. If a second admin attempts
6937      * to set the proxy, the {@link ComponentName} of the admin originally setting the
6938      * proxy will be returned. If successful in setting the proxy, {@code null} will
6939      * be returned.
6940      * The method can be called repeatedly by the device admin alrady setting the
6941      * proxy to update the proxy and exclusion list.
6942      *
6943      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6944      * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
6945      *            Pass Proxy.NO_PROXY to reset the proxy.
6946      * @param exclusionList a list of domains to be excluded from the global proxy.
6947      * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
6948      *            of the device admin that sets the proxy.
6949      * @hide
6950      */
6951     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setGlobalProxy(@onNull ComponentName admin, Proxy proxySpec, List<String> exclusionList )6952     public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
6953             List<String> exclusionList ) {
6954         throwIfParentInstance("setGlobalProxy");
6955         if (proxySpec == null) {
6956             throw new NullPointerException();
6957         }
6958         if (mService != null) {
6959             try {
6960                 String hostSpec;
6961                 String exclSpec;
6962                 if (proxySpec.equals(Proxy.NO_PROXY)) {
6963                     hostSpec = null;
6964                     exclSpec = null;
6965                 } else {
6966                     if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
6967                         throw new IllegalArgumentException();
6968                     }
6969                     final Pair<String, String> proxyParams =
6970                             getProxyParameters(proxySpec, exclusionList);
6971                     hostSpec = proxyParams.first;
6972                     exclSpec = proxyParams.second;
6973                 }
6974                 return mService.setGlobalProxy(admin, hostSpec, exclSpec);
6975             } catch (RemoteException e) {
6976                 throw e.rethrowFromSystemServer();
6977             }
6978         }
6979         return null;
6980     }
6981 
6982     /**
6983      * Build HTTP proxy parameters for {@link IDevicePolicyManager#setGlobalProxy}.
6984      * @throws IllegalArgumentException Invalid proxySpec
6985      * @hide
6986      */
6987     @VisibleForTesting
getProxyParameters(Proxy proxySpec, List<String> exclusionList)6988     public Pair<String, String> getProxyParameters(Proxy proxySpec, List<String> exclusionList) {
6989         InetSocketAddress sa = (InetSocketAddress) proxySpec.address();
6990         String hostName = sa.getHostName();
6991         int port = sa.getPort();
6992         final List<String> trimmedExclList;
6993         if (exclusionList == null) {
6994             trimmedExclList = Collections.emptyList();
6995         } else {
6996             trimmedExclList = new ArrayList<>(exclusionList.size());
6997             for (String exclDomain : exclusionList) {
6998                 trimmedExclList.add(exclDomain.trim());
6999             }
7000         }
7001         final ProxyInfo info = ProxyInfo.buildDirectProxy(hostName, port, trimmedExclList);
7002         // The hostSpec is built assuming that there is a specified port and hostname,
7003         // but ProxyInfo.isValid() accepts 0 / empty as unspecified: also reject them.
7004         if (port == 0 || TextUtils.isEmpty(hostName) || !info.isValid()) {
7005             throw new IllegalArgumentException();
7006         }
7007 
7008         return new Pair<>(hostName + ":" + port, TextUtils.join(",", trimmedExclList));
7009     }
7010 
7011     /**
7012      * Set a network-independent global HTTP proxy. This is not normally what you want for typical
7013      * HTTP proxies - they are generally network dependent. However if you're doing something
7014      * unusual like general internal filtering this may be useful. On a private network where the
7015      * proxy is not accessible, you may break HTTP using this.
7016      * <p>
7017      * This method requires the caller to be the device owner.
7018      * <p>
7019      * This proxy is only a recommendation and it is possible that some apps will ignore it.
7020      * <p>
7021      * Note: The device owner won't be able to set a global HTTP proxy if there are unaffiliated
7022      * secondary users or profiles on the device. It's recommended that affiliation ids are set for
7023      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
7024      *
7025      * @see ProxyInfo
7026      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7027      * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A
7028      *            {@code null} value will clear the global HTTP proxy.
7029      * @throws SecurityException if {@code admin} is not the device owner.
7030      */
setRecommendedGlobalProxy(@onNull ComponentName admin, @Nullable ProxyInfo proxyInfo)7031     public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
7032             proxyInfo) {
7033         throwIfParentInstance("setRecommendedGlobalProxy");
7034         if (mService != null) {
7035             try {
7036                 mService.setRecommendedGlobalProxy(admin, proxyInfo);
7037             } catch (RemoteException e) {
7038                 throw e.rethrowFromSystemServer();
7039             }
7040         }
7041     }
7042 
7043     /**
7044      * Returns the component name setting the global proxy.
7045      * @return ComponentName object of the device admin that set the global proxy, or {@code null}
7046      *         if no admin has set the proxy.
7047      * @hide
7048      */
getGlobalProxyAdmin()7049     public @Nullable ComponentName getGlobalProxyAdmin() {
7050         if (mService != null) {
7051             try {
7052                 return mService.getGlobalProxyAdmin(myUserId());
7053             } catch (RemoteException e) {
7054                 throw e.rethrowFromSystemServer();
7055             }
7056         }
7057         return null;
7058     }
7059 
7060     /**
7061      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
7062      * indicating that encryption is not supported.
7063      */
7064     public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
7065 
7066     /**
7067      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
7068      * indicating that encryption is supported, but is not currently active.
7069      * <p>
7070      * {@link #getStorageEncryptionStatus} can only return this value on devices that use Full Disk
7071      * Encryption.  Support for Full Disk Encryption was entirely removed in API level 33, having
7072      * been replaced by File Based Encryption.  Devices that use File Based Encryption always
7073      * automatically activate their encryption on first boot.
7074      * <p>
7075      * {@link #setStorageEncryption} can still return this value for an unrelated reason, but {@link
7076      * #setStorageEncryption} is deprecated since it doesn't do anything useful.
7077      */
7078     public static final int ENCRYPTION_STATUS_INACTIVE = 1;
7079 
7080     /**
7081      * Result code for {@link #getStorageEncryptionStatus}: indicating that encryption is not
7082      * currently active, but is currently being activated.
7083      * <p>
7084      * @deprecated This result code has never actually been used, so there is no reason for apps to
7085      * check for it.
7086      */
7087     @Deprecated
7088     public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
7089 
7090     /**
7091      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
7092      * indicating that encryption is active.
7093      * <p>
7094      * {@link #getStorageEncryptionStatus} can only return this value for apps targeting API level
7095      * 23 or lower, or on devices that use Full Disk Encryption.  Support for Full Disk Encryption
7096      * was entirely removed in API level 33, having been replaced by File Based Encryption.  The
7097      * result code {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER} is used on devices that use File Based
7098      * Encryption, except when the app targets API level 23 or lower.
7099      * <p>
7100      * {@link #setStorageEncryption} can still return this value for an unrelated reason, but {@link
7101      * #setStorageEncryption} is deprecated since it doesn't do anything useful.
7102      */
7103     public static final int ENCRYPTION_STATUS_ACTIVE = 3;
7104 
7105     /**
7106      * Result code for {@link #getStorageEncryptionStatus}: indicating that encryption is active,
7107      * but the encryption key is not cryptographically protected by the user's credentials.
7108      * <p>
7109      * This value can only be returned on devices that use Full Disk Encryption.  Support for Full
7110      * Disk Encryption was entirely removed in API level 33, having been replaced by File Based
7111      * Encryption.  With File Based Encryption, each user's credential-encrypted storage is always
7112      * cryptographically protected by the user's credentials.
7113      */
7114     public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
7115 
7116     /**
7117      * Result code for {@link #getStorageEncryptionStatus}:
7118      * indicating that encryption is active and the encryption key is tied to the user or profile.
7119      * <p>
7120      * This value is only returned to apps targeting API level 24 and above. For apps targeting
7121      * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the
7122      * encryption key is specific to the user or profile.
7123      */
7124     public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5;
7125 
7126     /**
7127      * Activity action: begin the process of encrypting data on the device.  This activity should
7128      * be launched after using {@link #setStorageEncryption} to request encryption be activated.
7129      * After resuming from this activity, use {@link #getStorageEncryption}
7130      * to check encryption status.  However, on some devices this activity may never return, as
7131      * it may trigger a reboot and in some cases a complete data wipe of the device.
7132      */
7133     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
7134     public static final String ACTION_START_ENCRYPTION
7135             = "android.app.action.START_ENCRYPTION";
7136 
7137     /**
7138      * Activity action: launch the DPC to check policy compliance. This intent is launched when
7139      * the user taps on the notification about personal apps suspension. When handling this intent
7140      * the DPC must check if personal apps should still be suspended and either unsuspend them or
7141      * instruct the user on how to resolve the noncompliance causing the suspension.
7142      *
7143      * @see #setPersonalAppsSuspended
7144      */
7145     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
7146     public static final String ACTION_CHECK_POLICY_COMPLIANCE =
7147             "android.app.action.CHECK_POLICY_COMPLIANCE";
7148 
7149     /**
7150      * Broadcast action: notify managed provisioning that PO/DO provisioning has completed.
7151      *
7152      * @hide
7153      */
7154     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
7155     public static final String ACTION_PROVISIONING_COMPLETED =
7156             "android.app.action.PROVISIONING_COMPLETED";
7157 
7158     /**
7159      * Extra for {@link #ACTION_PROVISIONING_COMPLETED} to indicate the provisioning action that has
7160      * been completed, this can either be {@link #ACTION_PROVISION_MANAGED_PROFILE},
7161      * {@link #ACTION_PROVISION_MANAGED_DEVICE}, or {@link #ACTION_PROVISION_MANAGED_USER}.
7162      *
7163      * @hide
7164      */
7165     public static final String EXTRA_PROVISIONING_ACTION =
7166             "android.app.extra.PROVISIONING_ACTION";
7167 
7168     /**
7169      * Broadcast action: notify system that a new (Android) user was added when the device is
7170      * managed by a device owner, so receivers can show the proper disclaimer to the (human) user.
7171      *
7172      * @hide
7173      */
7174     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
7175     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
7176     public static final String ACTION_SHOW_NEW_USER_DISCLAIMER =
7177             "android.app.action.SHOW_NEW_USER_DISCLAIMER";
7178 
7179     /**
7180      * Widgets are enabled in keyguard
7181      */
7182     public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
7183 
7184     /**
7185      * Disable all keyguard widgets. Has no effect between {@link
7186      * android.os.Build.VERSION_CODES#LOLLIPOP} and {@link
7187      * android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} (both inclusive), since keyguard widget is
7188      * only supported on Android versions lower than 5.0 and versions higher than 14.
7189      */
7190     public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
7191 
7192     /**
7193      * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
7194      */
7195     public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
7196 
7197     /**
7198      * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
7199      */
7200     public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
7201 
7202     /**
7203      * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
7204      */
7205     public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
7206 
7207     /**
7208      * Disable trust agents on secure keyguard screens (e.g. PIN/Pattern/Password).
7209      * By setting this flag alone, all trust agents are disabled. If the admin then wants to
7210      * allowlist specific features of some trust agent, {@link #setTrustAgentConfiguration} can be
7211      * used in conjuction to set trust-agent-specific configurations.
7212      */
7213     public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
7214 
7215     /**
7216      * Disable fingerprint authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
7217      */
7218     public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
7219 
7220     /**
7221      * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
7222      * @deprecated This flag was added in version {@link android.os.Build.VERSION_CODES#N}, but it
7223      * never had any effect.
7224      */
7225     @Deprecated
7226     public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
7227 
7228     /**
7229      * Disable face authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
7230      */
7231     public static final int KEYGUARD_DISABLE_FACE = 1 << 7;
7232 
7233     /**
7234      * Disable iris authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
7235      */
7236     public static final int KEYGUARD_DISABLE_IRIS = 1 << 8;
7237 
7238     /**
7239      * Disable all keyguard shortcuts.
7240      */
7241     public static final int KEYGUARD_DISABLE_SHORTCUTS_ALL = 1 << 9;
7242 
7243     /**
7244      * NOTE: Please remember to update the DevicePolicyManagerTest's testKeyguardDisabledFeatures
7245      * CTS test when adding to the list above.
7246      */
7247 
7248     /**
7249      * Disable all biometric authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
7250      */
7251     public static final int KEYGUARD_DISABLE_BIOMETRICS =
7252             DevicePolicyManager.KEYGUARD_DISABLE_FACE
7253             | DevicePolicyManager.KEYGUARD_DISABLE_IRIS
7254             | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
7255 
7256     /**
7257      * Disable all current and future keyguard customizations.
7258      */
7259     public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
7260 
7261     /**
7262      * Keyguard features that when set on a non-organization-owned managed profile that doesn't
7263      * have its own challenge will affect the profile's parent user. These can also be set on the
7264      * managed profile's parent {@link DevicePolicyManager} instance to explicitly control the
7265      * parent user.
7266      *
7267      * <p>
7268      * Organization-owned managed profile supports disabling additional keyguard features on the
7269      * parent user as defined in {@link #ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY}.
7270      *
7271      * @hide
7272      */
7273     public static final int NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
7274             DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
7275             | DevicePolicyManager.KEYGUARD_DISABLE_BIOMETRICS;
7276 
7277     /**
7278      * Keyguard features that when set by the profile owner of an organization-owned managed
7279      * profile will affect the profile's parent user if set on the managed profile's parent
7280      * {@link DevicePolicyManager} instance.
7281      *
7282      * @hide
7283      */
7284     public static final int ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY =
7285             DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA
7286                     | DevicePolicyManager.KEYGUARD_DISABLE_SECURE_NOTIFICATIONS
7287                     | DevicePolicyManager.KEYGUARD_DISABLE_SHORTCUTS_ALL
7288                     | DevicePolicyManager.KEYGUARD_DISABLE_WIDGETS_ALL;
7289 
7290     /**
7291      * Keyguard features that when set on a normal or organization-owned managed profile, have
7292      * the potential to affect the profile's parent user.
7293      *
7294      * @hide
7295      */
7296     public static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
7297             DevicePolicyManager.NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER
7298                     | DevicePolicyManager.ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY;
7299 
7300     /**
7301      * @deprecated This method does not actually modify the storage encryption of the device.
7302      * It has never affected the encryption status of a device.
7303      *
7304      * Called by an application that is administering the device to request that the storage system
7305      * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
7306      * <p>
7307      * When multiple device administrators attempt to control device encryption, the most secure,
7308      * supported setting will always be used. If any device administrator requests device
7309      * encryption, it will be enabled; Conversely, if a device administrator attempts to disable
7310      * device encryption while another device administrator has enabled it, the call to disable will
7311      * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
7312      * <p>
7313      * This policy controls encryption of the secure (application data) storage area. Data written
7314      * to other storage areas may or may not be encrypted, and this policy does not require or
7315      * control the encryption of any other storage areas. There is one exception: If
7316      * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the
7317      * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be
7318      * written to disk within the encrypted storage area.
7319      * <p>
7320      * Important Note: On some devices, it is possible to encrypt storage without requiring the user
7321      * to create a device PIN or Password. In this case, the storage is encrypted, but the
7322      * encryption key may not be fully secured. For maximum security, the administrator should also
7323      * require (and check for) a pattern, PIN, or password.
7324      *
7325      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7326      * @param encrypt true to request encryption, false to release any previous request
7327      * @return the new total request status (for all active admins), or {@link
7328      *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user.
7329      *         Will be one of {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link
7330      *         #ENCRYPTION_STATUS_INACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value
7331      *         of the requests; use {@link #getStorageEncryptionStatus()} to query the actual device
7332      *         state.
7333      *
7334      * @throws SecurityException if {@code admin} is not an active administrator or does not use
7335      *             {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE}
7336      */
7337     @Deprecated
setStorageEncryption(@onNull ComponentName admin, boolean encrypt)7338     public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
7339         throwIfParentInstance("setStorageEncryption");
7340         if (mService != null) {
7341             try {
7342                 return mService.setStorageEncryption(admin, encrypt);
7343             } catch (RemoteException e) {
7344                 throw e.rethrowFromSystemServer();
7345             }
7346         }
7347         return ENCRYPTION_STATUS_UNSUPPORTED;
7348     }
7349 
7350     /**
7351      * @deprecated This method only returns the value set by {@link #setStorageEncryption}.
7352      * It does not actually reflect the storage encryption status.
7353      * Use {@link #getStorageEncryptionStatus} for that.
7354      *
7355      * Called by an application that is administering the device to
7356      * determine the requested setting for secure storage.
7357      *
7358      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
7359      * this will return the requested encryption setting as an aggregate of all active
7360      * administrators.
7361      * @return true if the admin(s) are requesting encryption, false if not.
7362      */
7363     @Deprecated
getStorageEncryption(@ullable ComponentName admin)7364     public boolean getStorageEncryption(@Nullable ComponentName admin) {
7365         throwIfParentInstance("getStorageEncryption");
7366         if (mService != null) {
7367             try {
7368                 return mService.getStorageEncryption(admin, myUserId());
7369             } catch (RemoteException e) {
7370                 throw e.rethrowFromSystemServer();
7371             }
7372         }
7373         return false;
7374     }
7375 
7376     /**
7377      * Called by an application that is administering the device to
7378      * determine the current encryption status of the device.
7379      * <p>
7380      * Depending on the returned status code, the caller may proceed in different
7381      * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
7382      * storage system does not support encryption.  If the
7383      * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
7384      * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
7385      * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
7386      * storage system has enabled encryption but no password is set so further action
7387      * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING},
7388      * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER},
7389      * no further action is required.
7390      *
7391      * @return current status of encryption. The value will be one of
7392      * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
7393      * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
7394      * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
7395      *
7396      * @throws SecurityException if called on a parent instance.
7397      */
getStorageEncryptionStatus()7398     public int getStorageEncryptionStatus() {
7399         throwIfParentInstance("getStorageEncryptionStatus");
7400         return getStorageEncryptionStatus(myUserId());
7401     }
7402 
7403     /** @hide per-user version */
7404     @UnsupportedAppUsage
getStorageEncryptionStatus(int userHandle)7405     public int getStorageEncryptionStatus(int userHandle) {
7406         if (mService != null) {
7407             try {
7408                 return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle);
7409             } catch (RemoteException e) {
7410                 throw e.rethrowFromSystemServer();
7411             }
7412         }
7413         return ENCRYPTION_STATUS_UNSUPPORTED;
7414     }
7415 
7416     /**
7417      * Mark a CA certificate as approved by the device user. This means that they have been notified
7418      * of the installation, were made aware of the risks, viewed the certificate and still wanted to
7419      * keep the certificate on the device.
7420      *
7421      * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to
7422      * this certificate.
7423      *
7424      * @hide
7425      */
approveCaCert(String alias, int userHandle, boolean approval)7426     public boolean approveCaCert(String alias, int userHandle, boolean approval) {
7427         if (mService != null) {
7428             try {
7429                 return mService.approveCaCert(alias, userHandle, approval);
7430             } catch (RemoteException e) {
7431                 throw e.rethrowFromSystemServer();
7432             }
7433         }
7434         return false;
7435     }
7436 
7437     /**
7438      * Check whether a CA certificate has been approved by the device user.
7439      *
7440      * @hide
7441      */
isCaCertApproved(String alias, int userHandle)7442     public boolean isCaCertApproved(String alias, int userHandle) {
7443         if (mService != null) {
7444             try {
7445                 return mService.isCaCertApproved(alias, userHandle);
7446             } catch (RemoteException e) {
7447                 throw e.rethrowFromSystemServer();
7448             }
7449         }
7450         return false;
7451     }
7452 
7453     /**
7454      * Installs the given certificate as a user CA.
7455      * <p>
7456      * Inserted user CAs aren't automatically trusted by apps in Android 7.0 (API level 24) and
7457      * higher. App developers can change the default behavior for an app by adding a
7458      * <a href="{@docRoot}training/articles/security-config.html">Security Configuration
7459      * File</a> to the app manifest file.
7460      *
7461      * The caller must be a profile or device owner on that user, or a delegate package given the
7462      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
7463      * security exception will be thrown.
7464      *
7465      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7466      *              {@code null} if calling from a delegated certificate installer.
7467      * @param certBuffer encoded form of the certificate to install.
7468      *
7469      * @return false if the certBuffer cannot be parsed or installation is
7470      *         interrupted, true otherwise.
7471      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7472      *         owner.
7473      * @see #setDelegatedScopes
7474      * @see #DELEGATION_CERT_INSTALL
7475      */
installCaCert(@ullable ComponentName admin, byte[] certBuffer)7476     public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
7477         throwIfParentInstance("installCaCert");
7478         if (mService != null) {
7479             try {
7480                 return mService.installCaCert(admin, mContext.getPackageName(), certBuffer);
7481             } catch (RemoteException e) {
7482                 throw e.rethrowFromSystemServer();
7483             }
7484         }
7485         return false;
7486     }
7487 
7488     /**
7489      * Uninstalls the given certificate from trusted user CAs, if present.
7490      *
7491      * The caller must be a profile or device owner on that user, or a delegate package given the
7492      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
7493      * security exception will be thrown.
7494      *
7495      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7496      *              {@code null} if calling from a delegated certificate installer.
7497      * @param certBuffer encoded form of the certificate to remove.
7498      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7499      *         owner.
7500      * @see #setDelegatedScopes
7501      * @see #DELEGATION_CERT_INSTALL
7502      */
uninstallCaCert(@ullable ComponentName admin, byte[] certBuffer)7503     public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
7504         throwIfParentInstance("uninstallCaCert");
7505         if (mService != null) {
7506             try {
7507                 final String alias = getCaCertAlias(certBuffer);
7508                 mService.uninstallCaCerts(admin, mContext.getPackageName(), new String[] {alias});
7509             } catch (CertificateException e) {
7510                 Log.w(TAG, "Unable to parse certificate", e);
7511             } catch (RemoteException e) {
7512                 throw e.rethrowFromSystemServer();
7513             }
7514         }
7515     }
7516 
7517     /**
7518      * Returns all CA certificates that are currently trusted, excluding system CA certificates.
7519      * If a user has installed any certificates by other means than device policy these will be
7520      * included too.
7521      *
7522      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7523      *              {@code null} if calling from a delegated certificate installer.
7524      * @return a List of byte[] arrays, each encoding one user CA certificate.
7525      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7526      *         owner.
7527      */
getInstalledCaCerts(@ullable ComponentName admin)7528     public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
7529         final List<byte[]> certs = new ArrayList<byte[]>();
7530         throwIfParentInstance("getInstalledCaCerts");
7531         if (mService != null) {
7532             try {
7533                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
7534                 final TrustedCertificateStore certStore = new TrustedCertificateStore();
7535                 for (String alias : certStore.userAliases()) {
7536                     try {
7537                         certs.add(certStore.getCertificate(alias).getEncoded());
7538                     } catch (CertificateException ce) {
7539                         Log.w(TAG, "Could not encode certificate: " + alias, ce);
7540                     }
7541                 }
7542             } catch (RemoteException re) {
7543                 throw re.rethrowFromSystemServer();
7544             }
7545         }
7546         return certs;
7547     }
7548 
7549     /**
7550      * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
7551      * means other than device policy will also be removed, except for system CA certificates.
7552      *
7553      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7554      *              {@code null} if calling from a delegated certificate installer.
7555      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7556      *         owner.
7557      */
uninstallAllUserCaCerts(@ullable ComponentName admin)7558     public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
7559         throwIfParentInstance("uninstallAllUserCaCerts");
7560         if (mService != null) {
7561             try {
7562                 mService.uninstallCaCerts(admin, mContext.getPackageName(),
7563                         new TrustedCertificateStore().userAliases() .toArray(new String[0]));
7564             } catch (RemoteException re) {
7565                 throw re.rethrowFromSystemServer();
7566             }
7567         }
7568     }
7569 
7570     /**
7571      * Returns whether this certificate is installed as a trusted CA.
7572      *
7573      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7574      *              {@code null} if calling from a delegated certificate installer.
7575      * @param certBuffer encoded form of the certificate to look up.
7576      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7577      *         owner.
7578      */
hasCaCertInstalled(@ullable ComponentName admin, byte[] certBuffer)7579     public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
7580         throwIfParentInstance("hasCaCertInstalled");
7581         if (mService != null) {
7582             try {
7583                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
7584                 return getCaCertAlias(certBuffer) != null;
7585             } catch (RemoteException re) {
7586                 throw re.rethrowFromSystemServer();
7587             } catch (CertificateException ce) {
7588                 Log.w(TAG, "Could not parse certificate", ce);
7589             }
7590         }
7591         return false;
7592     }
7593 
7594     /**
7595      * This API can be called by the following to install a certificate and corresponding
7596      * private key:
7597      * <ul>
7598      *    <li>Device owner</li>
7599      *    <li>Profile owner</li>
7600      *    <li>Delegated certificate installer</li>
7601      *    <li>Credential management app</li>
7602      *    <li>An app that holds the
7603      *    {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission</li>
7604      * </ul>
7605      * All apps within the profile will be able to access the certificate and use the private key,
7606      * given direct user approval.
7607      *
7608      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7609      * can call this API. However, this API sets the key pair as user selectable by default,
7610      * which is not permitted when called by the credential management app. Instead,
7611      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)} should be
7612      * called with {@link #INSTALLKEY_SET_USER_SELECTABLE} not set as a flag.
7613      *
7614      * <p>Access to the installed credentials will not be granted to the caller of this API without
7615      * direct user approval. This is for security - should a certificate installer become
7616      * compromised, certificates it had already installed will be protected.
7617      *
7618      * <p>If the installer must have access to the credentials, call
7619      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead.
7620      *
7621      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
7622      * have been given to access the key and certificates associated with this alias will be
7623      * revoked.
7624      *
7625      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7626      *            {@code null} if the caller is not a device admin.
7627      * @param privKey The private key to install.
7628      * @param cert The certificate to install.
7629      * @param alias The private key alias under which to install the certificate. If a certificate
7630      * with that alias already exists, it will be overwritten.
7631      * @return {@code true} if the keys were installed, {@code false} otherwise.
7632      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7633      *         owner, or {@code admin} is null and the calling application does not have the
7634      *         {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission.
7635      * @see #setDelegatedScopes
7636      * @see #DELEGATION_CERT_INSTALL
7637      */
7638     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true)
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate cert, @NonNull String alias)7639     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
7640             @NonNull Certificate cert, @NonNull String alias) {
7641         return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false);
7642     }
7643 
7644     /**
7645      * This API can be called by the following to install a certificate chain and corresponding
7646      * private key for the leaf certificate:
7647      * <ul>
7648      *    <li>Device owner</li>
7649      *    <li>Profile owner</li>
7650      *    <li>Delegated certificate installer</li>
7651      *    <li>Credential management app</li>
7652      *    <li>An app that holds the
7653      *    {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission</li>
7654      * </ul>
7655      * All apps within the profile will be able to access the certificate chain and use the private
7656      * key, given direct user approval.
7657      *
7658      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7659      * can call this API. However, this API sets the key pair as user selectable by default,
7660      * which is not permitted when called by the credential management app. Instead,
7661      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)} should be
7662      * called with {@link #INSTALLKEY_SET_USER_SELECTABLE} not set as a flag.
7663      * Note, there can only be a credential management app on an unmanaged device.
7664      *
7665      * <p>The caller of this API may grant itself access to the certificate and private key
7666      * immediately, without user approval. It is a best practice not to request this unless strictly
7667      * necessary since it opens up additional security vulnerabilities.
7668      *
7669      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
7670      * have been given to access the key and certificates associated with this alias will be
7671      * revoked.
7672      *
7673      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7674      *        {@code null} if the caller is not a device admin.
7675      * @param privKey The private key to install.
7676      * @param certs The certificate chain to install. The chain should start with the leaf
7677      *        certificate and include the chain of trust in order. This will be returned by
7678      *        {@link android.security.KeyChain#getCertificateChain}.
7679      * @param alias The private key alias under which to install the certificate. If a certificate
7680      *        with that alias already exists, it will be overwritten.
7681      * @param requestAccess {@code true} to request that the calling app be granted access to the
7682      *        credentials immediately. Otherwise, access to the credentials will be gated by user
7683      *        approval.
7684      * @return {@code true} if the keys were installed, {@code false} otherwise.
7685      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7686      *         owner, or {@code admin} is null and the calling application does not have the
7687      *         {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission.
7688      * @see android.security.KeyChain#getCertificateChain
7689      * @see #setDelegatedScopes
7690      * @see #DELEGATION_CERT_INSTALL
7691      */
7692     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true)
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess)7693     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
7694             @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) {
7695         int flags = INSTALLKEY_SET_USER_SELECTABLE;
7696         if (requestAccess) {
7697             flags |= INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
7698         }
7699         return installKeyPair(admin, privKey, certs, alias, flags);
7700     }
7701 
7702     /**
7703      * This API can be called by the following to install a certificate chain and corresponding
7704      * private key for the leaf certificate:
7705      * <ul>
7706      *    <li>Device owner</li>
7707      *    <li>Profile owner</li>
7708      *    <li>Delegated certificate installer</li>
7709      *    <li>Credential management app</li>
7710      *    <li>An app that holds the
7711      *    {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission</li>
7712      * </ul>
7713      * All apps within the profile will be able to access the certificate chain and use the
7714      * private key, given direct user approval (if the user is allowed to select the private key).
7715      *
7716      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7717      * can call this API. If called by the credential management app:
7718      * <ul>
7719      *    <li>The componentName must be {@code null}r</li>
7720      *    <li>The alias must exist in the credential management app's
7721      *    {@link android.security.AppUriAuthenticationPolicy}</li>
7722      *    <li>The key pair must not be user selectable</li>
7723      * </ul>
7724      * Note, there can only be a credential management app on an unmanaged device.
7725      *
7726      * <p>The caller of this API may grant itself access to the certificate and private key
7727      * immediately, without user approval. It is a best practice not to request this unless strictly
7728      * necessary since it opens up additional security vulnerabilities.
7729      *
7730      * <p>Include {@link #INSTALLKEY_SET_USER_SELECTABLE} in the {@code flags} argument to allow
7731      * the user to select the key from a dialog.
7732      *
7733      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
7734      * have been given to access the key and certificates associated with this alias will be
7735      * revoked.
7736      *
7737      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7738      *        {@code null} if the caller is not a device admin.
7739      * @param privKey The private key to install.
7740      * @param certs The certificate chain to install. The chain should start with the leaf
7741      *        certificate and include the chain of trust in order. This will be returned by
7742      *        {@link android.security.KeyChain#getCertificateChain}.
7743      * @param alias The private key alias under which to install the certificate. If a certificate
7744      *        with that alias already exists, it will be overwritten.
7745      * @param flags Flags to request that the calling app be granted access to the credentials
7746      *        and set the key to be user-selectable. See {@link #INSTALLKEY_SET_USER_SELECTABLE} and
7747      *        {@link #INSTALLKEY_REQUEST_CREDENTIALS_ACCESS}.
7748      * @return {@code true} if the keys were installed, {@code false} otherwise.
7749      * @throws SecurityException if {@code admin} is not {@code null} and not a device or
7750      *        profile owner, or {@code admin} is null but the calling application is not a
7751      *        delegated certificate installer, credential management app and does not have the
7752      *        {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission.
7753      * @see android.security.KeyChain#getCertificateChain
7754      * @see #setDelegatedScopes
7755      * @see #DELEGATION_CERT_INSTALL
7756      */
7757     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true)
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, int flags)7758     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
7759             @NonNull Certificate[] certs, @NonNull String alias, int flags) {
7760         throwIfParentInstance("installKeyPair");
7761         boolean requestAccess = (flags & INSTALLKEY_REQUEST_CREDENTIALS_ACCESS)
7762                 == INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
7763         boolean isUserSelectable = (flags & INSTALLKEY_SET_USER_SELECTABLE)
7764                 == INSTALLKEY_SET_USER_SELECTABLE;
7765         try {
7766             final byte[] pemCert = Credentials.convertToPem(certs[0]);
7767             byte[] pemChain = null;
7768             if (certs.length > 1) {
7769                 pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length));
7770             }
7771             final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
7772                     .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
7773             return mService.installKeyPair(admin, mContext.getPackageName(), pkcs8Key, pemCert,
7774                     pemChain, alias, requestAccess, isUserSelectable);
7775         } catch (RemoteException e) {
7776             throw e.rethrowFromSystemServer();
7777         } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
7778             Log.w(TAG, "Failed to obtain private key material", e);
7779         } catch (CertificateException | IOException e) {
7780             Log.w(TAG, "Could not pem-encode certificate", e);
7781         }
7782         return false;
7783     }
7784 
7785     /**
7786      * This API can be called by the following to remove a certificate and private key pair
7787      * installed under a given alias:
7788      * <ul>
7789      *    <li>Device owner</li>
7790      *    <li>Profile owner</li>
7791      *    <li>Delegated certificate installer</li>
7792      *    <li>Credential management app</li>
7793      * </ul>
7794      *
7795      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7796      * can call this API. If called by the credential management app, the componentName must be
7797      * {@code null}. Note, there can only be a credential management app on an unmanaged device.
7798      *
7799      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7800      *        {@code null} if the caller is not a device admin.
7801      * @param alias The private key alias under which the certificate is installed.
7802      * @return {@code true} if the private key alias no longer exists, {@code false} otherwise.
7803      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7804      *         owner, or {@code admin} is null but the calling application is not a delegated
7805      *         certificate installer or credential management app.
7806      * @see #setDelegatedScopes
7807      * @see #DELEGATION_CERT_INSTALL
7808      */
7809     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true)
removeKeyPair(@ullable ComponentName admin, @NonNull String alias)7810     public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
7811         throwIfParentInstance("removeKeyPair");
7812         try {
7813             return mService.removeKeyPair(admin, mContext.getPackageName(), alias);
7814         } catch (RemoteException e) {
7815             throw e.rethrowFromSystemServer();
7816         }
7817     }
7818 
7819     // STOPSHIP(b/174298501): clarify the expected return value following generateKeyPair call.
7820     /**
7821      * This API can be called by the following to query whether a certificate and private key are
7822      * installed under a given alias:
7823      * <ul>
7824      *    <li>Device owner</li>
7825      *    <li>Profile owner</li>
7826      *    <li>Delegated certificate installer</li>
7827      *    <li>Credential management app</li>
7828      *    <li>An app that holds the
7829      *    {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission</li>
7830      * </ul>
7831      *
7832      * If called by the credential management app, the alias must exist in the credential
7833      * management app's {@link android.security.AppUriAuthenticationPolicy}.
7834      *
7835      * @param alias The alias under which the key pair is installed.
7836      * @return {@code true} if a key pair with this alias exists, {@code false} otherwise.
7837      * @throws SecurityException if the caller is not a device or profile owner, a delegated
7838      *         certificate installer, the credential management app and does not have the
7839      *         {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission.
7840      * @see #setDelegatedScopes
7841      * @see #DELEGATION_CERT_INSTALL
7842      */
7843     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true)
hasKeyPair(@onNull String alias)7844     public boolean hasKeyPair(@NonNull String alias) {
7845         throwIfParentInstance("hasKeyPair");
7846         try {
7847             return mService.hasKeyPair(mContext.getPackageName(), alias);
7848         } catch (RemoteException e) {
7849             throw e.rethrowFromSystemServer();
7850         }
7851     }
7852 
7853     /**
7854      * This API can be called by the following to generate a new private/public key pair:
7855      * <ul>
7856      *    <li>Device owner</li>
7857      *    <li>Profile owner</li>
7858      *    <li>Delegated certificate installer</li>
7859      *    <li>Credential management app</li>
7860      *    <li>An app that holds the
7861      *    {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission</li>
7862      * </ul>
7863      * If the device supports key generation via secure hardware, this method is useful for
7864      * creating a key in KeyChain that never left the secure hardware. Access to the key is
7865      * controlled the same way as in {@link #installKeyPair}.
7866      *
7867      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
7868      * can call this API. If called by the credential management app, the componentName must be
7869      * {@code null}. Note, there can only be a credential management app on an unmanaged device.
7870      *
7871      * <p>Because this method might take several seconds to complete, it should only be called from
7872      * a worker thread. This method returns {@code null} when called from the main thread.
7873      *
7874      * <p>This method is not thread-safe, calling it from multiple threads at the same time will
7875      * result in undefined behavior. If the calling thread is interrupted while the invocation is
7876      * in-flight, it will eventually terminate and return {@code null}.
7877      *
7878      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
7879      * have been given to access the key and certificates associated with this alias will be
7880      * revoked.
7881      *
7882      * <p>Attestation: to enable attestation, set an attestation challenge in {@code keySpec} via
7883      * {@link KeyGenParameterSpec.Builder#setAttestationChallenge}. By specifying flags to the
7884      * {@code idAttestationFlags} parameter, it is possible to request the device's unique
7885      * identity to be included in the attestation record.
7886      *
7887      * <p>Specific identifiers can be included in the attestation record, and an individual
7888      * attestation certificate can be used to sign the attestation record. To find out if the device
7889      * supports these features, refer to {@link #isDeviceIdAttestationSupported()} and
7890      * {@link #isUniqueDeviceAttestationSupported()}.
7891      *
7892      * <p>Device owner, profile owner, their delegated certificate installer and the credential
7893      * management app can use {@link #ID_TYPE_BASE_INFO} to request inclusion of the general device
7894      * information including manufacturer, model, brand, device and product in the attestation
7895      * record.
7896      * Only device owner, profile owner on an organization-owned device or affiliated user, and
7897      * their delegated certificate installers can use {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI}
7898      * and {@link #ID_TYPE_MEID} to request unique device identifiers to be attested (the serial
7899      * number, IMEI and MEID correspondingly), if supported by the device
7900      * (see {@link #isDeviceIdAttestationSupported()}).
7901      * Additionally, device owner, profile owner on an organization-owned device and their delegated
7902      * certificate installers can also request the attestation record to be signed using an
7903      * individual attestation certificate by specifying the {@link #ID_TYPE_INDIVIDUAL_ATTESTATION}
7904      * flag (if supported by the device, see {@link #isUniqueDeviceAttestationSupported()}).
7905      * <p>
7906      * If any of {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID}
7907      * is set, it is implicitly assumed that {@link #ID_TYPE_BASE_INFO} is also set.
7908      * <p>
7909      * Attestation using {@link #ID_TYPE_INDIVIDUAL_ATTESTATION} can only be requested if
7910      * key generation is done in StrongBox.
7911      *
7912      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7913      *            {@code null} if the caller is not a device admin.
7914      * @param algorithm The key generation algorithm, see {@link java.security.KeyPairGenerator}.
7915      * @param keySpec Specification of the key to generate, see
7916      * {@link java.security.KeyPairGenerator}.
7917      * @param idAttestationFlags A bitmask of the identifiers that should be included in the
7918      *        attestation record ({@code ID_TYPE_BASE_INFO}, {@code ID_TYPE_SERIAL},
7919      *        {@code ID_TYPE_IMEI} and {@code ID_TYPE_MEID}), and
7920      *        {@code ID_TYPE_INDIVIDUAL_ATTESTATION} if the attestation record should be signed
7921      *        using an individual attestation certificate.
7922      *        <p>
7923      *        {@code 0} should be passed in if no device identification is required in the
7924      *        attestation record and the batch attestation certificate should be used.
7925      *        <p>
7926      *        If any flag is specified, then an attestation challenge must be included in the
7927      *        {@code keySpec}.
7928      * @return A non-null {@code AttestedKeyPair} if the key generation succeeded, null otherwise.
7929      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
7930      *         owner, or {@code admin} is null but the calling application is not a delegated
7931      *         certificate installer or credential management app. If Device ID attestation is
7932      *         requested (using {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} or
7933      *         {@link #ID_TYPE_MEID}), the caller must be the Device Owner or the Certificate
7934      *         Installer delegate.
7935      * @throws IllegalArgumentException in the following cases:
7936      *         <p>
7937      *         <ul>
7938      *         <li>The alias in {@code keySpec} is empty.</li>
7939      *         <li>The algorithm specification in {@code keySpec} is not
7940      *         {@code RSAKeyGenParameterSpec} or {@code ECGenParameterSpec}.</li>
7941      *         <li>Device ID attestation was requested but the {@code keySpec} does not contain an
7942      *         attestation challenge.</li>
7943      *         </ul>
7944      * @throws UnsupportedOperationException if Device ID attestation or individual attestation
7945      *         was requested but the underlying hardware does not support it.
7946      * @throws StrongBoxUnavailableException if the use of StrongBox for key generation was
7947      *         specified in {@code keySpec} but the device does not have one.
7948      * @see KeyGenParameterSpec.Builder#setAttestationChallenge(byte[])
7949      */
7950     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true)
generateKeyPair(@ullable ComponentName admin, @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec, @AttestationIdType int idAttestationFlags)7951     public AttestedKeyPair generateKeyPair(@Nullable ComponentName admin,
7952             @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec,
7953             @AttestationIdType int idAttestationFlags) {
7954         throwIfParentInstance("generateKeyPair");
7955         try {
7956             final ParcelableKeyGenParameterSpec parcelableSpec =
7957                     new ParcelableKeyGenParameterSpec(keySpec);
7958             KeymasterCertificateChain attestationChain = new KeymasterCertificateChain();
7959 
7960             // Translate ID attestation flags to values used by AttestationUtils
7961             final boolean success = mService.generateKeyPair(
7962                     admin, mContext.getPackageName(), algorithm, parcelableSpec,
7963                     idAttestationFlags, attestationChain);
7964             if (!success) {
7965                 Log.e(TAG, "Error generating key via DevicePolicyManagerService.");
7966                 return null;
7967             }
7968 
7969             final String alias = keySpec.getKeystoreAlias();
7970             final KeyPair keyPair = KeyChain.getKeyPair(mContext, alias);
7971             Certificate[] outputChain = null;
7972             try {
7973                 if (AttestationUtils.isChainValid(attestationChain)) {
7974                     outputChain = AttestationUtils.parseCertificateChain(attestationChain);
7975                 }
7976             } catch (KeyAttestationException e) {
7977                 Log.e(TAG, "Error parsing attestation chain for alias " + alias, e);
7978                 mService.removeKeyPair(admin, mContext.getPackageName(), alias);
7979                 return null;
7980             }
7981             return new AttestedKeyPair(keyPair, outputChain);
7982         } catch (RemoteException e) {
7983             throw e.rethrowFromSystemServer();
7984         } catch (KeyChainException e) {
7985             Log.w(TAG, "Failed to generate key", e);
7986         } catch (InterruptedException e) {
7987             Log.w(TAG, "Interrupted while generating key", e);
7988             Thread.currentThread().interrupt();
7989         } catch (ServiceSpecificException e) {
7990             Log.w(TAG, String.format("Key Generation failure: %d", e.errorCode));
7991             switch (e.errorCode) {
7992                 case KEY_GEN_STRONGBOX_UNAVAILABLE:
7993                     throw new StrongBoxUnavailableException("No StrongBox for key generation.");
7994                 default:
7995                     throw new RuntimeException(
7996                             String.format("Unknown error while generating key: %d", e.errorCode));
7997             }
7998         }
7999         return null;
8000     }
8001 
8002     /**
8003      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
8004      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to grant an application access
8005      * to an already-installed (or generated) KeyChain key.
8006      * This is useful (in combination with {@link #installKeyPair} or {@link #generateKeyPair}) to
8007      * let an application call {@link android.security.KeyChain#getPrivateKey} without having to
8008      * call {@link android.security.KeyChain#choosePrivateKeyAlias} first.
8009      *
8010      * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED}
8011      * broadcast when access to a key is granted.
8012      *
8013      * Starting from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} throws an
8014      * {@link IllegalArgumentException} if {@code alias} doesn't correspond to an existing key.
8015      *
8016      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8017      *        {@code null} if calling from a delegated certificate chooser.
8018      * @param alias The alias of the key to grant access to.
8019      * @param packageName The name of the (already installed) package to grant access to.
8020      * @return {@code true} if the grant was set successfully, {@code false} otherwise.
8021      *
8022      * @throws SecurityException if the caller is not a device owner, a profile owner or
8023      *         delegated certificate chooser.
8024      * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if
8025      *         {@code packageName} is not a name of an installed package.
8026      * @see #revokeKeyPairFromApp
8027      */
grantKeyPairToApp(@ullable ComponentName admin, @NonNull String alias, @NonNull String packageName)8028     public boolean grantKeyPairToApp(@Nullable ComponentName admin, @NonNull String alias,
8029             @NonNull String packageName) {
8030         throwIfParentInstance("grantKeyPairToApp");
8031         try {
8032             return mService.setKeyGrantForApp(
8033                     admin, mContext.getPackageName(), alias, packageName, true);
8034         } catch (RemoteException e) {
8035             e.rethrowFromSystemServer();
8036         }
8037         return false;
8038     }
8039 
8040     /**
8041      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
8042      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to query which apps have access
8043      * to a given KeyChain key.
8044      *
8045      * Key are granted on a per-UID basis, so if several apps share the same UID, granting access to
8046      * one of them automatically grants it to others. This method returns a map containing one entry
8047      * per grantee UID. Entries have UIDs as keys and sets of corresponding package names as values.
8048      * In particular, grantee packages that don't share UID with other packages are represented by
8049      * entries having singleton sets as values.
8050      *
8051      * @param alias The alias of the key to grant access to.
8052      * @return apps that have access to a given key, arranged in a map from UID to sets of
8053      *       package names.
8054      *
8055      * @throws SecurityException if the caller is not a device owner, a profile owner or
8056      *         delegated certificate chooser.
8057      * @throws IllegalArgumentException if {@code alias} doesn't correspond to an existing key.
8058      *
8059      * @see #grantKeyPairToApp(ComponentName, String, String)
8060      */
getKeyPairGrants(@onNull String alias)8061     public @NonNull Map<Integer, Set<String>> getKeyPairGrants(@NonNull String alias) {
8062         throwIfParentInstance("getKeyPairGrants");
8063         try {
8064             // The result is wrapped into intermediate parcelable representation.
8065             return mService.getKeyPairGrants(mContext.getPackageName(), alias).getPackagesByUid();
8066         } catch (RemoteException e) {
8067             e.rethrowFromSystemServer();
8068         }
8069         return null;
8070     }
8071 
8072     /**
8073      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
8074      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to revoke an application's
8075      * grant to a KeyChain key pair.
8076      * Calls by the application to {@link android.security.KeyChain#getPrivateKey}
8077      * will fail after the grant is revoked.
8078      *
8079      * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED}
8080      * broadcast when access to a key is revoked.
8081      *
8082      * Starting from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} throws an
8083      * {@link IllegalArgumentException} if {@code alias} doesn't correspond to an existing key.
8084      *
8085      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8086      *        {@code null} if calling from a delegated certificate chooser.
8087      * @param alias The alias of the key to revoke access from.
8088      * @param packageName The name of the (already installed) package to revoke access from.
8089      * @return {@code true} if the grant was revoked successfully, {@code false} otherwise.
8090      *
8091      * @throws SecurityException if the caller is not a device owner, a profile owner or
8092      *         delegated certificate chooser.
8093      * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if
8094      *         {@code packageName} is not a name of an installed package.
8095      * @see #grantKeyPairToApp
8096      */
revokeKeyPairFromApp(@ullable ComponentName admin, @NonNull String alias, @NonNull String packageName)8097     public boolean revokeKeyPairFromApp(@Nullable ComponentName admin, @NonNull String alias,
8098             @NonNull String packageName) {
8099         throwIfParentInstance("revokeKeyPairFromApp");
8100         try {
8101             return mService.setKeyGrantForApp(
8102                     admin, mContext.getPackageName(), alias, packageName, false);
8103         } catch (RemoteException e) {
8104             e.rethrowFromSystemServer();
8105         }
8106         return false;
8107     }
8108 
8109     /**
8110      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
8111      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to allow using a KeyChain key
8112      * pair for authentication to Wifi networks. The key can then be used in configurations passed
8113      * to {@link android.net.wifi.WifiManager#addNetwork}.
8114      *
8115      * Starting from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} throws an
8116      * {@link IllegalArgumentException} if {@code alias} doesn't correspond to an existing key.
8117      *
8118      * @param alias The alias of the key pair.
8119      * @return {@code true} if the operation was set successfully, {@code false} otherwise.
8120      *
8121      * @throws SecurityException if the caller is not a device owner, a profile owner or
8122      *         delegated certificate chooser.
8123      * @see #revokeKeyPairFromWifiAuth
8124      */
grantKeyPairToWifiAuth(@onNull String alias)8125     public boolean grantKeyPairToWifiAuth(@NonNull String alias) {
8126         throwIfParentInstance("grantKeyPairToWifiAuth");
8127         try {
8128             return mService.setKeyGrantToWifiAuth(mContext.getPackageName(), alias, true);
8129         } catch (RemoteException e) {
8130             e.rethrowFromSystemServer();
8131         }
8132         return false;
8133     }
8134 
8135     /**
8136      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
8137      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to deny using a KeyChain key
8138      * pair for authentication to Wifi networks. Configured networks using this key won't be able to
8139      * authenticate.
8140      *
8141      * Starting from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} throws an
8142      * {@link IllegalArgumentException} if {@code alias} doesn't correspond to an existing key.
8143      *
8144      * @param alias The alias of the key pair.
8145      * @return {@code true} if the operation was set successfully, {@code false} otherwise.
8146      *
8147      * @throws SecurityException if the caller is not a device owner, a profile owner or
8148      *         delegated certificate chooser.
8149      * @see #grantKeyPairToWifiAuth
8150      */
revokeKeyPairFromWifiAuth(@onNull String alias)8151     public boolean revokeKeyPairFromWifiAuth(@NonNull String alias) {
8152         throwIfParentInstance("revokeKeyPairFromWifiAuth");
8153         try {
8154             return mService.setKeyGrantToWifiAuth(mContext.getPackageName(), alias, false);
8155         } catch (RemoteException e) {
8156             e.rethrowFromSystemServer();
8157         }
8158         return false;
8159     }
8160 
8161     /**
8162      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
8163      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to query whether a KeyChain key
8164      * pair can be used for authentication to Wifi networks.
8165      *
8166      * @param alias The alias of the key pair.
8167      * @return {@code true} if the key pair can be used, {@code false} otherwise.
8168      *
8169      * @throws SecurityException if the caller is not a device owner, a profile owner or
8170      *         delegated certificate chooser.
8171      * @see #grantKeyPairToWifiAuth
8172      */
isKeyPairGrantedToWifiAuth(@onNull String alias)8173     public boolean isKeyPairGrantedToWifiAuth(@NonNull String alias) {
8174         throwIfParentInstance("isKeyPairGrantedToWifiAuth");
8175         try {
8176             return mService.isKeyPairGrantedToWifiAuth(mContext.getPackageName(), alias);
8177         } catch (RemoteException e) {
8178             e.rethrowFromSystemServer();
8179         }
8180         return false;
8181     }
8182 
8183     /**
8184      * Returns {@code true} if the device supports attestation of device identifiers in addition
8185      * to key attestation. See
8186      * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}
8187      * @return {@code true} if Device ID attestation is supported.
8188      */
isDeviceIdAttestationSupported()8189     public boolean isDeviceIdAttestationSupported() {
8190         PackageManager pm = mContext.getPackageManager();
8191         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ID_ATTESTATION);
8192     }
8193 
8194     /**
8195      * Returns {@code true} if the StrongBox Keymaster implementation on the device was provisioned
8196      * with an individual attestation certificate and can sign attestation records using it (as
8197      * attestation using an individual attestation certificate is a feature only Keymaster
8198      * implementations with StrongBox security level can implement).
8199      * For use prior to calling
8200      * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}.
8201      * @return {@code true} if individual attestation is supported.
8202      */
isUniqueDeviceAttestationSupported()8203     public boolean isUniqueDeviceAttestationSupported() {
8204         PackageManager pm = mContext.getPackageManager();
8205         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_UNIQUE_ATTESTATION);
8206     }
8207 
8208     /**
8209      * This API can be called by the following to associate certificates with a key pair that was
8210      * generated using {@link #generateKeyPair}, and set whether the key is available for the user
8211      * to choose in the certificate selection prompt:
8212      * <ul>
8213      *    <li>Device owner</li>
8214      *    <li>Profile owner</li>
8215      *    <li>Delegated certificate installer</li>
8216      *    <li>Credential management app</li>
8217      * </ul>
8218      *
8219      * <p>From Android {@link android.os.Build.VERSION_CODES#S}, the credential management app
8220      * can call this API. If called by the credential management app, the componentName must be
8221      * {@code null}. Note, there can only be a credential management app on an unmanaged device.
8222      *
8223      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8224      *            {@code null} if the caller is not a device admin.
8225      * @param alias The private key alias under which to install the certificate. The {@code alias}
8226      *        should denote an existing private key. If a certificate with that alias already
8227      *        exists, it will be overwritten.
8228      * @param certs The certificate chain to install. The chain should start with the leaf
8229      *        certificate and include the chain of trust in order. This will be returned by
8230      *        {@link android.security.KeyChain#getCertificateChain}.
8231      * @param isUserSelectable {@code true} to indicate that a user can select this key via the
8232      *        certificate selection prompt, {@code false} to indicate that this key can only be
8233      *        granted access by implementing
8234      *        {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
8235      * @return {@code true} if the provided {@code alias} exists and the certificates has been
8236      *        successfully associated with it, {@code false} otherwise.
8237      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
8238      *         owner, or {@code admin} is null but the calling application is not a delegated
8239      *         certificate installer or credential management app.
8240      */
8241     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true)
setKeyPairCertificate(@ullable ComponentName admin, @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable)8242     public boolean setKeyPairCertificate(@Nullable ComponentName admin,
8243             @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable) {
8244         throwIfParentInstance("setKeyPairCertificate");
8245         try {
8246             final byte[] pemCert = Credentials.convertToPem(certs.get(0));
8247             byte[] pemChain = null;
8248             if (certs.size() > 1) {
8249                 pemChain = Credentials.convertToPem(
8250                         certs.subList(1, certs.size()).toArray(new Certificate[0]));
8251             }
8252             return mService.setKeyPairCertificate(admin, mContext.getPackageName(), alias, pemCert,
8253                     pemChain, isUserSelectable);
8254         } catch (RemoteException e) {
8255             throw e.rethrowFromSystemServer();
8256         } catch (CertificateException | IOException e) {
8257             Log.w(TAG, "Could not pem-encode certificate", e);
8258         }
8259         return false;
8260     }
8261 
8262     /**
8263      * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
8264      * doesn't exist.
8265      */
getCaCertAlias(byte[] certBuffer)8266     private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
8267         final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
8268         final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
8269                               new ByteArrayInputStream(certBuffer));
8270         return new TrustedCertificateStore().getCertificateAlias(cert);
8271     }
8272 
8273     /**
8274      * Called by a profile owner or device owner to grant access to privileged certificate
8275      * manipulation APIs to a third-party certificate installer app. Granted APIs include
8276      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
8277      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
8278      * <p>
8279      * Delegated certificate installer is a per-user state. The delegated access is persistent until
8280      * it is later cleared by calling this method with a null value or uninstallling the certificate
8281      * installer.
8282      * <p>
8283      * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
8284      * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
8285      * supplied certificate installer package must be installed when calling this API, otherwise an
8286      * {@link IllegalArgumentException} will be thrown.
8287      *
8288      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8289      * @param installerPackage The package name of the certificate installer which will be given
8290      *            access. If {@code null} is given the current package will be cleared.
8291      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8292      *
8293      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
8294      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
8295      */
8296     @Deprecated
setCertInstallerPackage(@onNull ComponentName admin, @Nullable String installerPackage)8297     public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
8298             installerPackage) throws SecurityException {
8299         throwIfParentInstance("setCertInstallerPackage");
8300         if (mService != null) {
8301             try {
8302                 mService.setCertInstallerPackage(admin, installerPackage);
8303             } catch (RemoteException e) {
8304                 throw e.rethrowFromSystemServer();
8305             }
8306         }
8307     }
8308 
8309     /**
8310      * Called by a profile owner or device owner to retrieve the certificate installer for the user,
8311      * or {@code null} if none is set. If there are multiple delegates this function will return one
8312      * of them.
8313      *
8314      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8315      * @return The package name of the current delegated certificate installer, or {@code null} if
8316      *         none is set.
8317      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8318      *
8319      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
8320      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
8321      */
8322     @Deprecated
getCertInstallerPackage(@onNull ComponentName admin)8323     public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
8324             throws SecurityException {
8325         throwIfParentInstance("getCertInstallerPackage");
8326         if (mService != null) {
8327             try {
8328                 return mService.getCertInstallerPackage(admin);
8329             } catch (RemoteException e) {
8330                 throw e.rethrowFromSystemServer();
8331             }
8332         }
8333         return null;
8334     }
8335 
8336     /**
8337      * Called by a profile owner or device owner to grant access to privileged APIs to another app.
8338      * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*}
8339      * constants.
8340      * <p>
8341      * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be
8342      * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra
8343      * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the
8344      * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag.
8345      * <p>
8346      * Delegated scopes are a per-user state. The delegated access is persistent until it is later
8347      * cleared by calling this method with an empty {@code scopes} list or uninstalling the
8348      * {@code delegatePackage}.
8349      *
8350      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8351      * @param delegatePackage The package name of the app which will be given access.
8352      * @param scopes The groups of privileged APIs whose access should be granted to
8353      *            {@code delegatedPackage}.
8354      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8355      */
setDelegatedScopes(@onNull ComponentName admin, @NonNull String delegatePackage, @NonNull List<String> scopes)8356      public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage,
8357             @NonNull List<String> scopes) {
8358         throwIfParentInstance("setDelegatedScopes");
8359         if (mService != null) {
8360             try {
8361                 mService.setDelegatedScopes(admin, delegatePackage, scopes);
8362             } catch (RemoteException e) {
8363                 throw e.rethrowFromSystemServer();
8364             }
8365         }
8366     }
8367 
8368     /**
8369      * Called by a profile owner or device owner to retrieve a list of the scopes given to a
8370      * delegate package. Other apps can use this method to retrieve their own delegated scopes by
8371      * passing {@code null} for {@code admin} and their own package name as
8372      * {@code delegatedPackage}.
8373      *
8374      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8375      *            {@code null} if the caller is {@code delegatedPackage}.
8376      * @param delegatedPackage The package name of the app whose scopes should be retrieved.
8377      * @return A list containing the scopes given to {@code delegatedPackage}.
8378      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8379      */
8380      @NonNull
getDelegatedScopes(@ullable ComponentName admin, @NonNull String delegatedPackage)8381      public List<String> getDelegatedScopes(@Nullable ComponentName admin,
8382              @NonNull String delegatedPackage) {
8383          throwIfParentInstance("getDelegatedScopes");
8384          if (mService != null) {
8385              try {
8386                  return mService.getDelegatedScopes(admin, delegatedPackage);
8387              } catch (RemoteException e) {
8388                  throw e.rethrowFromSystemServer();
8389              }
8390          }
8391          return null;
8392     }
8393 
8394     /**
8395      * Called by a profile owner or device owner to retrieve a list of delegate packages that were
8396      * granted a delegation scope.
8397      *
8398      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8399      * @param delegationScope The scope whose delegates should be retrieved.
8400      * @return A list of package names of the current delegated packages for
8401                {@code delegationScope}.
8402      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8403      */
8404      @Nullable
getDelegatePackages(@onNull ComponentName admin, @NonNull String delegationScope)8405      public List<String> getDelegatePackages(@NonNull ComponentName admin,
8406              @NonNull String delegationScope) {
8407         throwIfParentInstance("getDelegatePackages");
8408         if (mService != null) {
8409             try {
8410                 return mService.getDelegatePackages(admin, delegationScope);
8411             } catch (RemoteException e) {
8412                 throw e.rethrowFromSystemServer();
8413             }
8414         }
8415         return null;
8416     }
8417 
8418     /**
8419      * Service-specific error code used in implementation of {@code setAlwaysOnVpnPackage} methods.
8420      * @hide
8421      */
8422     public static final int ERROR_VPN_PACKAGE_NOT_FOUND = 1;
8423 
8424     /**
8425      * Called by a device or profile owner to configure an always-on VPN connection through a
8426      * specific application for the current user. This connection is automatically granted and
8427      * persisted after a reboot.
8428      * <p> To support the always-on feature, an app must
8429      * <ul>
8430      *     <li>declare a {@link android.net.VpnService} in its manifest, guarded by
8431      *         {@link android.Manifest.permission#BIND_VPN_SERVICE};</li>
8432      *     <li>target {@link android.os.Build.VERSION_CODES#N API 24} or above; and</li>
8433      *     <li><i>not</i> explicitly opt out of the feature through
8434      *         {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}.</li>
8435      * </ul>
8436      * The call will fail if called with the package name of an unsupported VPN app.
8437      * <p> Enabling lockdown via {@code lockdownEnabled} argument carries the risk that any failure
8438      * of the VPN provider could break networking for all apps. This method clears any lockdown
8439      * allowlist set by {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)}.
8440      * <p> Starting from {@link android.os.Build.VERSION_CODES#S API 31} calling this method with
8441      * {@code vpnPackage} set to {@code null} only removes the existing configuration if it was
8442      * previously created by this admin. To remove VPN configuration created by the user use
8443      * {@link UserManager#DISALLOW_CONFIG_VPN}.
8444      *
8445      * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
8446      *        remove an existing always-on VPN configuration.
8447      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
8448      *        {@code false} otherwise. This has no effect when clearing.
8449      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8450      * @throws NameNotFoundException if {@code vpnPackage} is not installed.
8451      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
8452      *         set as always-on, or if always-on VPN is not available.
8453      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
8454      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled)8455     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
8456             boolean lockdownEnabled) throws NameNotFoundException {
8457         setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled, Collections.emptySet());
8458     }
8459 
8460     /**
8461      * A version of {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} that allows the
8462      * admin to specify a set of apps that should be able to access the network directly when VPN
8463      * is not connected. When VPN connects these apps switch over to VPN if allowed to use that VPN.
8464      * System apps can always bypass VPN.
8465      * <p> Note that the system doesn't update the allowlist when packages are installed or
8466      * uninstalled, the admin app must call this method to keep the list up to date.
8467      * <p> When {@code lockdownEnabled} is false {@code lockdownAllowlist} is ignored . When
8468      * {@code lockdownEnabled} is {@code true} and {@code lockdownAllowlist} is {@code null} or
8469      * empty, only system apps can bypass VPN.
8470      * <p> Setting always-on VPN package to {@code null} or using
8471      * {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} clears lockdown allowlist.
8472      *
8473      * @param vpnPackage package name for an installed VPN app on the device, or {@code null}
8474      *         to remove an existing always-on VPN configuration
8475      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
8476      *         {@code false} otherwise. This has no effect when clearing.
8477      * @param lockdownAllowlist Packages that will be able to access the network directly when VPN
8478      *         is in lockdown mode but not connected. Has no effect when clearing.
8479      * @throws SecurityException if {@code admin} is not a device or a profile
8480      *         owner.
8481      * @throws NameNotFoundException if {@code vpnPackage} or one of
8482      *         {@code lockdownAllowlist} is not installed.
8483      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does
8484      *         not support being set as always-on, or if always-on VPN is not
8485      *         available.
8486      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled, @Nullable Set<String> lockdownAllowlist)8487     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
8488             boolean lockdownEnabled, @Nullable Set<String> lockdownAllowlist)
8489             throws NameNotFoundException {
8490         throwIfParentInstance("setAlwaysOnVpnPackage");
8491         if (mService != null) {
8492             try {
8493                 mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled,
8494                         lockdownAllowlist == null ? null : new ArrayList<>(lockdownAllowlist));
8495             } catch (ServiceSpecificException e) {
8496                 switch (e.errorCode) {
8497                     case ERROR_VPN_PACKAGE_NOT_FOUND:
8498                         throw new NameNotFoundException(e.getMessage());
8499                     default:
8500                         throw new RuntimeException(
8501                                 "Unknown error setting always-on VPN: " + e.errorCode, e);
8502                 }
8503             } catch (RemoteException e) {
8504                 throw e.rethrowFromSystemServer();
8505             }
8506         }
8507     }
8508 
8509     /**
8510      * Called by device or profile owner to query whether current always-on VPN is configured in
8511      * lockdown mode. Returns {@code false} when no always-on configuration is set.
8512      *
8513      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8514      *
8515      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8516      *
8517      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean)
8518      */
isAlwaysOnVpnLockdownEnabled(@onNull ComponentName admin)8519     public boolean isAlwaysOnVpnLockdownEnabled(@NonNull ComponentName admin) {
8520         throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
8521         if (mService != null) {
8522             try {
8523                 // Starting from Android R, the caller can pass the permission check in
8524                 // DevicePolicyManagerService if it holds android.permission.MAINLINE_NETWORK_STACK.
8525                 // Note that the android.permission.MAINLINE_NETWORK_STACK is a signature permission
8526                 // which is used by the NetworkStack mainline module.
8527                 return mService.isAlwaysOnVpnLockdownEnabled(admin);
8528             } catch (RemoteException e) {
8529                 throw e.rethrowFromSystemServer();
8530             }
8531         }
8532         return false;
8533     }
8534 
8535     /**
8536      * Returns whether the admin has enabled always-on VPN lockdown for the current user.
8537      *
8538      * Only callable by the system.
8539     * @hide
8540     */
8541     @UserHandleAware
isAlwaysOnVpnLockdownEnabled()8542     public boolean isAlwaysOnVpnLockdownEnabled() {
8543         throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
8544         if (mService != null) {
8545             try {
8546                 return mService.isAlwaysOnVpnLockdownEnabledForUser(myUserId());
8547             } catch (RemoteException e) {
8548                 throw e.rethrowFromSystemServer();
8549             }
8550         }
8551         return false;
8552     }
8553 
8554     /**
8555      * Called by device or profile owner to query the set of packages that are allowed to access
8556      * the network directly when always-on VPN is in lockdown mode but not connected. Returns
8557      * {@code null} when always-on VPN is not active or not in lockdown mode.
8558      *
8559      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8560      *
8561      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8562      *
8563      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
8564      */
getAlwaysOnVpnLockdownWhitelist(@onNull ComponentName admin)8565     public @Nullable Set<String> getAlwaysOnVpnLockdownWhitelist(@NonNull ComponentName admin) {
8566         throwIfParentInstance("getAlwaysOnVpnLockdownWhitelist");
8567         if (mService != null) {
8568             try {
8569                 final List<String> allowlist =
8570                         mService.getAlwaysOnVpnLockdownAllowlist(admin);
8571                 return allowlist == null ? null : new HashSet<>(allowlist);
8572             } catch (RemoteException e) {
8573                 throw e.rethrowFromSystemServer();
8574             }
8575         }
8576         return null;
8577     }
8578 
8579     /**
8580      * Called by a device or profile owner to read the name of the package administering an
8581      * always-on VPN connection for the current user. If there is no such package, or the always-on
8582      * VPN is provided by the system instead of by an application, {@code null} will be returned.
8583      *
8584      * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
8585      *         is set.
8586      * @throws SecurityException if {@code admin} is not a device or a profile owner.
8587      */
getAlwaysOnVpnPackage(@onNull ComponentName admin)8588     public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
8589         throwIfParentInstance("getAlwaysOnVpnPackage");
8590         if (mService != null) {
8591             try {
8592                 return mService.getAlwaysOnVpnPackage(admin);
8593             } catch (RemoteException e) {
8594                 throw e.rethrowFromSystemServer();
8595             }
8596         }
8597         return null;
8598     }
8599 
8600     /**
8601      * Returns the VPN package name if the admin has enabled always-on VPN on the current user,
8602      * or {@code null} if none is set.
8603      *
8604      * Only callable by the system.
8605      * @hide
8606      */
8607     @UserHandleAware
getAlwaysOnVpnPackage()8608     public @Nullable String getAlwaysOnVpnPackage() {
8609         throwIfParentInstance("getAlwaysOnVpnPackage");
8610         if (mService != null) {
8611             try {
8612                 return mService.getAlwaysOnVpnPackageForUser(myUserId());
8613             } catch (RemoteException e) {
8614                 throw e.rethrowFromSystemServer();
8615             }
8616         }
8617         return null;
8618     }
8619 
8620     /**
8621      * Called by an application that is administering the device to disable all cameras on the
8622      * device, for this user. After setting this, no applications running as this user will be able
8623      * to access any cameras on the device.
8624      * <p>
8625      * This method can be called on the {@link DevicePolicyManager} instance,
8626      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
8627      * the profile owner of an organization-owned managed profile.
8628      * <p>
8629      * If the caller is device owner, then the restriction will be applied to all users. If
8630      * called on the parent instance, then the restriction will be applied on the personal profile.
8631      * <p>
8632      * The calling device admin must have requested
8633      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
8634      * not, a security exception will be thrown.
8635      * <p>
8636      * <b>Note</b>, this policy type is deprecated for legacy device admins since
8637      * {@link android.os.Build.VERSION_CODES#Q}. On Android
8638      * {@link android.os.Build.VERSION_CODES#Q} devices, legacy device admins targeting SDK
8639      * version {@link android.os.Build.VERSION_CODES#P} or below can still call this API to
8640      * disable camera, while legacy device admins targeting SDK version
8641      * {@link android.os.Build.VERSION_CODES#Q} will receive a SecurityException. Starting
8642      * from Android {@link android.os.Build.VERSION_CODES#R}, requests to disable camera from
8643      * legacy device admins targeting SDK version {@link android.os.Build.VERSION_CODES#P} or
8644      * below will be silently ignored.
8645      * <p>
8646      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the camera disabled
8647      * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
8648      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
8649      * successfully set or not. This callback will contain:
8650      * <ul>
8651      * <li> The policy identifier: userRestriction_no_camera
8652      * <li> The {@link TargetUser} that this policy relates to
8653      * <li> The {@link PolicyUpdateResult}, which will be
8654      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
8655      * reason the policy failed to be set
8656      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
8657      * </ul>
8658      * If there has been a change to the policy,
8659      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
8660      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
8661      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
8662      * will contain the reason why the policy changed.
8663      *
8664      * @param admin Which {@link DeviceAdminReceiver} this request is associated with or null if
8665                      the caller is not a device admin
8666      * @param disabled Whether or not the camera should be disabled.
8667      * @throws SecurityException if {@code admin} is not an active administrator or does not use
8668      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
8669      */
8670     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CAMERA, conditional = true)
setCameraDisabled(@ullable ComponentName admin, boolean disabled)8671     public void setCameraDisabled(@Nullable ComponentName admin, boolean disabled) {
8672         if (mService != null) {
8673             try {
8674                 mService.setCameraDisabled(admin, mContext.getPackageName(), disabled,
8675                         mParentInstance);
8676             } catch (RemoteException e) {
8677                 throw e.rethrowFromSystemServer();
8678             }
8679         }
8680     }
8681 
8682     /**
8683      * Determine whether or not the device's cameras have been disabled for this user,
8684      * either by the calling admin, if specified, or all admins.
8685      * <p>
8686      * This method can be called on the {@link DevicePolicyManager} instance,
8687      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
8688      * the profile owner of an organization-owned managed profile.
8689      *
8690      * @param admin The name of the admin component to check, or {@code null} to check whether any
8691      *              admins have disabled the camera
8692      */
8693     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CAMERA, conditional = true)
getCameraDisabled(@ullable ComponentName admin)8694     public boolean getCameraDisabled(@Nullable ComponentName admin) {
8695         return getCameraDisabled(admin, myUserId());
8696     }
8697 
8698     /** @hide per-user version */
8699     @UnsupportedAppUsage
getCameraDisabled(@ullable ComponentName admin, int userHandle)8700     public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
8701         if (mService != null) {
8702             try {
8703                 return mService.getCameraDisabled(admin, mContext.getPackageName(), userHandle,
8704                         mParentInstance);
8705             } catch (RemoteException e) {
8706                 throw e.rethrowFromSystemServer();
8707             }
8708         }
8709         return false;
8710     }
8711 
8712     /**
8713      * Called by a device owner to request a bugreport.
8714      * <p>
8715      * If the device contains secondary users or profiles, they must be affiliated with the device.
8716      * Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
8717      *
8718      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8719      * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
8720      *         wasn't triggered because a previous bugreport operation is still active (either the
8721      *         bugreport is still running or waiting for the user to share or decline)
8722      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
8723      *         profile or secondary user that is not affiliated with the device.
8724      * @see #isAffiliatedUser
8725      */
requestBugreport(@onNull ComponentName admin)8726     public boolean requestBugreport(@NonNull ComponentName admin) {
8727         throwIfParentInstance("requestBugreport");
8728         if (mService != null) {
8729             try {
8730                 return mService.requestBugreport(admin);
8731             } catch (RemoteException e) {
8732                 throw e.rethrowFromSystemServer();
8733             }
8734         }
8735         return false;
8736     }
8737 
8738     /**
8739      * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
8740      * screen capture also prevents the content from being shown on display devices that do not have
8741      * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
8742      * secure surfaces and secure displays.
8743      * <p>
8744      * This method can be called on the {@link DevicePolicyManager} instance, returned by
8745      * {@link #getParentProfileInstance(ComponentName)}, where the calling device admin must be
8746      * the profile owner of an organization-owned managed profile. If it is not, a security
8747      * exception will be thrown.
8748      * <p>
8749      * If the caller is device owner or called on the parent instance by a profile owner of an
8750      * organization-owned managed profile, then the restriction will be applied to all users.
8751      * <p>
8752      * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
8753      * assist requests for all activities of the relevant user.
8754      *
8755      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
8756      *              caller is not a device admin.
8757      * @param disabled Whether screen capture is disabled or not.
8758      * @throws SecurityException if the caller is not permitted to control screen capture policy.
8759      */
8760     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SCREEN_CAPTURE, conditional = true)
setScreenCaptureDisabled(@ullable ComponentName admin, boolean disabled)8761     public void setScreenCaptureDisabled(@Nullable ComponentName admin, boolean disabled) {
8762         if (mService != null) {
8763             try {
8764                 mService.setScreenCaptureDisabled(
8765                         admin, mContext.getPackageName(), disabled, mParentInstance);
8766             } catch (RemoteException e) {
8767                 throw e.rethrowFromSystemServer();
8768             }
8769         }
8770     }
8771 
8772     /**
8773      * Determine whether or not screen capture has been disabled by the calling
8774      * admin, if specified, or all admins.
8775      * <p>
8776      * This method can be called on the {@link DevicePolicyManager} instance,
8777      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
8778      * the profile owner of an organization-owned managed profile (the calling admin must be
8779      * specified).
8780      *
8781      * @param admin The name of the admin component to check, or {@code null} to check whether any
8782      *              admins have disabled screen capture.
8783      */
getScreenCaptureDisabled(@ullable ComponentName admin)8784     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
8785         return getScreenCaptureDisabled(admin, myUserId());
8786     }
8787 
8788     /** @hide per-user version */
getScreenCaptureDisabled(@ullable ComponentName admin, int userHandle)8789     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
8790         if (mService != null) {
8791             try {
8792                 return mService.getScreenCaptureDisabled(admin, userHandle, mParentInstance);
8793             } catch (RemoteException e) {
8794                 throw e.rethrowFromSystemServer();
8795             }
8796         }
8797         return false;
8798     }
8799 
8800     /**
8801      * Called by a device/profile owner to set nearby notification streaming policy. Notification
8802      * streaming is sending notification data from pre-installed apps to nearby devices.
8803      *
8804      * @param policy One of the {@code NearbyStreamingPolicy} constants.
8805      * @throws SecurityException if caller is not a device or profile owner
8806      */
setNearbyNotificationStreamingPolicy(@earbyStreamingPolicy int policy)8807     public void setNearbyNotificationStreamingPolicy(@NearbyStreamingPolicy int policy) {
8808         throwIfParentInstance("setNearbyNotificationStreamingPolicy");
8809         if (mService == null) {
8810             return;
8811         }
8812         try {
8813             mService.setNearbyNotificationStreamingPolicy(policy);
8814         } catch (RemoteException e) {
8815             throw e.rethrowFromSystemServer();
8816         }
8817     }
8818 
8819     /**
8820      * Returns the current runtime nearby notification streaming policy set by the device or profile
8821      * owner.
8822      * <p>
8823      * The caller must be the target user's device owner/profile owner or hold the
8824      * {@link android.Manifest.permission#READ_NEARBY_STREAMING_POLICY READ_NEARBY_STREAMING_POLICY}
8825      * permission.
8826      */
8827     @RequiresPermission(
8828             value = android.Manifest.permission.READ_NEARBY_STREAMING_POLICY,
8829             conditional = true)
getNearbyNotificationStreamingPolicy()8830     public @NearbyStreamingPolicy int getNearbyNotificationStreamingPolicy() {
8831         return getNearbyNotificationStreamingPolicy(myUserId());
8832     }
8833 
8834     /** @hide per-user version */
getNearbyNotificationStreamingPolicy(int userId)8835     public @NearbyStreamingPolicy int getNearbyNotificationStreamingPolicy(int userId) {
8836         throwIfParentInstance("getNearbyNotificationStreamingPolicy");
8837         if (mService == null) {
8838             return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
8839         }
8840         try {
8841             return mService.getNearbyNotificationStreamingPolicy(userId);
8842         } catch (RemoteException re) {
8843             throw re.rethrowFromSystemServer();
8844         }
8845     }
8846 
8847     /**
8848      * Called by a device/profile owner to set nearby app streaming policy. App streaming is when
8849      * the device starts an app on a virtual display and sends a video stream of the app to nearby
8850      * devices.
8851      *
8852      * @param policy One of the {@code NearbyStreamingPolicy} constants.
8853      * @throws SecurityException if caller is not a device or profile owner.
8854      */
setNearbyAppStreamingPolicy(@earbyStreamingPolicy int policy)8855     public void setNearbyAppStreamingPolicy(@NearbyStreamingPolicy int policy) {
8856         throwIfParentInstance("setNearbyAppStreamingPolicy");
8857         if (mService == null) {
8858             return;
8859         }
8860         try {
8861             mService.setNearbyAppStreamingPolicy(policy);
8862         } catch (RemoteException e) {
8863             throw e.rethrowFromSystemServer();
8864         }
8865     }
8866 
8867     /**
8868      * Returns the current runtime nearby app streaming policy set by the device or profile owner.
8869      * <p>
8870      * The caller must be the target user's device owner/profile owner or hold the
8871      * {@link android.Manifest.permission#READ_NEARBY_STREAMING_POLICY READ_NEARBY_STREAMING_POLICY}
8872      * permission.
8873      */
8874     @RequiresPermission(
8875             value = android.Manifest.permission.READ_NEARBY_STREAMING_POLICY,
8876             conditional = true)
getNearbyAppStreamingPolicy()8877     public @NearbyStreamingPolicy int getNearbyAppStreamingPolicy() {
8878         return getNearbyAppStreamingPolicy(myUserId());
8879     }
8880 
8881     /** @hide per-user version */
getNearbyAppStreamingPolicy(int userId)8882     public @NearbyStreamingPolicy int getNearbyAppStreamingPolicy(int userId) {
8883         throwIfParentInstance("getNearbyAppStreamingPolicy");
8884         if (mService == null) {
8885             return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
8886         }
8887         try {
8888             return mService.getNearbyAppStreamingPolicy(userId);
8889         } catch (RemoteException re) {
8890             throw re.rethrowFromSystemServer();
8891         }
8892     }
8893 
8894     /**
8895      * Called by a device owner, or alternatively a profile owner from Android 8.0 (API level 26) or
8896      * higher, to set whether auto time is required. If auto time is required, no user will be able
8897      * set the date and time and network date and time will be used.
8898      * <p>
8899      * Note: If auto time is required the user can still manually set the time zone. Staring from
8900      * Android 11, if auto time is required, the user cannot manually set the time zone.
8901      * <p>
8902      * The calling device admin must be a device owner, or alternatively a profile owner from
8903      * Android 8.0 (API level 26) or higher. If it is not, a security exception will be thrown.
8904      * <p>
8905      * Staring from Android 11, this API switches to use
8906      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} to enforce the auto time settings. Calling
8907      * this API to enforce auto time will result in
8908      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being set, while calling this API to lift
8909      * the requirement will result in {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being cleared.
8910      * From Android 11, this API can also no longer be called on a managed profile.
8911      *
8912      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8913      * @param required Whether auto time is set required or not.
8914      * @throws SecurityException if {@code admin} is not a device owner, not a profile owner or
8915      * if this API is called on a managed profile.
8916      * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #setAutoTimeEnabled}
8917      * to turn auto time on or off and use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
8918      * to prevent the user from changing this setting.
8919      */
8920     @Deprecated
setAutoTimeRequired(@onNull ComponentName admin, boolean required)8921     public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
8922         throwIfParentInstance("setAutoTimeRequired");
8923         if (mService != null) {
8924             try {
8925                 mService.setAutoTimeRequired(admin, required);
8926             } catch (RemoteException e) {
8927                 throw e.rethrowFromSystemServer();
8928             }
8929         }
8930     }
8931 
8932     /**
8933      * @return true if auto time is required.
8934      * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #getAutoTimeEnabled}
8935      */
8936     @Deprecated
getAutoTimeRequired()8937     public boolean getAutoTimeRequired() {
8938         throwIfParentInstance("getAutoTimeRequired");
8939         if (mService != null) {
8940             try {
8941                 return mService.getAutoTimeRequired();
8942             } catch (RemoteException e) {
8943                 throw e.rethrowFromSystemServer();
8944             }
8945         }
8946         return false;
8947     }
8948 
8949     /**
8950      * Called by a device owner, a profile owner for the primary user or a profile
8951      * owner of an organization-owned managed profile to turn auto time on and off.
8952      * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
8953      * to prevent the user from changing this setting.
8954      * <p>
8955      * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
8956      * no user will be able set the date and time. Instead, the network date
8957      * and time will be used.
8958      *
8959      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
8960      *              caller is not a device admin.
8961      * @param enabled Whether time should be obtained automatically from the network or not.
8962      * @throws SecurityException if caller is not a device owner, a profile owner for the
8963      * primary user, or a profile owner of an organization-owned managed profile.
8964      */
8965     @RequiresPermission(value = SET_TIME, conditional = true)
setAutoTimeEnabled(@ullable ComponentName admin, boolean enabled)8966     public void setAutoTimeEnabled(@Nullable ComponentName admin, boolean enabled) {
8967         throwIfParentInstance("setAutoTimeEnabled");
8968         if (mService != null) {
8969             try {
8970                 mService.setAutoTimeEnabled(admin, mContext.getPackageName(), enabled);
8971             } catch (RemoteException e) {
8972                 throw e.rethrowFromSystemServer();
8973             }
8974         }
8975     }
8976 
8977     /**
8978      * Returns true if auto time is enabled on the device.
8979      *
8980      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
8981      *              caller is not a device admin.
8982      * @return true if auto time is enabled on the device.
8983      * @throws SecurityException if caller is not a device owner, a profile owner for the
8984      * primary user, or a profile owner of an organization-owned managed profile.
8985      */
8986     @RequiresPermission(anyOf = {SET_TIME, QUERY_ADMIN_POLICY}, conditional = true)
getAutoTimeEnabled(@ullable ComponentName admin)8987     public boolean getAutoTimeEnabled(@Nullable ComponentName admin) {
8988         throwIfParentInstance("getAutoTimeEnabled");
8989         if (mService != null) {
8990             try {
8991                 return mService.getAutoTimeEnabled(admin, mContext.getPackageName());
8992             } catch (RemoteException e) {
8993                 throw e.rethrowFromSystemServer();
8994             }
8995         }
8996         return false;
8997     }
8998 
8999     /**
9000      * Called by a device owner, a profile owner for the primary user or a profile
9001      * owner of an organization-owned managed profile to turn auto time zone on and off.
9002      * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
9003      * to prevent the user from changing this setting.
9004      * <p>
9005      * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
9006      * no user will be able set the date and time zone. Instead, the network date
9007      * and time zone will be used.
9008      *
9009      * @param admin Which {@link DeviceAdminReceiver} this request is associated with or Null if the
9010      *              caller is not a device admin.
9011      * @param enabled Whether time zone should be obtained automatically from the network or not.
9012      * @throws SecurityException if caller is not a device owner, a profile owner for the
9013      * primary user, or a profile owner of an organization-owned managed profile.
9014      */
9015     @SupportsCoexistence
9016     @RequiresPermission(value = SET_TIME_ZONE, conditional = true)
setAutoTimeZoneEnabled(@ullable ComponentName admin, boolean enabled)9017     public void setAutoTimeZoneEnabled(@Nullable ComponentName admin, boolean enabled) {
9018         throwIfParentInstance("setAutoTimeZone");
9019         if (mService != null) {
9020             try {
9021                 mService.setAutoTimeZoneEnabled(admin, mContext.getPackageName(), enabled);
9022             } catch (RemoteException e) {
9023                 throw e.rethrowFromSystemServer();
9024             }
9025         }
9026     }
9027 
9028     /**
9029      * Returns true if auto time zone is enabled on the device.
9030      *
9031      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
9032      *              caller is not a device admin.
9033      * @return true if auto time zone is enabled on the device.
9034      * @throws SecurityException if caller is not a device owner, a profile owner for the
9035      * primary user, or a profile owner of an organization-owned managed profile.
9036      */
9037     @RequiresPermission(anyOf = {SET_TIME_ZONE, QUERY_ADMIN_POLICY}, conditional = true)
getAutoTimeZoneEnabled(@ullable ComponentName admin)9038     public boolean getAutoTimeZoneEnabled(@Nullable ComponentName admin) {
9039         throwIfParentInstance("getAutoTimeZone");
9040         if (mService != null) {
9041             try {
9042                 return mService.getAutoTimeZoneEnabled(admin, mContext.getPackageName());
9043             } catch (RemoteException e) {
9044                 throw e.rethrowFromSystemServer();
9045             }
9046         }
9047         return false;
9048     }
9049 
9050     /**
9051      * TODO (b/137101239): remove this method in follow-up CL
9052      * since it's only used for split system user.
9053      * Called by a device owner to set whether all users created on the device should be ephemeral.
9054      * @hide
9055      */
setForceEphemeralUsers( @onNull ComponentName admin, boolean forceEphemeralUsers)9056     public void setForceEphemeralUsers(
9057             @NonNull ComponentName admin, boolean forceEphemeralUsers) {
9058         throwIfParentInstance("setForceEphemeralUsers");
9059         if (mService != null) {
9060             try {
9061                 mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
9062             } catch (RemoteException e) {
9063                 throw e.rethrowFromSystemServer();
9064             }
9065         }
9066     }
9067 
9068     /**
9069      * TODO (b/137101239): remove this method in follow-up CL
9070      * since it's only used for split system user.
9071      * @return true if all users are created ephemeral.
9072      * @throws SecurityException if {@code admin} is not a device owner.
9073      * @hide
9074      */
getForceEphemeralUsers(@onNull ComponentName admin)9075     public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
9076         throwIfParentInstance("getForceEphemeralUsers");
9077         if (mService != null) {
9078             try {
9079                 return mService.getForceEphemeralUsers(admin);
9080             } catch (RemoteException e) {
9081                 throw e.rethrowFromSystemServer();
9082             }
9083         }
9084         return false;
9085     }
9086 
9087     /**
9088      * Called by an application that is administering the device to disable keyguard customizations,
9089      * such as widgets. After setting this, keyguard features will be disabled according to the
9090      * provided feature list.
9091      * <p>
9092      * A calling device admin must have requested
9093      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
9094      * if it has not, a security exception will be thrown.
9095      * <p>
9096      * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
9097      * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
9098      * profile owner of a managed profile can set:
9099      * <ul>
9100      * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
9101      * is no separate challenge set on the managed profile.
9102      * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FACE} or
9103      * {@link #KEYGUARD_DISABLE_IRIS} which affects the managed profile challenge if
9104      * there is one, or the parent user otherwise.
9105      * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
9106      * by applications in the managed profile.
9107      * </ul>
9108      * <p>
9109      * From version {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}, the profile owner of a
9110      * managed profile can also set {@link #KEYGUARD_DISABLE_WIDGETS_ALL} which disables keyguard
9111      * widgets for the managed profile.
9112      * <p>
9113      * From version {@link android.os.Build.VERSION_CODES#R} the profile owner of an
9114      * organization-owned managed profile can set:
9115      * <ul>
9116      * <li>{@link #KEYGUARD_DISABLE_SECURE_CAMERA} which affects the parent user when called on the
9117      * parent profile.
9118      * <li>{@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS} which affects the parent user when called
9119      * on the parent profile.
9120      * </ul>
9121      * Starting from version {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM} the profile
9122      * owner of an organization-owned managed profile can set:
9123      * <ul>
9124      * <li>{@link #KEYGUARD_DISABLE_WIDGETS_ALL} which affects the parent user when called on the
9125      * parent profile.
9126      * </ul>
9127      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, {@link #KEYGUARD_DISABLE_FINGERPRINT},
9128      * {@link #KEYGUARD_DISABLE_FACE}, {@link #KEYGUARD_DISABLE_IRIS},
9129      * {@link #KEYGUARD_DISABLE_SECURE_CAMERA} and {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS}
9130      * can also be set on the {@link DevicePolicyManager} instance returned by
9131      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
9132      * profile. {@link #KEYGUARD_DISABLE_SECURE_CAMERA} can only be set on the parent profile
9133      * instance if the calling device admin is the profile owner of an organization-owned
9134      * managed profile.
9135      * <p>
9136      * Requests to disable other features on a managed profile will be ignored.
9137      * <p>
9138      * The admin can check which features have been disabled by calling
9139      * {@link #getKeyguardDisabledFeatures(ComponentName)}
9140      *
9141      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
9142      *              caller is not a device admin
9143      * @param which The disabled features flag which can be either
9144      *            {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
9145      *            {@link #KEYGUARD_DISABLE_FEATURES_ALL}, or a combination of
9146      *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
9147      *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
9148      *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
9149      *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
9150      *            {@link #KEYGUARD_DISABLE_FINGERPRINT},
9151      *            {@link #KEYGUARD_DISABLE_FACE},
9152      *            {@link #KEYGUARD_DISABLE_IRIS},
9153      *            {@link #KEYGUARD_DISABLE_SHORTCUTS_ALL}.
9154      * @throws SecurityException if {@code admin} is not an active administrator or does not use
9155      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
9156      */
9157     @RequiresPermission(value = MANAGE_DEVICE_POLICY_KEYGUARD, conditional = true)
setKeyguardDisabledFeatures(@ullable ComponentName admin, int which)9158     public void setKeyguardDisabledFeatures(@Nullable ComponentName admin, int which) {
9159         if (mService != null) {
9160             try {
9161                 mService.setKeyguardDisabledFeatures(
9162                         admin, mContext.getPackageName(), which, mParentInstance);
9163             } catch (RemoteException e) {
9164                 throw e.rethrowFromSystemServer();
9165             }
9166         }
9167     }
9168 
9169     /**
9170      * Determine whether or not features have been disabled in keyguard either by the calling
9171      * admin, if specified, or all admins that set restrictions on this user and its participating
9172      * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
9173      *
9174      * <p>This method can be called on the {@link DevicePolicyManager} instance
9175      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
9176      * restrictions on the parent profile.
9177      *
9178      * @param admin The name of the admin component to check, or {@code null} to check whether any
9179      * admins have disabled features in keyguard.
9180      * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
9181      * for a list.
9182      */
getKeyguardDisabledFeatures(@ullable ComponentName admin)9183     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
9184         return getKeyguardDisabledFeatures(admin, myUserId());
9185     }
9186 
9187     private IpcDataCache<Pair<ComponentName, Integer>, Integer> mGetKeyGuardDisabledFeaturesCache =
9188             new IpcDataCache<>(sDpmCaches.child("getKeyguardDisabledFeatures"),
9189                     (query) -> getService().getKeyguardDisabledFeatures(
9190                             query.first, query.second, isParentInstance()));
9191 
9192     /** @hide per-user version */
9193     @UnsupportedAppUsage
getKeyguardDisabledFeatures(@ullable ComponentName admin, int userHandle)9194     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
9195         if (mService != null) {
9196             return mGetKeyGuardDisabledFeaturesCache.query(new Pair<>(admin, userHandle));
9197         } else {
9198             return KEYGUARD_DISABLE_FEATURES_NONE;
9199         }
9200     }
9201 
9202     /**
9203      * @hide
9204      */
9205     @TestApi
9206     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
9207     @RequiresPermission(allOf = {
9208             MANAGE_DEVICE_ADMINS,
9209             INTERACT_ACROSS_USERS_FULL
9210     })
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing, int userHandle)9211     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
9212             int userHandle) {
9213         if (mService != null) {
9214             try {
9215                 mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
9216             } catch (RemoteException e) {
9217                 throw e.rethrowFromSystemServer();
9218             }
9219         }
9220     }
9221 
9222     /**
9223      * @hide
9224      */
9225     @UnsupportedAppUsage
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing)9226     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
9227         setActiveAdmin(policyReceiver, refreshing, myUserId());
9228     }
9229 
9230     /**
9231      * Called by a privileged caller holding {@code BIND_DEVICE_ADMIN} permission to retrieve
9232      * the remove warning for the given device admin.
9233      * @hide
9234      */
getRemoveWarning(@ullable ComponentName admin, RemoteCallback result)9235     public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
9236         if (mService != null) {
9237             try {
9238                 mService.getRemoveWarning(admin, result, myUserId());
9239             } catch (RemoteException e) {
9240                 throw e.rethrowFromSystemServer();
9241             }
9242         }
9243     }
9244 
9245     /**
9246      * @hide
9247      */
9248     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportPasswordChanged(PasswordMetrics metrics, @UserIdInt int userId)9249     public void reportPasswordChanged(PasswordMetrics metrics, @UserIdInt int userId) {
9250         if (mService != null) {
9251             try {
9252                 mService.reportPasswordChanged(metrics, userId);
9253             } catch (RemoteException e) {
9254                 throw e.rethrowFromSystemServer();
9255             }
9256         }
9257     }
9258 
9259     /**
9260      * @hide
9261      */
9262     @UnsupportedAppUsage
9263     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedPasswordAttempt(int userHandle)9264     public void reportFailedPasswordAttempt(int userHandle) {
9265         if (mService != null) {
9266             try {
9267                 mService.reportFailedPasswordAttempt(userHandle, mParentInstance);
9268             } catch (RemoteException e) {
9269                 throw e.rethrowFromSystemServer();
9270             }
9271         }
9272     }
9273 
9274     /**
9275      * @hide
9276      */
9277     @UnsupportedAppUsage
9278     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulPasswordAttempt(int userHandle)9279     public void reportSuccessfulPasswordAttempt(int userHandle) {
9280         if (mService != null) {
9281             try {
9282                 mService.reportSuccessfulPasswordAttempt(userHandle);
9283             } catch (RemoteException e) {
9284                 throw e.rethrowFromSystemServer();
9285             }
9286         }
9287     }
9288 
9289     /**
9290      * @hide
9291      */
9292     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedBiometricAttempt(int userHandle)9293     public void reportFailedBiometricAttempt(int userHandle) {
9294         if (mService != null) {
9295             try {
9296                 mService.reportFailedBiometricAttempt(userHandle);
9297             } catch (RemoteException e) {
9298                 throw e.rethrowFromSystemServer();
9299             }
9300         }
9301     }
9302 
9303     /**
9304      * @hide
9305      */
9306     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulBiometricAttempt(int userHandle)9307     public void reportSuccessfulBiometricAttempt(int userHandle) {
9308         if (mService != null) {
9309             try {
9310                 mService.reportSuccessfulBiometricAttempt(userHandle);
9311             } catch (RemoteException e) {
9312                 throw e.rethrowFromSystemServer();
9313             }
9314         }
9315     }
9316 
9317     /**
9318      * Should be called when keyguard has been dismissed.
9319      * @hide
9320      */
reportKeyguardDismissed(int userHandle)9321     public void reportKeyguardDismissed(int userHandle) {
9322         if (mService != null) {
9323             try {
9324                 mService.reportKeyguardDismissed(userHandle);
9325             } catch (RemoteException e) {
9326                 throw e.rethrowFromSystemServer();
9327             }
9328         }
9329     }
9330 
9331     /**
9332      * Should be called when keyguard view has been shown to the user.
9333      * @hide
9334      */
reportKeyguardSecured(int userHandle)9335     public void reportKeyguardSecured(int userHandle) {
9336         if (mService != null) {
9337             try {
9338                 mService.reportKeyguardSecured(userHandle);
9339             } catch (RemoteException e) {
9340                 throw e.rethrowFromSystemServer();
9341             }
9342         }
9343     }
9344 
9345     /**
9346      * Sets the given package as the device owner.
9347      *
9348      * <p>Preconditions:
9349      * <ul>
9350      *   <li>The package must already be installed.
9351      *   <li>There must not already be a device owner.
9352      *   <li>Only apps with the {@code MANAGE_PROFILE_AND_DEVICE_OWNERS} permission or the
9353      *       {@link Process#SHELL_UID Shell UID} can call this method.
9354      * </ul>
9355      *
9356      * <p>Calling this after the setup phase of the device owner user has completed is allowed only
9357      * if the caller is the {@link Process#SHELL_UID Shell UID}, and there are no additional users
9358      * (except when the device runs on headless system user mode, in which case it could have exact
9359      * one extra user, which is the current user.
9360      *
9361      * <p>On a headless devices, if it is in affiliated mode the device owner will be set in the
9362      * {@link UserHandle#SYSTEM system} user. If the device is in single user mode, the device owner
9363      * will be set in the first secondary user.
9364      *
9365      * @param who the component name to be registered as device owner.
9366      * @param userId ID of the user on which the device owner runs.
9367      *
9368      * @return whether the package was successfully registered as the device owner.
9369      *
9370      * @throws IllegalArgumentException if the package name is {@code null} or invalid.
9371      * @throws IllegalStateException If the preconditions mentioned are not met.
9372      *
9373      * @hide
9374      */
9375     @TestApi
9376     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setDeviceOwner(@onNull ComponentName who, @UserIdInt int userId)9377     public boolean setDeviceOwner(@NonNull ComponentName who, @UserIdInt int userId) {
9378         if (mService != null) {
9379             try {
9380                 return mService.setDeviceOwner(who, userId,
9381                         /* setProfileOwnerOnCurrentUserIfNecessary= */ true);
9382             } catch (RemoteException re) {
9383                 throw re.rethrowFromSystemServer();
9384             }
9385         }
9386         return false;
9387     }
9388 
9389     /**
9390      * Same as {@link #setDeviceOwner(ComponentName, int)}, but without setting the profile
9391      * owner on current user when running on headless system user mode - should be used only by
9392      * testing infra.
9393      *
9394      * @hide
9395      */
9396     @TestApi
9397     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setDeviceOwnerOnly( @onNull ComponentName who, @UserIdInt int userId)9398     public boolean setDeviceOwnerOnly(
9399             @NonNull ComponentName who, @UserIdInt int userId) {
9400         if (mService != null) {
9401             try {
9402                 return mService.setDeviceOwner(who, userId,
9403                         /* setProfileOwnerOnCurrentUserIfNecessary= */ false);
9404             } catch (RemoteException re) {
9405                 throw re.rethrowFromSystemServer();
9406             }
9407         }
9408         return false;
9409     }
9410 
9411     /**
9412      * For apps targeting {@link Build.VERSION_CODES#VANILLA_ICE_CREAM} and above, the
9413      * {@link #isDeviceOwnerApp} method will use the user contained within the
9414      * context.
9415      * For apps targeting an SDK version <em>below</em> this, the user of the calling process will
9416      * be used (Process.myUserHandle()).
9417      *
9418      * @hide
9419      */
9420     @ChangeId
9421     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.VANILLA_ICE_CREAM)
9422     public static final long IS_DEVICE_OWNER_USER_AWARE = 307233716L;
9423 
9424     /**
9425      * Used to determine if a particular package has been registered as a Device Owner app.
9426      * A device owner app is a special device admin that cannot be deactivated by the user, once
9427      * activated as a device admin. It also cannot be uninstalled. To check whether a particular
9428      * package is currently registered as the device owner app, pass in the package name from
9429      * {@link Context#getPackageName()} to this method.<p/>This is useful for device
9430      * admin apps that want to check whether they are also registered as the device owner app. The
9431      * exact mechanism by which a device admin app is registered as a device owner app is defined by
9432      * the setup process.
9433      * @param packageName the package name of the app, to compare with the registered device owner
9434      * app, if any.
9435      * @return whether or not the package is registered as the device owner app.
9436      */
9437     @UserHandleAware(enabledSinceTargetSdkVersion = Build.VERSION_CODES.VANILLA_ICE_CREAM)
isDeviceOwnerApp(String packageName)9438     public boolean isDeviceOwnerApp(String packageName) {
9439         throwIfParentInstance("isDeviceOwnerApp");
9440         if (android.permission.flags.Flags.systemServerRoleControllerEnabled()
9441                 && CompatChanges.isChangeEnabled(IS_DEVICE_OWNER_USER_AWARE)) {
9442             return isDeviceOwnerAppOnContextUser(packageName);
9443         }
9444         return isDeviceOwnerAppOnCallingUser(packageName);
9445     }
9446 
9447     /**
9448      * @return true if a package is registered as device owner, only when it's running on the
9449      * calling user.
9450      *
9451      * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
9452      * @hide
9453      */
isDeviceOwnerAppOnCallingUser(String packageName)9454     public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
9455         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
9456     }
9457 
9458     /**
9459      * @return true if a package is registered as device owner, even if it's running on a different
9460      * user.
9461      *
9462      * <p>Requires the MANAGE_USERS permission.
9463      *
9464      * @hide
9465      */
isDeviceOwnerAppOnAnyUser(String packageName)9466     public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
9467         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
9468     }
9469 
9470     /**
9471      * @return device owner component name, only when it's running on the calling user.
9472      *
9473      * @hide
9474      */
getDeviceOwnerComponentOnCallingUser()9475     public ComponentName getDeviceOwnerComponentOnCallingUser() {
9476         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
9477     }
9478 
9479     /**
9480      * @return device owner component name, even if it's running on a different user.
9481      *
9482      * @hide
9483      */
9484     @SystemApi
9485     @RequiresPermission(anyOf = {
9486             android.Manifest.permission.MANAGE_USERS,
9487             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
9488     })
getDeviceOwnerComponentOnAnyUser()9489     public ComponentName getDeviceOwnerComponentOnAnyUser() {
9490         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
9491     }
9492 
isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly)9493     private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
9494         if (packageName == null) {
9495             return false;
9496         }
9497         final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
9498         if (deviceOwner == null) {
9499             return false;
9500         }
9501         return packageName.equals(deviceOwner.getPackageName());
9502     }
9503 
isDeviceOwnerAppOnContextUser(String packageName)9504     private boolean isDeviceOwnerAppOnContextUser(String packageName) {
9505         if (packageName == null) {
9506             return false;
9507         }
9508         ComponentName deviceOwner = null;
9509         if (mService != null) {
9510             try {
9511                 deviceOwner = mService.getDeviceOwnerComponentOnUser(myUserId());
9512             } catch (RemoteException re) {
9513                 throw re.rethrowFromSystemServer();
9514             }
9515         }
9516         if (deviceOwner == null) {
9517             return false;
9518         }
9519         return packageName.equals(deviceOwner.getPackageName());
9520     }
9521 
getDeviceOwnerComponentInner(boolean callingUserOnly)9522     private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
9523         if (mService != null) {
9524             try {
9525                 return mService.getDeviceOwnerComponent(callingUserOnly);
9526             } catch (RemoteException re) {
9527                 throw re.rethrowFromSystemServer();
9528             }
9529         }
9530         return null;
9531     }
9532 
9533     /**
9534      * @return Handle of the user who runs device owner, or {@code null} if there's no device owner.
9535      *
9536      * @hide
9537      */
9538     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
9539     @SystemApi
getDeviceOwnerUser()9540     public @Nullable UserHandle getDeviceOwnerUser() {
9541         if (mService != null) {
9542             try {
9543                 int userId = mService.getDeviceOwnerUserId();
9544 
9545                 if (userId != UserHandle.USER_NULL) {
9546                     return UserHandle.of(userId);
9547                 }
9548             } catch (RemoteException re) {
9549                 throw re.rethrowFromSystemServer();
9550             }
9551         }
9552         return null;
9553     }
9554 
9555     /**
9556      * @hide
9557      */
getDeviceOwnerUserId()9558     public int getDeviceOwnerUserId() {
9559         if (mService != null) {
9560             try {
9561                 return mService.getDeviceOwnerUserId();
9562             } catch (RemoteException re) {
9563                 throw re.rethrowFromSystemServer();
9564             }
9565         }
9566         return UserHandle.USER_NULL;
9567     }
9568 
9569     /**
9570      * Clears the current device owner. The caller must be the device owner. This function should be
9571      * used cautiously as once it is called it cannot be undone. The device owner can only be set as
9572      * a part of device setup, before it completes.
9573      * <p>
9574      * While some policies previously set by the device owner will be cleared by this method, it is
9575      * a best-effort process and some other policies will still remain in place after the device
9576      * owner is cleared.
9577      *
9578      * @param packageName The package name of the device owner.
9579      * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
9580      *             does not own the current device owner component.
9581      *
9582      * @deprecated This method is expected to be used for testing purposes only. The device owner
9583      * will lose control of the device and its data after calling it. In order to protect any
9584      * sensitive data that remains on the device, it is advised that the device owner factory resets
9585      * the device instead of calling this method. See {@link #wipeData(int)}.
9586      */
9587     @Deprecated
clearDeviceOwnerApp(String packageName)9588     public void clearDeviceOwnerApp(String packageName) {
9589         throwIfParentInstance("clearDeviceOwnerApp");
9590         if (mService != null) {
9591             try {
9592                 mService.clearDeviceOwner(packageName);
9593             } catch (RemoteException re) {
9594                 throw re.rethrowFromSystemServer();
9595             }
9596         }
9597     }
9598 
9599     /**
9600      * Returns the device owner package name, only if it's running on the calling user.
9601      *
9602      * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
9603      *
9604      * @hide
9605      */
9606     @SystemApi
9607     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwner()9608     public @Nullable String getDeviceOwner() {
9609         throwIfParentInstance("getDeviceOwner");
9610         final ComponentName name = getDeviceOwnerComponentOnCallingUser();
9611         return name != null ? name.getPackageName() : null;
9612     }
9613 
9614     private IpcDataCache<Void, Boolean> mHasDeviceOwnerCache =
9615             new IpcDataCache<>(sDpmCaches.child("hasDeviceOwner"),
9616                     (query) -> getService().hasDeviceOwner());
9617 
9618     /**
9619      * Called by the system to find out whether the device is managed by a Device Owner.
9620      *
9621      * @return whether the device is managed by a Device Owner.
9622      * @throws SecurityException if the caller is not the device owner, does not hold
9623      *         MANAGE_USERS or MANAGE_PROFILE_AND_DEVICE_OWNERS permissions and is not the system.
9624      *
9625      * @hide
9626      */
9627     @SystemApi
9628     @SuppressLint("RequiresPermission")
isDeviceManaged()9629     public boolean isDeviceManaged() {
9630         return mHasDeviceOwnerCache.query(null);
9631     }
9632 
9633     /**
9634      * Returns the device owner name.  Note this method *will* return the device owner
9635      * name when it's running on a different user.
9636      *
9637      * @hide
9638      */
9639     @SystemApi
9640     @RequiresPermission(anyOf = {
9641             android.Manifest.permission.MANAGE_USERS,
9642             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
9643     })
getDeviceOwnerNameOnAnyUser()9644     public String getDeviceOwnerNameOnAnyUser() {
9645         throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
9646         if (mService != null) {
9647             try {
9648                 return mService.getDeviceOwnerName();
9649             } catch (RemoteException re) {
9650                 throw re.rethrowFromSystemServer();
9651             }
9652         }
9653         return null;
9654     }
9655 
9656     /**
9657      * @hide
9658      * @deprecated Use #ACTION_SET_PROFILE_OWNER
9659      * Sets the given component as an active admin and registers the package as the profile
9660      * owner for this user. The package must already be installed and there shouldn't be
9661      * an existing profile owner registered for this user. Also, this method must be called
9662      * before the user setup has been completed.
9663      * <p>
9664      * This method can only be called by system apps that hold MANAGE_USERS permission and
9665      * MANAGE_DEVICE_ADMINS permission.
9666      * @param admin The component to register as an active admin and profile owner.
9667      * @param ownerName The user-visible name of the entity that is managing this user.
9668      * @return whether the admin was successfully registered as the profile owner.
9669      * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
9670      *         the user has already been set up.
9671      */
9672     @Deprecated
9673     @SystemApi
9674     @RequiresPermission(MANAGE_DEVICE_ADMINS)
setActiveProfileOwner(@onNull ComponentName admin, String ownerName)9675     public boolean setActiveProfileOwner(@NonNull ComponentName admin, String ownerName)
9676             throws IllegalArgumentException {
9677         throwIfParentInstance("setActiveProfileOwner");
9678         if (mService != null) {
9679             try {
9680                 final int myUserId = myUserId();
9681                 mService.setActiveAdmin(admin, false, myUserId);
9682                 return mService.setProfileOwner(admin, myUserId);
9683             } catch (RemoteException re) {
9684                 throw re.rethrowFromSystemServer();
9685             }
9686         }
9687         return false;
9688     }
9689 
9690     /**
9691      * Clears the active profile owner. The caller must be the profile owner of this user, otherwise
9692      * a SecurityException will be thrown. This method is not available to managed profile owners.
9693      * <p>
9694      * While some policies previously set by the profile owner will be cleared by this method, it is
9695      * a best-effort process and some other policies will still remain in place after the profile
9696      * owner is cleared.
9697      *
9698      * @param admin The component to remove as the profile owner.
9699      * @throws SecurityException if {@code admin} is not an active profile owner, or the method is
9700      * being called from a managed profile.
9701      *
9702      * @deprecated This method is expected to be used for testing purposes only. The profile owner
9703      * will lose control of the user and its data after calling it. In order to protect any
9704      * sensitive data that remains on this user, it is advised that the profile owner deletes it
9705      * instead of calling this method. See {@link #wipeData(int)}.
9706      */
9707     @Deprecated
clearProfileOwner(@onNull ComponentName admin)9708     public void clearProfileOwner(@NonNull ComponentName admin) {
9709         throwIfParentInstance("clearProfileOwner");
9710         if (mService != null) {
9711             try {
9712                 mService.clearProfileOwner(admin);
9713             } catch (RemoteException re) {
9714                 throw re.rethrowFromSystemServer();
9715             }
9716         }
9717     }
9718 
9719     /**
9720      * @hide
9721      * Checks whether the user was already setup.
9722      */
hasUserSetupCompleted()9723     public boolean hasUserSetupCompleted() {
9724         if (mService != null) {
9725             try {
9726                 return mService.hasUserSetupCompleted();
9727             } catch (RemoteException re) {
9728                 throw re.rethrowFromSystemServer();
9729             }
9730         }
9731         return true;
9732     }
9733 
9734     /**
9735      * @hide
9736      * Sets the given component as the profile owner of the given user profile. The package must
9737      * already be installed. There must not already be a profile owner for this user.
9738      * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
9739      * this method.
9740      * Calling this after the setup phase of the specified user has completed is allowed only if:
9741      * - the caller is SYSTEM_UID.
9742      * - or the caller is the shell uid, and there are no accounts on the specified user.
9743      * @param admin the component name to be registered as profile owner.
9744      * @param userHandle the userId to set the profile owner for.
9745      * @return whether the component was successfully registered as the profile owner.
9746      * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
9747      * preconditions mentioned are not met.
9748      */
setProfileOwner(@onNull ComponentName admin, int userHandle)9749     public boolean setProfileOwner(@NonNull ComponentName admin, int userHandle)
9750             throws IllegalArgumentException {
9751         if (mService != null) {
9752             try {
9753                 return mService.setProfileOwner(admin, userHandle);
9754             } catch (RemoteException re) {
9755                 throw re.rethrowFromSystemServer();
9756             }
9757         }
9758         return false;
9759     }
9760 
9761     /**
9762      * Sets the device owner information to be shown on the lock screen.
9763      * <p>
9764      * Device owner information set using this method overrides any owner information manually set
9765      * by the user and prevents the user from further changing it.
9766      * <p>
9767      * If the device owner information is {@code null} or empty then the device owner info is
9768      * cleared and the user owner info is shown on the lock screen if it is set.
9769      * <p>
9770      * If the device owner information contains only whitespaces then the message on the lock screen
9771      * will be blank and the user will not be allowed to change it.
9772      * <p>
9773      * If the device owner information needs to be localized, it is the responsibility of the
9774      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9775      * and set a new version of this string accordingly.
9776      * <p>
9777      * May be called by the device owner or the profile owner of an organization-owned device.
9778      *
9779      * @param admin The name of the admin component to check.
9780      * @param info Device owner information which will be displayed instead of the user owner info.
9781      * @throws SecurityException if {@code admin} is not a device owner.
9782      */
setDeviceOwnerLockScreenInfo(@onNull ComponentName admin, CharSequence info)9783     public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
9784         throwIfParentInstance("setDeviceOwnerLockScreenInfo");
9785         if (mService != null) {
9786             try {
9787                 mService.setDeviceOwnerLockScreenInfo(admin, info);
9788             } catch (RemoteException re) {
9789                 throw re.rethrowFromSystemServer();
9790             }
9791         }
9792     }
9793 
9794     /**
9795      * @return The device owner information. If it is not set returns {@code null}.
9796      */
getDeviceOwnerLockScreenInfo()9797     public CharSequence getDeviceOwnerLockScreenInfo() {
9798         throwIfParentInstance("getDeviceOwnerLockScreenInfo");
9799         if (mService != null) {
9800             try {
9801                 return mService.getDeviceOwnerLockScreenInfo();
9802             } catch (RemoteException re) {
9803                 throw re.rethrowFromSystemServer();
9804             }
9805         }
9806         return null;
9807     }
9808 
9809     /**
9810      * Called by device or profile owners to suspend packages for this user. This function can be
9811      * called by a device owner, profile owner, or by a delegate given the
9812      * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}.
9813      * <p>
9814      * A suspended package will not be able to start activities. Its notifications will be hidden,
9815      * it will not show up in recents, will not be able to show toasts or dialogs or ring the
9816      * device.
9817      * <p>
9818      * The package must already be installed. If the package is uninstalled while suspended the
9819      * package will no longer be suspended. The admin can block this by using
9820      * {@link #setUninstallBlocked}.
9821      *
9822      * <p>Some apps cannot be suspended, such as device admins, the active launcher, the required
9823      * package installer, the required package uninstaller, the required package verifier, the
9824      * default dialer, and the permission controller.
9825      *
9826      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
9827      *              caller is not a device admin.
9828      * @param packageNames The package names to suspend or unsuspend.
9829      * @param suspended If set to {@code true} than the packages will be suspended, if set to
9830      *            {@code false} the packages will be unsuspended.
9831      * @return an array of package names for which the suspended status is not set as requested in
9832      *         this method.
9833      * @throws SecurityException if {@code admin} is not a device or profile owner.
9834      * @see #setDelegatedScopes
9835      * @see #DELEGATION_PACKAGE_ACCESS
9836      */
9837     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PACKAGE_STATE, conditional = true)
9838     @NonNull
setPackagesSuspended(@ullable ComponentName admin, @NonNull String[] packageNames, boolean suspended)9839     public String[] setPackagesSuspended(@Nullable ComponentName admin,
9840             @NonNull String[] packageNames, boolean suspended) {
9841         throwIfParentInstance("setPackagesSuspended");
9842         if (mService != null) {
9843             try {
9844                 return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames,
9845                         suspended);
9846             } catch (RemoteException re) {
9847                 throw re.rethrowFromSystemServer();
9848             }
9849         }
9850         return packageNames;
9851     }
9852 
9853     /**
9854      * Determine if a package is suspended. This function can be called by a device owner, profile
9855      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
9856      * {@link #setDelegatedScopes} or by holders of the permission
9857      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PACKAGE_STATE}.
9858      *
9859      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
9860      *              caller is not a device admin.
9861      * @param packageName The name of the package to retrieve the suspended status of.
9862      * @return {@code true} if the package is suspended or {@code false} if the package is not
9863      *         suspended, could not be found or an error occurred.
9864      * @throws SecurityException if {@code admin} is not a device or profile owner or has not been
9865      * granted the permission
9866      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PACKAGE_STATE}.
9867      * @throws NameNotFoundException if the package could not be found.
9868      * @see #setDelegatedScopes
9869      * @see #DELEGATION_PACKAGE_ACCESS
9870      */
9871     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PACKAGE_STATE, conditional = true)
isPackageSuspended(@ullable ComponentName admin, String packageName)9872     public boolean isPackageSuspended(@Nullable ComponentName admin, String packageName)
9873             throws NameNotFoundException {
9874         throwIfParentInstance("isPackageSuspended");
9875         if (mService != null) {
9876             try {
9877                 return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName);
9878             } catch (RemoteException e) {
9879                 throw e.rethrowFromSystemServer();
9880             } catch (IllegalArgumentException ex) {
9881                 Log.e(TAG, "IllegalArgumentException checking isPackageSuspended", ex);
9882                 throw new NameNotFoundException(packageName);
9883             }
9884         }
9885         return false;
9886     }
9887 
9888     /**
9889      * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
9890      * be used. Only the profile owner can call this.
9891      *
9892      * @see #isProfileOwnerApp
9893      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9894      * @throws SecurityException if {@code admin} is not a profile owner.
9895      */
setProfileEnabled(@onNull ComponentName admin)9896     public void setProfileEnabled(@NonNull ComponentName admin) {
9897         throwIfParentInstance("setProfileEnabled");
9898         if (mService != null) {
9899             try {
9900                 mService.setProfileEnabled(admin);
9901             } catch (RemoteException e) {
9902                 throw e.rethrowFromSystemServer();
9903             }
9904         }
9905     }
9906 
9907     /**
9908      * Sets the name of the profile. In the device owner case it sets the name of the user which it
9909      * is called from. Only a profile owner or device owner can call this. If this is never called
9910      * by the profile or device owner, the name will be set to default values.
9911      *
9912      * @see #isProfileOwnerApp
9913      * @see #isDeviceOwnerApp
9914      * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
9915      * @param profileName The name of the profile. If the name is longer than 200 characters
9916      *                    it will be truncated.
9917      * @throws SecurityException if {@code admin} is not a device or profile owner.
9918      */
setProfileName(@onNull ComponentName admin, String profileName)9919     public void setProfileName(@NonNull ComponentName admin, String profileName) {
9920         throwIfParentInstance("setProfileName");
9921         if (mService != null) {
9922             try {
9923                 mService.setProfileName(admin, profileName);
9924             } catch (RemoteException e) {
9925                 throw e.rethrowFromSystemServer();
9926             }
9927         }
9928     }
9929 
9930     /**
9931      * Used to determine if a particular package is registered as the profile owner for the
9932      * user. A profile owner is a special device admin that has additional privileges
9933      * within the profile.
9934      *
9935      * @param packageName The package name of the app to compare with the registered profile owner.
9936      * @return Whether or not the package is registered as the profile owner.
9937      */
9938     @UserHandleAware
isProfileOwnerApp(String packageName)9939     public boolean isProfileOwnerApp(String packageName) {
9940         throwIfParentInstance("isProfileOwnerApp");
9941         if (mService != null) {
9942             try {
9943                 ComponentName profileOwner = mService.getProfileOwnerAsUser(myUserId());
9944                 return profileOwner != null
9945                         && profileOwner.getPackageName().equals(packageName);
9946             } catch (RemoteException re) {
9947                 throw re.rethrowFromSystemServer();
9948             }
9949         }
9950         return false;
9951     }
9952 
9953     /**
9954      * @hide
9955      * @return the packageName of the owner of the given user profile or {@code null} if no profile
9956      * owner has been set for that user.
9957      * @throws IllegalArgumentException if the userId is invalid.
9958      */
9959     @SystemApi
getProfileOwner()9960     public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
9961         throwIfParentInstance("getProfileOwner");
9962         return getProfileOwnerAsUser(mContext.getUserId());
9963     }
9964 
9965     /**
9966      * @see #getProfileOwner()
9967      * @hide
9968      */
9969     @RequiresPermission(value = android.Manifest.permission.INTERACT_ACROSS_USERS,
9970             conditional = true)
getProfileOwnerAsUser(@onNull UserHandle user)9971     public @Nullable ComponentName getProfileOwnerAsUser(@NonNull UserHandle user) {
9972         if (mService != null) {
9973             try {
9974                 return mService.getProfileOwnerAsUser(user.getIdentifier());
9975             } catch (RemoteException re) {
9976                 throw re.rethrowFromSystemServer();
9977             }
9978         }
9979         return null;
9980     }
9981 
9982     /**
9983      * @hide
9984      */
9985     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getProfileOwnerAsUser(final int userId)9986     public @Nullable ComponentName getProfileOwnerAsUser(final int userId) {
9987         if (mService != null) {
9988             try {
9989                 return mService.getProfileOwnerAsUser(userId);
9990             } catch (RemoteException re) {
9991                 throw re.rethrowFromSystemServer();
9992             }
9993         }
9994         return null;
9995     }
9996 
9997     private final IpcDataCache<UserHandle, ComponentName>
9998             mGetProfileOwnerOrDeviceOwnerSupervisionComponentCache =
9999             new IpcDataCache<>(sDpmCaches.child("getProfileOwnerOrDeviceOwnerSupervisionComponent"),
10000                     (arg) -> getService().getProfileOwnerOrDeviceOwnerSupervisionComponent(arg));
10001 
10002     /**
10003      * Returns the configured supervision app if it exists and is the device owner or policy owner.
10004      * @hide
10005      */
getProfileOwnerOrDeviceOwnerSupervisionComponent( @onNull UserHandle user)10006     public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent(
10007             @NonNull UserHandle user) {
10008         if (mService != null) {
10009             return mGetProfileOwnerOrDeviceOwnerSupervisionComponentCache.query(user);
10010         }
10011         return null;
10012     }
10013 
10014     /**
10015      * Checks if the specified component is the supervision component.
10016      * @hide
10017      */
isSupervisionComponent(@onNull ComponentName who)10018     public boolean isSupervisionComponent(@NonNull ComponentName who) {
10019         if (mService != null) {
10020             try {
10021                 return getService().isSupervisionComponent(who);
10022             } catch (RemoteException re) {
10023                 throw re.rethrowFromSystemServer();
10024             }
10025         }
10026         return false;
10027     }
10028 
10029     /**
10030      * @hide
10031      * @return the human readable name of the organisation associated with this DPM or {@code null}
10032      *         if one is not set.
10033      * @throws IllegalArgumentException if the userId is invalid.
10034      */
getProfileOwnerName()10035     public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
10036         if (mService != null) {
10037             try {
10038                 return mService.getProfileOwnerName(mContext.getUserId());
10039             } catch (RemoteException re) {
10040                 throw re.rethrowFromSystemServer();
10041             }
10042         }
10043         return null;
10044     }
10045 
10046     /**
10047      * @hide
10048      * @param userId The user for whom to fetch the profile owner name, if any.
10049      * @return the human readable name of the organisation associated with this profile owner or
10050      *         null if one is not set.
10051      * @throws IllegalArgumentException if the userId is invalid.
10052      */
10053     @SystemApi
10054     @RequiresPermission(anyOf = {
10055             android.Manifest.permission.MANAGE_USERS,
10056             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
10057     })
getProfileOwnerNameAsUser(int userId)10058     public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
10059         throwIfParentInstance("getProfileOwnerNameAsUser");
10060         if (mService != null) {
10061             try {
10062                 return mService.getProfileOwnerName(userId);
10063             } catch (RemoteException re) {
10064                 throw re.rethrowFromSystemServer();
10065             }
10066         }
10067         return null;
10068     }
10069 
10070     private final IpcDataCache<Void, Boolean> mIsOrganizationOwnedDeviceWithManagedProfileCache =
10071             new IpcDataCache(sDpmCaches.child("isOrganizationOwnedDeviceWithManagedProfile"),
10072                     (query) -> getService().isOrganizationOwnedDeviceWithManagedProfile());
10073 
10074     /**
10075      * Apps can use this method to find out if the device was provisioned as
10076      * organization-owend device with a managed profile.
10077      *
10078      * This, together with checking whether the device has a device owner (by calling
10079      * {@link #isDeviceOwnerApp}), could be used to learn whether the device is owned by an
10080      * organization or an individual:
10081      * If this method returns true OR {@link #isDeviceOwnerApp} returns true (for any package),
10082      * then the device is owned by an organization. Otherwise, it's owned by an individual.
10083      *
10084      * @return {@code true} if the device was provisioned as organization-owned device,
10085      * {@code false} otherwise.
10086      */
isOrganizationOwnedDeviceWithManagedProfile()10087     public boolean isOrganizationOwnedDeviceWithManagedProfile() {
10088         throwIfParentInstance("isOrganizationOwnedDeviceWithManagedProfile");
10089         if (mService != null) {
10090             return mIsOrganizationOwnedDeviceWithManagedProfileCache.query(null);
10091         }
10092         return false;
10093     }
10094 
10095     /**
10096      * Returns whether the specified package can read the device identifiers.
10097      *
10098      * @param packageName The package name of the app to check for device identifier access.
10099      * @param pid The process id of the package to be checked.
10100      * @param uid The uid of the package to be checked.
10101      * @return whether the package can read the device identifiers.
10102      *
10103      * @hide
10104      */
hasDeviceIdentifierAccess(@onNull String packageName, int pid, int uid)10105     public boolean hasDeviceIdentifierAccess(@NonNull String packageName, int pid, int uid) {
10106         throwIfParentInstance("hasDeviceIdentifierAccess");
10107         if (packageName == null) {
10108             return false;
10109         }
10110         if (mService != null) {
10111             try {
10112                 return mService.checkDeviceIdentifierAccess(packageName, pid, uid);
10113             } catch (RemoteException re) {
10114                 throw re.rethrowFromSystemServer();
10115             }
10116         }
10117         return false;
10118     }
10119 
10120     /**
10121      * Called by a profile owner or device owner or holder of the permission
10122      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}. to set a default activity
10123      * that the system selects to handle intents that match the given {@link IntentFilter} instead
10124      * of showing the default disambiguation mechanism.
10125      * This activity will remain the default intent handler even if the set of potential event
10126      * handlers for the intent filter changes and if the intent preferences are reset.
10127      * <p>
10128      * Note that the target application should still declare the activity in the manifest, the API
10129      * just sets the activity to be the default one to handle the given intent filter.
10130      * <p>
10131      * The default disambiguation mechanism takes over if the activity is not installed (anymore).
10132      * When the activity is (re)installed, it is automatically reset as default intent handler for
10133      * the filter.
10134      * <p>
10135      * Note that calling this API to set a default intent handler, only allow to avoid the default
10136      * disambiguation mechanism. Implicit intents that do not trigger this mechanism (like invoking
10137      * the browser) cannot be configured as they are controlled by other configurations.
10138      * <p>
10139      * The calling device admin must be a profile owner or device owner. If it is not, a security
10140      * exception will be thrown.
10141      * <p>
10142      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the persistent preferred
10143      * activity policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
10144      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
10145      * successfully set or not. This callback will contain:
10146      * <ul>
10147      * <li> The policy identifier
10148      * {@link DevicePolicyIdentifiers#PERSISTENT_PREFERRED_ACTIVITY_POLICY}
10149      * <li> The additional policy params bundle, which contains
10150      * {@link PolicyUpdateReceiver#EXTRA_INTENT_FILTER} the intent filter the policy applies to
10151      * <li> The {@link TargetUser} that this policy relates to
10152      * <li> The {@link PolicyUpdateResult}, which will be
10153      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
10154      * reason the policy failed to be set
10155      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
10156      * </ul>
10157      * If there has been a change to the policy,
10158      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
10159      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
10160      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
10161      * will contain the reason why the policy changed.
10162      *
10163      * <p>NOTE: Performs disk I/O and shouldn't be called on the main thread.
10164      *
10165      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
10166      *        caller is not a device admin.
10167      * @param filter The IntentFilter for which a default handler is added.
10168      * @param activity The Activity that is added as default intent handler.
10169      * @throws SecurityException if {@code admin} is not a device or profile owner or holder of the
10170      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}.
10171      */
10172     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true)
10173     @SupportsCoexistence
addPersistentPreferredActivity(@ullable ComponentName admin, IntentFilter filter, @NonNull ComponentName activity)10174     public void addPersistentPreferredActivity(@Nullable ComponentName admin, IntentFilter filter,
10175             @NonNull ComponentName activity) {
10176         throwIfParentInstance("addPersistentPreferredActivity");
10177         if (mService != null) {
10178             try {
10179                 mService.addPersistentPreferredActivity(admin, mContext.getPackageName(), filter,
10180                         activity);
10181             } catch (RemoteException e) {
10182                 throw e.rethrowFromSystemServer();
10183             }
10184         }
10185     }
10186 
10187     /**
10188      * Called by a profile owner or device owner or holder of the
10189      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK} to remove all
10190      * persistent intent handler preferences associated with the given package that were set by
10191      * {@link #addPersistentPreferredActivity}.
10192      * <p>
10193      * The calling device admin must be a profile owner. If it is not, a security exception will be
10194      * thrown.
10195      * <p>
10196      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the persistent preferred
10197      * activity policy has been cleared, {@link PolicyUpdateReceiver#onPolicySetResult(Context,
10198      * String, Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy
10199      * was successfully cleared or not. This callback will contain:
10200      * <ul>
10201      * <li> The policy identifier
10202      * {@link DevicePolicyIdentifiers#PERSISTENT_PREFERRED_ACTIVITY_POLICY}
10203      * <li> The additional policy params bundle, which contains
10204      * {@link PolicyUpdateReceiver#EXTRA_INTENT_FILTER} the intent filter the policy applies to
10205      * <li> The {@link TargetUser} that this policy relates to
10206      * <li> The {@link PolicyUpdateResult}, which will be
10207      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully cleared or the
10208      * reason the policy failed to be cleared
10209      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
10210      * </ul>
10211      * If there has been a change to the policy,
10212      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
10213      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
10214      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
10215      * will contain the reason why the policy changed.
10216      *
10217      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
10218      *              caller is not a device admin.
10219      * @param packageName The name of the package for which preferences are removed.
10220      * @throws SecurityException if {@code admin} is not a device or profile owner or holder of the
10221      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}.
10222      */
10223     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true)
clearPackagePersistentPreferredActivities(@ullable ComponentName admin, String packageName)10224     public void clearPackagePersistentPreferredActivities(@Nullable ComponentName admin,
10225             String packageName) {
10226         throwIfParentInstance("clearPackagePersistentPreferredActivities");
10227         if (mService != null) {
10228             try {
10229                 mService.clearPackagePersistentPreferredActivities(
10230                         admin,
10231                         mContext.getPackageName(),
10232                         packageName);
10233             } catch (RemoteException e) {
10234                 throw e.rethrowFromSystemServer();
10235             }
10236         }
10237     }
10238 
10239     /**
10240      * Must be called by a device owner or a profile owner of an organization-owned managed profile
10241      * to set the default SMS application.
10242      * <p>
10243      * This method can be called on the {@link DevicePolicyManager} instance, returned by
10244      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
10245      * of an organization-owned managed profile and the package must be a pre-installed system
10246      * package. If called on the parent instance, then the default SMS application is set on the
10247      * personal profile.
10248      * <p>
10249      * Starting from Android {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the profile
10250      * owner of an organization-owned managed profile can also call this method directly (not on the
10251      * parent profile instance) to set the default SMS application in the work profile. This is only
10252      * meaningful when work profile telephony is enabled by {@link #setManagedSubscriptionsPolicy}.
10253      *
10254      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
10255      *              caller is not a device admin.
10256      * @param packageName The name of the package to set as the default SMS application.
10257      * @throws SecurityException        if {@code admin} is not a device or profile owner or if
10258      *                                  called on the parent profile and the {@code admin} is not a
10259      *                                  profile owner of an organization-owned managed profile.
10260      * @throws IllegalArgumentException if called on the parent profile and the package
10261      *                                  provided is not a pre-installed system package.
10262      * @throws IllegalStateException while trying to set default sms app on the profile and
10263      *                             {@link ManagedSubscriptionsPolicy#TYPE_ALL_MANAGED_SUBSCRIPTIONS}
10264      *                             policy is not set.
10265      */
10266     @RequiresPermission(value = MANAGE_DEVICE_POLICY_DEFAULT_SMS, conditional = true)
setDefaultSmsApplication(@ullable ComponentName admin, @NonNull String packageName)10267     public void setDefaultSmsApplication(@Nullable ComponentName admin,
10268             @NonNull String packageName) {
10269         if (mService != null) {
10270             try {
10271                 mService.setDefaultSmsApplication(admin, mContext.getPackageName(), packageName,
10272                         mParentInstance);
10273             } catch (RemoteException e) {
10274                 throw e.rethrowFromSystemServer();
10275             }
10276         }
10277     }
10278 
10279     /**
10280      * Must be called by a device owner or a profile owner of an organization-owned managed profile
10281      * to set the default dialer application for the calling user.
10282      * <p>
10283      * When the profile owner of an organization-owned managed profile calls this method, it sets
10284      * the default dialer application in the work profile. This is only meaningful when work profile
10285      * telephony is enabled by {@link #setManagedSubscriptionsPolicy}.
10286      * <p>
10287      * If the device does not support telephony ({@link PackageManager#FEATURE_TELEPHONY}), calling
10288      * this method will do nothing.
10289      *
10290      * @param packageName The name of the package to set as the default dialer application.
10291      * @throws SecurityException        if {@code admin} is not a device or profile owner or a
10292      *                                  profile owner of an organization-owned managed profile.
10293      * @throws IllegalArgumentException if the package cannot be set as the default dialer, for
10294      *                                  example if the package is not installed or does not expose
10295      *                                  the expected activities or services that a dialer app is
10296      *                                  required to have.
10297      */
setDefaultDialerApplication(@onNull String packageName)10298     public void setDefaultDialerApplication(@NonNull String packageName) {
10299         throwIfParentInstance("setDefaultDialerApplication");
10300         if (mService != null) {
10301             try {
10302                 mService.setDefaultDialerApplication(packageName);
10303             } catch (RemoteException e) {
10304                 throw e.rethrowFromSystemServer();
10305             }
10306         }
10307     }
10308 
10309     /**
10310      * Called by a profile owner or device owner to grant permission to a package to manage
10311      * application restrictions for the calling user via {@link #setApplicationRestrictions} and
10312      * {@link #getApplicationRestrictions}.
10313      * <p>
10314      * This permission is persistent until it is later cleared by calling this method with a
10315      * {@code null} value or uninstalling the managing package.
10316      * <p>
10317      * The supplied application restriction managing package must be installed when calling this
10318      * API, otherwise an {@link NameNotFoundException} will be thrown.
10319      *
10320      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10321      * @param packageName The package name which will be given access to application restrictions
10322      *            APIs. If {@code null} is given the current package will be cleared.
10323      * @throws SecurityException if {@code admin} is not a device or profile owner.
10324      * @throws NameNotFoundException if {@code packageName} is not found
10325      *
10326      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
10327      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
10328      */
10329     @Deprecated
setApplicationRestrictionsManagingPackage(@onNull ComponentName admin, @Nullable String packageName)10330     public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
10331             @Nullable String packageName) throws NameNotFoundException {
10332         throwIfParentInstance("setApplicationRestrictionsManagingPackage");
10333         if (mService != null) {
10334             try {
10335                 if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
10336                     throw new NameNotFoundException(packageName);
10337                 }
10338             } catch (RemoteException e) {
10339                 throw e.rethrowFromSystemServer();
10340             }
10341         }
10342     }
10343 
10344     /**
10345      * Called by a profile owner or device owner to retrieve the application restrictions managing
10346      * package for the current user, or {@code null} if none is set. If there are multiple
10347      * delegates this function will return one of them.
10348      *
10349      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10350      * @return The package name allowed to manage application restrictions on the current user, or
10351      *         {@code null} if none is set.
10352      * @throws SecurityException if {@code admin} is not a device or profile owner.
10353      *
10354      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
10355      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
10356      */
10357     @Deprecated
10358     @Nullable
getApplicationRestrictionsManagingPackage( @onNull ComponentName admin)10359     public String getApplicationRestrictionsManagingPackage(
10360             @NonNull ComponentName admin) {
10361         throwIfParentInstance("getApplicationRestrictionsManagingPackage");
10362         if (mService != null) {
10363             try {
10364                 return mService.getApplicationRestrictionsManagingPackage(admin);
10365             } catch (RemoteException e) {
10366                 throw e.rethrowFromSystemServer();
10367             }
10368         }
10369         return null;
10370     }
10371 
10372     /**
10373      * Called by any application to find out whether it has been granted permission via
10374      * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
10375      * for the calling user.
10376      *
10377      * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
10378      * that method.
10379      *
10380      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes}
10381      * instead.
10382      */
10383     @Deprecated
isCallerApplicationRestrictionsManagingPackage()10384     public boolean isCallerApplicationRestrictionsManagingPackage() {
10385         throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
10386         if (mService != null) {
10387             try {
10388                 return mService.isCallerApplicationRestrictionsManagingPackage(
10389                         mContext.getPackageName());
10390             } catch (RemoteException e) {
10391                 throw e.rethrowFromSystemServer();
10392             }
10393         }
10394         return false;
10395     }
10396 
10397     /**
10398      * Sets the application restrictions for a given target application running in the calling user.
10399      * <p>
10400      * The caller must be a profile or device owner on that user, or the package allowed to manage
10401      * application restrictions via {@link #setDelegatedScopes} with the
10402      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
10403      * <p>
10404      * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
10405      * <ul>
10406      * <li>{@code boolean}
10407      * <li>{@code int}
10408      * <li>{@code String} or {@code String[]}
10409      * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
10410      * </ul>
10411      * <p>
10412      * If the restrictions are not available yet, but may be applied in the near future, the caller
10413      * can notify the target application of that by adding
10414      * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
10415      * <p>
10416      * The application restrictions are only made visible to the target application via
10417      * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
10418      * owner, and the application restrictions managing package via
10419      * {@link #getApplicationRestrictions}.
10420      *
10421      * <p>Starting from Android Version {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE},
10422      * multiple admins can set app restrictions for the same application, the target application can
10423      * get the list of app restrictions set by each admin via
10424      * {@link android.content.RestrictionsManager#getApplicationRestrictionsPerAdmin}.
10425      *
10426      * <p>Starting from Android Version {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM},
10427      * the device policy management role holder can also set app restrictions on any applications
10428      * in the calling user, as well as the parent user of an organization-owned managed profile via
10429      * the {@link DevicePolicyManager} instance returned by
10430      * {@link #getParentProfileInstance(ComponentName)}. App restrictions set by the device policy
10431      * management role holder are not returned by
10432      * {@link UserManager#getApplicationRestrictions(String)}. The target application should use
10433      * {@link android.content.RestrictionsManager#getApplicationRestrictionsPerAdmin} to retrieve
10434      * them, alongside any app restrictions the profile or device owner might have set.
10435      *
10436      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
10437      *
10438      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10439      *            {@code null} if called by the application restrictions managing package.
10440      * @param packageName The name of the package to update restricted settings for.
10441      * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
10442      *            set of active restrictions.
10443      * @throws SecurityException if {@code admin} is not a device or profile owner.
10444      * @see #setDelegatedScopes
10445      * @see #DELEGATION_APP_RESTRICTIONS
10446      * @see UserManager#KEY_RESTRICTIONS_PENDING
10447      */
10448     @WorkerThread
setApplicationRestrictions(@ullable ComponentName admin, String packageName, Bundle settings)10449     public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
10450             Bundle settings) {
10451         if (!Flags.dmrhSetAppRestrictions()) {
10452             throwIfParentInstance("setApplicationRestrictions");
10453         }
10454 
10455         if (mService != null) {
10456             try {
10457                 mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName,
10458                         settings, mParentInstance);
10459             } catch (RemoteException e) {
10460                 throw e.rethrowFromSystemServer();
10461             }
10462         }
10463     }
10464 
10465     /**
10466      * Sets a list of configuration features to enable for a trust agent component. This is meant to
10467      * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
10468      * agents but those enabled by this function call. If flag
10469      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
10470      * <p>
10471      * For any specific trust agent, whether it is disabled or not depends on the aggregated state
10472      * of each admin's {@link #KEYGUARD_DISABLE_TRUST_AGENTS} setting and its trust agent
10473      * configuration as set by this function call. In particular: if any admin sets
10474      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and does not additionally set any
10475      * trust agent configuration, the trust agent is disabled completely. Otherwise, the trust agent
10476      * will receive the list of configurations from all admins who set
10477      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and aggregate the configurations to determine its
10478      * behavior. The exact meaning of aggregation is trust-agent-specific.
10479      * <p>
10480      * A calling device admin must have requested
10481      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
10482      * if not, a security exception will be thrown.
10483      * <p>
10484      * This method can be called on the {@link DevicePolicyManager} instance returned by
10485      * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
10486      * the parent profile.
10487      * <p>
10488      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, calling
10489      * this method has no effect - no trust agent configuration will be set.
10490      *
10491      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
10492      *              caller is not a device admin
10493      * @param target Component name of the agent to be configured.
10494      * @param configuration Trust-agent-specific feature configuration bundle. Please consult
10495      *        documentation of the specific trust agent to determine the interpretation of this
10496      *        bundle.
10497      * @throws SecurityException if {@code admin} is not an active administrator or does not use
10498      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
10499      */
10500     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
10501     @RequiresPermission(value = MANAGE_DEVICE_POLICY_KEYGUARD, conditional = true)
setTrustAgentConfiguration(@ullable ComponentName admin, @NonNull ComponentName target, PersistableBundle configuration)10502     public void setTrustAgentConfiguration(@Nullable ComponentName admin,
10503             @NonNull ComponentName target, PersistableBundle configuration) {
10504         if (mService != null) {
10505             try {
10506                 mService.setTrustAgentConfiguration(
10507                         admin, mContext.getPackageName(), target, configuration, mParentInstance);
10508             } catch (RemoteException e) {
10509                 throw e.rethrowFromSystemServer();
10510             }
10511         }
10512     }
10513 
10514     /**
10515      * Gets configuration for the given trust agent based on aggregating all calls to
10516      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
10517      * all device admins.
10518      * <p>
10519      * This method can be called on the {@link DevicePolicyManager} instance returned by
10520      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
10521      * on the parent profile.
10522      * <p>
10523      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, null is
10524      * always returned.
10525      *
10526      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
10527      * this function returns a list of configurations for all admins that declare
10528      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
10529      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
10530      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
10531      * for this {@param agent} or calls it with a null configuration, null is returned.
10532      * @param agent Which component to get enabled features for.
10533      * @return configuration for the given trust agent.
10534      */
10535     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent)10536     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
10537             @Nullable ComponentName admin, @NonNull ComponentName agent) {
10538         return getTrustAgentConfiguration(admin, agent, myUserId());
10539     }
10540 
10541     /** @hide per-user version */
10542     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
10543     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent, int userHandle)10544     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
10545             @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
10546         if (mService != null) {
10547             try {
10548                 return mService.getTrustAgentConfiguration(admin, agent, userHandle,
10549                         mParentInstance);
10550             } catch (RemoteException e) {
10551                 throw e.rethrowFromSystemServer();
10552             }
10553         }
10554         return new ArrayList<PersistableBundle>(); // empty list
10555     }
10556 
10557     /**
10558      * Called by a profile owner of a managed profile to set whether caller-Id information from the
10559      * managed profile will be shown in the parent profile, for incoming calls.
10560      * <p>
10561      * The calling device admin must be a profile owner. If it is not, a security exception will be
10562      * thrown.
10563      * <p>
10564      * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, calling this function
10565      * is similar to calling {@link #setManagedProfileCallerIdAccessPolicy(PackagePolicy)}
10566      * with a {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST} policy type when {@code disabled} is
10567      * false or a {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST} policy type when
10568      * {@code disabled} is true.
10569      *
10570      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10571      * @param disabled If true caller-Id information in the managed profile is not displayed.
10572      * @throws SecurityException if {@code admin} is not a profile owner.
10573      * @deprecated starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, use
10574      * {@link #setManagedProfileCallerIdAccessPolicy(PackagePolicy)} instead
10575      */
10576     @Deprecated
setCrossProfileCallerIdDisabled(@onNull ComponentName admin, boolean disabled)10577     public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
10578         throwIfParentInstance("setCrossProfileCallerIdDisabled");
10579         if (mService != null) {
10580             try {
10581                 mService.setCrossProfileCallerIdDisabled(admin, disabled);
10582             } catch (RemoteException e) {
10583                 throw e.rethrowFromSystemServer();
10584             }
10585         }
10586     }
10587 
10588     /**
10589      * Called by a profile owner of a managed profile to determine whether or not caller-Id
10590      * information has been disabled.
10591      * <p>
10592      * The calling device admin must be a profile owner. If it is not, a security exception will be
10593      * thrown.
10594      * <p>
10595      * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE},
10596      * this will return true when
10597      * {@link #setManagedProfileCallerIdAccessPolicy(PackagePolicy)}
10598      * has been set with a non-null policy whose policy type is NOT
10599      * {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST}
10600      *
10601      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10602      * @throws SecurityException if {@code admin} is not a profile owner.
10603      * @deprecated starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, use
10604      * {@link #getManagedProfileCallerIdAccessPolicy()} instead
10605      */
10606     @Deprecated
getCrossProfileCallerIdDisabled(@onNull ComponentName admin)10607     public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
10608         throwIfParentInstance("getCrossProfileCallerIdDisabled");
10609         if (mService != null) {
10610             try {
10611                 return mService.getCrossProfileCallerIdDisabled(admin);
10612             } catch (RemoteException e) {
10613                 throw e.rethrowFromSystemServer();
10614             }
10615         }
10616         return false;
10617     }
10618 
10619     /**
10620      * Called by the system to determine whether or not caller-Id information has been disabled.
10621      * <p>
10622      * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE},
10623      * this will return true when
10624      * {@link #setManagedProfileCallerIdAccessPolicy(PackagePolicy)}
10625      * has been set with a non-null policy whose policy type is NOT
10626      * {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST}
10627      *
10628      * @param userHandle The user for whom to check the caller-id permission
10629      * @deprecated use {@link #hasManagedProfileCallerIdAccess(UserHandle, String)} and provide the
10630      * package name requesting access
10631      * @hide
10632      */
10633     @Deprecated
getCrossProfileCallerIdDisabled(UserHandle userHandle)10634     public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
10635         if (mService != null) {
10636             try {
10637                 return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
10638             } catch (RemoteException e) {
10639                 throw e.rethrowFromSystemServer();
10640             }
10641         }
10642         return false;
10643     }
10644 
10645     /**
10646      * Called by a device owner or profile owner of a managed profile to set the credential manager
10647      * policy.
10648      *
10649      * <p>Affects APIs exposed by {@link android.credentials.CredentialManager}.
10650      *
10651      * <p>A {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST} policy type will limit the credential
10652      * providers that the user can use to the list of packages in the policy.
10653      *
10654      * <p>A {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST_AND_SYSTEM} policy type
10655      * allows access from the OEM default credential providers and the allowlist of credential
10656      * providers.
10657      *
10658      * <p>A {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST} policy type will block the credential
10659      * providers listed in the policy from being used by the user.
10660      *
10661      * @param policy the policy to set, setting this value to {@code null} will allow all packages
10662      * @throws SecurityException if caller is not a device owner or profile owner of a
10663      * managed profile
10664      */
setCredentialManagerPolicy(@ullable PackagePolicy policy)10665     public void setCredentialManagerPolicy(@Nullable PackagePolicy policy) {
10666         throwIfParentInstance("setCredentialManagerPolicy");
10667         if (mService != null) {
10668             try {
10669                 mService.setCredentialManagerPolicy(policy);
10670             } catch (RemoteException e) {
10671                 throw e.rethrowFromSystemServer();
10672             }
10673         }
10674     }
10675 
10676     /**
10677      * Called by a device owner or profile owner of a managed profile to retrieve the credential
10678      * manager policy.
10679      *
10680      * @throws SecurityException if caller is not a device owner or profile owner of a
10681      * managed profile.
10682      * @return the current credential manager policy if null then this policy has not been
10683      * configured.
10684      */
10685     @UserHandleAware(
10686             enabledSinceTargetSdkVersion = UPSIDE_DOWN_CAKE,
10687             requiresPermissionIfNotCaller = INTERACT_ACROSS_USERS)
getCredentialManagerPolicy()10688     public @Nullable PackagePolicy getCredentialManagerPolicy() {
10689         throwIfParentInstance("getCredentialManagerPolicy");
10690         if (mService != null) {
10691             try {
10692                 return mService.getCredentialManagerPolicy(myUserId());
10693             } catch (RemoteException e) {
10694                 throw e.rethrowFromSystemServer();
10695             }
10696         }
10697         return null;
10698     }
10699 
10700     /**
10701      * Called by a profile owner of a managed profile to set the packages that are allowed to
10702      * lookup contacts in the managed profile based on caller id information.
10703      * <p>
10704      * For example, the policy determines if a dialer app in the parent profile resolving
10705      * an incoming call can search the caller id data, such as phone number,
10706      * of managed contacts and return managed contacts that match.
10707      * <p>
10708      * The calling device admin must be a profile owner of a managed profile.
10709      * If it is not, a {@link SecurityException} will be thrown.
10710      * <p>
10711      * A {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST_AND_SYSTEM} policy type
10712      * allows access from the OEM default packages for the Sms, Dialer and Contact roles,
10713      * in addition to the packages specified in {@link PackagePolicy#getPackageNames()}
10714      *
10715      * @param policy the policy to set, setting this value to {@code null} will allow
10716      *               all packages
10717      * @throws SecurityException if caller is not a profile owner of a managed profile
10718      */
setManagedProfileCallerIdAccessPolicy(@ullable PackagePolicy policy)10719     public void setManagedProfileCallerIdAccessPolicy(@Nullable PackagePolicy policy) {
10720         throwIfParentInstance("setManagedProfileCallerIdAccessPolicy");
10721         if (mService != null) {
10722             try {
10723                 mService.setManagedProfileCallerIdAccessPolicy(policy);
10724             } catch (RemoteException e) {
10725                 throw e.rethrowFromSystemServer();
10726             }
10727         }
10728     }
10729 
10730     /**
10731      * Called by a profile owner of a managed profile to retrieve the caller id policy.
10732      * <p>
10733      * The calling device admin must be a profile owner of a managed profile.
10734      * If it is not, a {@link SecurityException} will be thrown.
10735      *
10736      * @throws SecurityException if caller is not a profile owner of a managed profile.
10737      * @return the current caller id policy
10738      */
getManagedProfileCallerIdAccessPolicy()10739     public @Nullable PackagePolicy getManagedProfileCallerIdAccessPolicy() {
10740         throwIfParentInstance("getManagedProfileCallerIdAccessPolicy");
10741         if (mService != null) {
10742             try {
10743                 return mService.getManagedProfileCallerIdAccessPolicy();
10744             } catch (RemoteException e) {
10745                 throw e.rethrowFromSystemServer();
10746             }
10747         }
10748         return null;
10749     }
10750 
10751     /**
10752      * Determine whether the given package is allowed to query the requested user to
10753      * populate caller id information
10754      *
10755      * @param userHandle The user for whom to check the contacts search permission
10756      * @param packageName the name of the package requesting access
10757      * @return true if package should be granted access, false otherwise
10758      * @hide
10759      */
10760     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
hasManagedProfileCallerIdAccess(@onNull UserHandle userHandle, @NonNull String packageName)10761     public boolean hasManagedProfileCallerIdAccess(@NonNull UserHandle userHandle,
10762             @NonNull String packageName) {
10763         if (mService == null) {
10764             return true;
10765         }
10766         try {
10767             return mService.hasManagedProfileCallerIdAccess(userHandle.getIdentifier(),
10768                     packageName);
10769         } catch (RemoteException e) {
10770             throw e.rethrowFromSystemServer();
10771         }
10772     }
10773 
10774     /**
10775      * Called by a profile owner of a managed profile to set the packages that are allowed
10776      * access to the managed profile contacts from the parent user.
10777      * <p>
10778      * For example, the system will enforce the provided policy and determine
10779      * if contacts in the managed profile are shown when queried by an application
10780      * in the parent user.
10781      * <p>
10782      * The calling device admin must be a profile owner of a managed profile.
10783      * If it is not, a {@link SecurityException} will be thrown.
10784      * <p>
10785      * A {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST_AND_SYSTEM} policy type
10786      * allows access from the OEM default packages for the Sms, Dialer and Contact roles,
10787      * in addition to the packages specified in {@link PackagePolicy#getPackageNames()}
10788      *
10789      * @param policy the policy to set, setting this value to {@code null} will allow
10790      *               all packages
10791      * @throws SecurityException if caller is not a profile owner of a managed profile
10792      */
setManagedProfileContactsAccessPolicy(@ullable PackagePolicy policy)10793     public void setManagedProfileContactsAccessPolicy(@Nullable PackagePolicy policy) {
10794         throwIfParentInstance("setManagedProfileContactsAccessPolicy");
10795         if (mService != null) {
10796             try {
10797                 mService.setManagedProfileContactsAccessPolicy(policy);
10798             } catch (RemoteException e) {
10799                 throw e.rethrowFromSystemServer();
10800             }
10801         }
10802     }
10803 
10804     /**
10805      * Called by a profile owner of a managed profile to determine the current policy applied
10806      * to managed profile contacts.
10807      * <p>
10808      * The calling device admin must be a profile owner of a managed profile.
10809      * If it is not, a {@link SecurityException} will be thrown.
10810      *
10811      * @throws SecurityException if caller is not a profile owner of a managed profile.
10812      * @return the current contacts search policy
10813      */
getManagedProfileContactsAccessPolicy()10814     public @Nullable PackagePolicy getManagedProfileContactsAccessPolicy() {
10815         throwIfParentInstance("getManagedProfileContactsAccessPolicy");
10816         if (mService == null) {
10817             return null;
10818         }
10819         try {
10820             return mService.getManagedProfileContactsAccessPolicy();
10821         } catch (RemoteException e) {
10822             throw e.rethrowFromSystemServer();
10823         }
10824     }
10825 
10826     /**
10827      * Determine whether requesting package has ability to access contacts of the requested user
10828      *
10829      * @param userHandle The user for whom to check the contacts search permission
10830      * @param packageName packageName requesting access to contact search
10831      * @return true when package is allowed access, false otherwise
10832      * @hide
10833      */
10834     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
hasManagedProfileContactsAccess(@onNull UserHandle userHandle, @NonNull String packageName)10835     public boolean hasManagedProfileContactsAccess(@NonNull UserHandle userHandle,
10836             @NonNull String packageName) {
10837         if (mService != null) {
10838             try {
10839                 return mService.hasManagedProfileContactsAccess(userHandle.getIdentifier(),
10840                         packageName);
10841             } catch (RemoteException e) {
10842                 throw e.rethrowFromSystemServer();
10843             }
10844         }
10845         return false;
10846     }
10847 
10848     /**
10849      * Called by a profile owner of a managed profile to set whether contacts search from the
10850      * managed profile will be shown in the parent profile, for incoming calls.
10851      * <p>
10852      * The calling device admin must be a profile owner. If it is not, a security exception will be
10853      * thrown.
10854      *
10855      * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, calling this function
10856      * is similar to calling {@link #setManagedProfileContactsAccessPolicy(PackagePolicy)} with a
10857      * {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST} policy type when {@code disabled} is false
10858      * or a {@link PackagePolicy#PACKAGE_POLICY_ALLOWLIST} policy type when {@code disabled}
10859      * is true.
10860      *
10861      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10862      * @param disabled If true contacts search in the managed profile is not displayed.
10863      * @throws SecurityException if {@code admin} is not a profile owner.
10864      *
10865      * @deprecated From {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} use
10866      * {@link #setManagedProfileContactsAccessPolicy(PackagePolicy)}
10867      */
10868     @Deprecated
setCrossProfileContactsSearchDisabled(@onNull ComponentName admin, boolean disabled)10869     public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
10870             boolean disabled) {
10871         throwIfParentInstance("setCrossProfileContactsSearchDisabled");
10872         if (mService != null) {
10873             try {
10874                 mService.setCrossProfileContactsSearchDisabled(admin, disabled);
10875             } catch (RemoteException e) {
10876                 throw e.rethrowFromSystemServer();
10877             }
10878         }
10879     }
10880 
10881     /**
10882      * Called by a profile owner of a managed profile to determine whether or not contacts search
10883      * has been disabled.
10884      * <p>
10885      * The calling device admin must be a profile owner. If it is not, a security exception will be
10886      * thrown.
10887      * <p>
10888      * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE},
10889      * this will return true when
10890      * {@link #setManagedProfileContactsAccessPolicy(PackagePolicy)}
10891      * has been set with a non-null policy whose policy type is NOT
10892      * {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST}
10893      *
10894      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10895      * @throws SecurityException if {@code admin} is not a profile owner.
10896      * @deprecated From {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} use
10897      * {@link #getManagedProfileContactsAccessPolicy()}
10898      */
10899     @Deprecated
getCrossProfileContactsSearchDisabled(@onNull ComponentName admin)10900     public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
10901         throwIfParentInstance("getCrossProfileContactsSearchDisabled");
10902         if (mService != null) {
10903             try {
10904                 return mService.getCrossProfileContactsSearchDisabled(admin);
10905             } catch (RemoteException e) {
10906                 throw e.rethrowFromSystemServer();
10907             }
10908         }
10909         return false;
10910     }
10911 
10912     /**
10913      * Determine whether or not contacts search has been disabled.
10914      * <p>
10915      * Starting with {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE},
10916      * this will return true when
10917      * {@link #setManagedProfileContactsAccessPolicy(PackagePolicy)}
10918      * has been set with a non-null policy whose policy type is NOT
10919      * {@link PackagePolicy#PACKAGE_POLICY_BLOCKLIST}
10920      * @param userHandle The user for whom to check the contacts search permission
10921      * @deprecated use {@link #hasManagedProfileContactsAccess(UserHandle, String)} and provide the
10922      * package name requesting access
10923      * @hide
10924      */
10925     @Deprecated
getCrossProfileContactsSearchDisabled(@onNull UserHandle userHandle)10926     public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
10927         if (mService != null) {
10928             try {
10929                 return mService
10930                         .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
10931             } catch (RemoteException e) {
10932                 throw e.rethrowFromSystemServer();
10933             }
10934         }
10935         return false;
10936     }
10937 
10938     /**
10939      * Start Quick Contact on the managed profile for the user, if the policy allows.
10940      *
10941      * @hide
10942      */
startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long directoryId, Intent originalIntent)10943     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
10944             boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
10945         if (mService != null) {
10946             try {
10947                 mService.startManagedQuickContact(actualLookupKey, actualContactId,
10948                         isContactIdIgnored, directoryId, originalIntent);
10949             } catch (RemoteException e) {
10950                 throw e.rethrowFromSystemServer();
10951             }
10952         }
10953     }
10954 
10955     /**
10956      * Start Quick Contact on the managed profile for the user, if the policy allows.
10957      * @hide
10958      */
startManagedQuickContact(String actualLookupKey, long actualContactId, Intent originalIntent)10959     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
10960             Intent originalIntent) {
10961         startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
10962                 originalIntent);
10963     }
10964 
10965     /**
10966      * Called by a profile owner of a managed profile to set whether bluetooth devices can access
10967      * enterprise contacts.
10968      * <p>
10969      * The calling device admin must be a profile owner. If it is not, a security exception will be
10970      * thrown.
10971      * <p>
10972      * This API works on managed profile only.
10973      *
10974      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10975      * @param disabled If true, bluetooth devices cannot access enterprise contacts.
10976      * @throws SecurityException if {@code admin} is not a profile owner.
10977      */
setBluetoothContactSharingDisabled(@onNull ComponentName admin, boolean disabled)10978     public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
10979         throwIfParentInstance("setBluetoothContactSharingDisabled");
10980         if (mService != null) {
10981             try {
10982                 mService.setBluetoothContactSharingDisabled(admin, disabled);
10983             } catch (RemoteException e) {
10984                 throw e.rethrowFromSystemServer();
10985             }
10986         }
10987     }
10988 
10989     /**
10990      * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
10991      * cannot access enterprise contacts.
10992      * <p>
10993      * The calling device admin must be a profile owner. If it is not, a security exception will be
10994      * thrown.
10995      * <p>
10996      * This API works on managed profile only.
10997      *
10998      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10999      * @throws SecurityException if {@code admin} is not a profile owner.
11000      */
getBluetoothContactSharingDisabled(@onNull ComponentName admin)11001     public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
11002         throwIfParentInstance("getBluetoothContactSharingDisabled");
11003         if (mService != null) {
11004             try {
11005                 return mService.getBluetoothContactSharingDisabled(admin);
11006             } catch (RemoteException e) {
11007                 throw e.rethrowFromSystemServer();
11008             }
11009         }
11010         return true;
11011     }
11012 
11013     /**
11014      * Determine whether or not Bluetooth devices cannot access contacts.
11015      * <p>
11016      * This API works on managed profile UserHandle only.
11017      *
11018      * @param userHandle The user for whom to check the caller-id permission
11019      * @hide
11020      */
11021     @SystemApi
11022     @RequiresPermission(permission.INTERACT_ACROSS_USERS)
getBluetoothContactSharingDisabled(@onNull UserHandle userHandle)11023     public boolean getBluetoothContactSharingDisabled(@NonNull UserHandle userHandle) {
11024         if (mService != null) {
11025             try {
11026                 return mService.getBluetoothContactSharingDisabledForUser(userHandle
11027                         .getIdentifier());
11028             } catch (RemoteException e) {
11029                 throw e.rethrowFromSystemServer();
11030             }
11031         }
11032         return true;
11033     }
11034 
11035     /**
11036      * Called by the profile owner of a managed profile so that some intents sent in the managed
11037      * profile can also be resolved in the parent, or vice versa. Only activity intents are
11038      * supported.
11039      *
11040      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11041      * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
11042      *            other profile
11043      * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
11044      *            {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
11045      * @throws SecurityException if {@code admin} is not a device or profile owner.
11046      */
11047     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PROFILE_INTERACTION, conditional = true)
addCrossProfileIntentFilter(@ullable ComponentName admin, IntentFilter filter, int flags)11048     public void addCrossProfileIntentFilter(@Nullable ComponentName admin, IntentFilter filter,
11049             int flags) {
11050         throwIfParentInstance("addCrossProfileIntentFilter");
11051         if (mService != null) {
11052             try {
11053                 mService.addCrossProfileIntentFilter(admin, mContext.getPackageName(), filter,
11054                         flags);
11055             } catch (RemoteException e) {
11056                 throw e.rethrowFromSystemServer();
11057             }
11058         }
11059     }
11060 
11061     /**
11062      * Called by a profile owner of a managed profile to remove the cross-profile intent filters
11063      * that go from the managed profile to the parent, or from the parent to the managed profile.
11064      * Only removes those that have been set by the profile owner.
11065      * <p>
11066      * <em>Note</em>: A list of default cross profile intent filters are set up by the system when
11067      * the profile is created, some of them ensure the proper functioning of the profile, while
11068      * others enable sharing of data from the parent to the managed profile for user convenience.
11069      * These default intent filters are not cleared when this API is called. If the default cross
11070      * profile data sharing is not desired, they can be disabled with
11071      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE}.
11072      *
11073      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11074      * @throws SecurityException if {@code admin} is not a profile owner.
11075      */
11076     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PROFILE_INTERACTION, conditional = true)
clearCrossProfileIntentFilters(@ullable ComponentName admin)11077     public void clearCrossProfileIntentFilters(@Nullable ComponentName admin) {
11078         throwIfParentInstance("clearCrossProfileIntentFilters");
11079         if (mService != null) {
11080             try {
11081                 mService.clearCrossProfileIntentFilters(admin, mContext.getPackageName());
11082             } catch (RemoteException e) {
11083                 throw e.rethrowFromSystemServer();
11084             }
11085         }
11086     }
11087 
11088     /**
11089      * Called by a profile or device owner to set the permitted
11090      * {@link android.accessibilityservice.AccessibilityService}. When set by
11091      * a device owner or profile owner the restriction applies to all profiles of the user the
11092      * device owner or profile owner is an admin for. By default, the user can use any accessibility
11093      * service. When zero or more packages have been added, accessibility services that are not in
11094      * the list and not part of the system can not be enabled by the user.
11095      * <p>
11096      * Calling with a {@code null} value for the list disables the restriction so that all services
11097      * can be used, calling with an empty list only allows the built-in system services. Any
11098      * non-system accessibility service that's currently enabled must be included in the list.
11099      * <p>
11100      * System accessibility services are always available to the user and this method can't
11101      * disable them.
11102      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11103      * @param packageNames List of accessibility service package names.
11104      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
11105      *         contain every enabled non-system accessibility service.
11106      * @throws SecurityException if {@code admin} is not a device or profile owner.
11107      */
setPermittedAccessibilityServices(@onNull ComponentName admin, List<String> packageNames)11108     public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
11109             List<String> packageNames) {
11110         throwIfParentInstance("setPermittedAccessibilityServices");
11111         if (mService != null) {
11112             try {
11113                 return mService.setPermittedAccessibilityServices(admin, packageNames);
11114             } catch (RemoteException e) {
11115                 throw e.rethrowFromSystemServer();
11116             }
11117         }
11118         return false;
11119     }
11120 
11121     /**
11122      * Returns the list of permitted accessibility services set by this device or profile owner.
11123      * <p>
11124      * An empty list means no accessibility services except system services are allowed.
11125      * {@code null} means all accessibility services are allowed.
11126      *
11127      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11128      * @return List of accessiblity service package names.
11129      * @throws SecurityException if {@code admin} is not a device or profile owner.
11130      */
getPermittedAccessibilityServices(@onNull ComponentName admin)11131     public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
11132         throwIfParentInstance("getPermittedAccessibilityServices");
11133         if (mService != null) {
11134             try {
11135                 return mService.getPermittedAccessibilityServices(admin);
11136             } catch (RemoteException e) {
11137                 throw e.rethrowFromSystemServer();
11138             }
11139         }
11140         return null;
11141     }
11142 
11143     /**
11144      * Called by the system to check if a specific accessibility service is disabled by admin.
11145      *
11146      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11147      * @param packageName Accessibility service package name that needs to be checked.
11148      * @param userHandle user id the admin is running as.
11149      * @return true if the accessibility service is permitted, otherwise false.
11150      *
11151      * @hide
11152      */
isAccessibilityServicePermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)11153     public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
11154             @NonNull String packageName, int userHandle) {
11155         if (mService != null) {
11156             try {
11157                 return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
11158                         userHandle);
11159             } catch (RemoteException e) {
11160                 throw e.rethrowFromSystemServer();
11161             }
11162         }
11163         return false;
11164     }
11165 
11166     /**
11167      * Returns the list of accessibility services permitted by the device or profiles
11168      * owners of this user.
11169      *
11170      * <p>{@code null} means all accessibility services are allowed, if a non-null list is returned
11171      * it will contain the intersection of the permitted lists for any device or profile
11172      * owners that apply to this user. It will also include any system accessibility services.
11173      *
11174      * @param userId which user to check for.
11175      * @return List of accessiblity service package names.
11176      * @hide
11177      */
11178      @SystemApi
11179      @RequiresPermission(anyOf = {
11180              android.Manifest.permission.MANAGE_USERS,
11181              android.Manifest.permission.QUERY_ADMIN_POLICY})
getPermittedAccessibilityServices(int userId)11182      public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
11183         throwIfParentInstance("getPermittedAccessibilityServices");
11184         if (mService != null) {
11185             try {
11186                 return mService.getPermittedAccessibilityServicesForUser(userId);
11187             } catch (RemoteException e) {
11188                 throw e.rethrowFromSystemServer();
11189             }
11190         }
11191         return null;
11192      }
11193 
11194     /**
11195      * Called by a profile or device owner or holder of the
11196      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_INPUT_METHODS} permission to set
11197      * the permitted input methods services for this user. By default, the user can use any input
11198      * method.
11199      * <p>
11200      * This method can be called on the {@link DevicePolicyManager} instance,
11201      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
11202      * a profile owner of an organization-owned device.
11203      * <p>
11204      * If called on the parent instance:
11205      * <ul>
11206      *    <li>The permitted input methods will be applied on the personal profile</li>
11207      *    <li>Can only permit all input methods (calling this method with a {@code null} package
11208      *    list) or only permit system input methods (calling this method with an empty package
11209      *    list). This is to prevent the caller from learning which packages are installed on
11210      *    the personal side</li>
11211      * </ul>
11212      * <p>
11213      * When zero or more packages have been added, input method that are not in the list and not
11214      * part of the system can not be enabled by the user. This method will fail if it is called for
11215      * a admin that is not for the foreground user or a profile of the foreground user. Any
11216      * non-system input method service that's currently enabled must be included in the list.
11217      * <p>
11218      * Calling with a null value for the list disables the restriction so that all input methods can
11219      * be used, calling with an empty list disables all but the system's own input methods.
11220      * <p>
11221      * System input methods are always available to the user - this method can't modify this.
11222      *
11223      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
11224      *              caller is not a device admin
11225      * @param packageNames List of input method package names.
11226      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
11227      *        contain every enabled non-system input method service.
11228      * @throws SecurityException if {@code admin} is not a device or profile owner and does not
11229      *                              hold the {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_INPUT_METHODS}
11230      *                              permission, or if called on the parent profile and the
11231      *                              {@code admin} is not a profile owner of an organization-owned
11232      *                              managed profile.
11233      * @throws IllegalArgumentException if called on the parent profile, the {@code admin} is a
11234      *                           profile owner of an organization-owned managed profile and the
11235      *                           list of permitted input method package names is not null or empty.
11236      */
11237     @SupportsCoexistence
11238     @RequiresPermission(value = MANAGE_DEVICE_POLICY_INPUT_METHODS, conditional = true)
setPermittedInputMethods( @ullable ComponentName admin, List<String> packageNames)11239     public boolean setPermittedInputMethods(
11240             @Nullable ComponentName admin, List<String> packageNames) {
11241         if (mService != null) {
11242             try {
11243                 return mService.setPermittedInputMethods(
11244                         admin, mContext.getPackageName(), packageNames, mParentInstance);
11245             } catch (RemoteException e) {
11246                 throw e.rethrowFromSystemServer();
11247             }
11248         }
11249         return false;
11250     }
11251 
11252 
11253     /**
11254      * Returns the list of permitted input methods set by this device or profile owner.
11255      * <p>
11256      * This method can be called on the {@link DevicePolicyManager} instance,
11257      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
11258      * a profile owner of an organization-owned managed profile. If called on the parent instance,
11259      * then the returned list of permitted input methods are those which are applied on the
11260      * personal profile.
11261      * <p>
11262      * An empty list means no input methods except system input methods are allowed. Null means all
11263      * input methods are allowed.
11264      *
11265      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
11266      *              caller is not a device admin
11267      * @return List of input method package names.
11268      * @throws SecurityException if {@code admin} is not a device, profile owner or if called on
11269      *                           the parent profile and the {@code admin} is not a profile owner
11270      *                           of an organization-owned managed profile.
11271      */
11272     @RequiresPermission(value = MANAGE_DEVICE_POLICY_INPUT_METHODS, conditional = true)
getPermittedInputMethods(@ullable ComponentName admin)11273     public @Nullable List<String> getPermittedInputMethods(@Nullable ComponentName admin) {
11274         if (mService != null) {
11275             try {
11276                 return mService.getPermittedInputMethods(admin, mContext.getPackageName(), mParentInstance);
11277             } catch (RemoteException e) {
11278                 throw e.rethrowFromSystemServer();
11279             }
11280         }
11281         return null;
11282     }
11283 
11284     /**
11285      * Called by the system to check if a specific input method is disabled by admin.
11286      * <p>
11287      * This method can be called on the {@link DevicePolicyManager} instance,
11288      * returned by {@link #getParentProfileInstance(ComponentName)}. If called on the parent
11289      * instance, this method will check whether the given input method is permitted on
11290      * the personal profile.
11291      *
11292      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11293      * @param packageName Input method package name that needs to be checked.
11294      * @param userHandle user id the admin is running as.
11295      * @return true if the input method is permitted, otherwise false.
11296      *
11297      * @hide
11298      */
isInputMethodPermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)11299     public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
11300             @NonNull String packageName, int userHandle) {
11301         if (mService != null) {
11302             try {
11303                 return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle,
11304                         mParentInstance);
11305             } catch (RemoteException e) {
11306                 throw e.rethrowFromSystemServer();
11307             }
11308         }
11309         return false;
11310     }
11311 
11312     /**
11313      * Returns the list of input methods permitted by the device or profiles owners.
11314      *
11315      * <p>On {@link android.os.Build.VERSION_CODES#Q} and later devices, this method returns the
11316      * result for the calling user.</p>
11317      *
11318      * <p>On Android P and prior devices, this method returns the result for the current user.</p>
11319      *
11320      * <p>Null means all input methods are allowed, if a non-null list is returned
11321      * it will contain the intersection of the permitted lists for any device or profile
11322      * owners that apply to this user. It will also include any system input methods.
11323      *
11324      * @return List of input method package names.
11325      * @hide
11326      *
11327      * @see #setPermittedAccessibilityServices(ComponentName, List)
11328      */
11329     @SystemApi
11330     @RequiresPermission(anyOf = {
11331             android.Manifest.permission.MANAGE_USERS,
11332             android.Manifest.permission.QUERY_ADMIN_POLICY})
getPermittedInputMethodsForCurrentUser()11333     public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
11334         throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
11335         if (mService != null) {
11336             try {
11337                 return mService.getPermittedInputMethodsAsUser(UserHandle.myUserId());
11338             } catch (RemoteException e) {
11339                 throw e.rethrowFromSystemServer();
11340             }
11341         }
11342         return null;
11343     }
11344 
11345     /**
11346      * Returns the list of input methods permitted.
11347      *
11348      * <p>{@code null} means all input methods are allowed, if a non-null list is returned
11349      * it will contain the intersection of the permitted lists for any device or profile
11350      * owners that apply to this user. It will also include any system input methods.
11351      *
11352      * @return List of input method package names.
11353      * @hide
11354      *
11355      * @see #setPermittedAccessibilityServices(ComponentName, List)
11356      */
11357     @UserHandleAware
11358     @RequiresPermission(allOf = {
11359             INTERACT_ACROSS_USERS_FULL,
11360             android.Manifest.permission.MANAGE_USERS
11361             }, conditional = true)
getPermittedInputMethods()11362     public @Nullable List<String> getPermittedInputMethods() {
11363         throwIfParentInstance("getPermittedInputMethods");
11364         if (mService != null) {
11365             try {
11366                 return mService.getPermittedInputMethodsAsUser(myUserId());
11367             } catch (RemoteException e) {
11368                 throw e.rethrowFromSystemServer();
11369             }
11370         }
11371         return null;
11372     }
11373 
11374     /**
11375      * Called by a profile owner of a managed profile to set the packages that are allowed to use
11376      * a {@link android.service.notification.NotificationListenerService} in the primary user to
11377      * see notifications from the managed profile. By default all packages are permitted by this
11378      * policy. When zero or more packages have been added, notification listeners installed on the
11379      * primary user that are not in the list and are not part of the system won't receive events
11380      * for managed profile notifications.
11381      * <p>
11382      * Calling with a {@code null} value for the list disables the restriction so that all
11383      * notification listener services be used. Calling with an empty list disables all but the
11384      * system's own notification listeners. System notification listener services are always
11385      * available to the user.
11386      * <p>
11387      * If a device or profile owner want to stop notification listeners in their user from seeing
11388      * that user's notifications they should prevent that service from running instead (e.g. via
11389      * {@link #setApplicationHidden(ComponentName, String, boolean)})
11390      *
11391      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11392      * @param packageList List of package names to allowlist
11393      * @return true if setting the restriction succeeded. It will fail if called outside a managed
11394      * profile
11395      * @throws SecurityException if {@code admin} is not a profile owner.
11396      *
11397      * @see android.service.notification.NotificationListenerService
11398      */
setPermittedCrossProfileNotificationListeners( @onNull ComponentName admin, @Nullable List<String> packageList)11399     public boolean setPermittedCrossProfileNotificationListeners(
11400             @NonNull ComponentName admin, @Nullable List<String> packageList) {
11401         throwIfParentInstance("setPermittedCrossProfileNotificationListeners");
11402         if (mService != null) {
11403             try {
11404                 return mService.setPermittedCrossProfileNotificationListeners(admin, packageList);
11405             } catch (RemoteException e) {
11406                 throw e.rethrowFromSystemServer();
11407             }
11408         }
11409         return false;
11410     }
11411 
11412     /**
11413      * Returns the list of packages installed on the primary user that allowed to use a
11414      * {@link android.service.notification.NotificationListenerService} to receive
11415      * notifications from this managed profile, as set by the profile owner.
11416      * <p>
11417      * An empty list means no notification listener services except system ones are allowed.
11418      * A {@code null} return value indicates that all notification listeners are allowed.
11419      */
getPermittedCrossProfileNotificationListeners( @onNull ComponentName admin)11420     public @Nullable List<String> getPermittedCrossProfileNotificationListeners(
11421             @NonNull ComponentName admin) {
11422         throwIfParentInstance("getPermittedCrossProfileNotificationListeners");
11423         if (mService != null) {
11424             try {
11425                 return mService.getPermittedCrossProfileNotificationListeners(admin);
11426             } catch (RemoteException e) {
11427                 throw e.rethrowFromSystemServer();
11428             }
11429         }
11430         return null;
11431     }
11432 
11433     /**
11434      * Returns true if {@code NotificationListenerServices} from the given package are allowed to
11435      * receive events for notifications from the given user id. Can only be called by the system uid
11436      *
11437      * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List)
11438      *
11439      * @hide
11440      */
isNotificationListenerServicePermitted( @onNull String packageName, @UserIdInt int userId)11441     public boolean isNotificationListenerServicePermitted(
11442             @NonNull String packageName, @UserIdInt int userId) {
11443         if (mService != null) {
11444             try {
11445                 return mService.isNotificationListenerServicePermitted(packageName, userId);
11446             } catch (RemoteException e) {
11447                 throw e.rethrowFromSystemServer();
11448             }
11449         }
11450         return true;
11451     }
11452 
11453     /**
11454      * Get the list of apps to keep around as APKs even if no user has currently installed it. This
11455      * function can be called by a device owner or by a delegate given the
11456      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
11457      * <p>
11458      * Please note that packages returned in this method are not automatically pre-cached.
11459      *
11460      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
11461      *            {@code null} if the caller is a keep uninstalled packages delegate.
11462      * @return List of package names to keep cached.
11463      * @see #setDelegatedScopes
11464      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
11465      */
getKeepUninstalledPackages(@ullable ComponentName admin)11466     public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) {
11467         throwIfParentInstance("getKeepUninstalledPackages");
11468         if (mService != null) {
11469             try {
11470                 return mService.getKeepUninstalledPackages(admin, mContext.getPackageName());
11471             } catch (RemoteException e) {
11472                 throw e.rethrowFromSystemServer();
11473             }
11474         }
11475         return null;
11476     }
11477 
11478     /**
11479      * Set a list of apps to keep around as APKs even if no user has currently installed it. This
11480      * function can be called by a device owner or by a delegate given the
11481      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
11482      *
11483      * <p>Please note that setting this policy does not imply that specified apps will be
11484      * automatically pre-cached.</p>
11485      *
11486      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
11487      *            {@code null} if the caller is a keep uninstalled packages delegate.
11488      * @param packageNames List of package names to keep cached.
11489      * @throws SecurityException if {@code admin} is not a device owner.
11490      * @see #setDelegatedScopes
11491      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
11492      */
setKeepUninstalledPackages(@ullable ComponentName admin, @NonNull List<String> packageNames)11493     public void setKeepUninstalledPackages(@Nullable ComponentName admin,
11494             @NonNull List<String> packageNames) {
11495         throwIfParentInstance("setKeepUninstalledPackages");
11496         if (mService != null) {
11497             try {
11498                 mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames);
11499             } catch (RemoteException e) {
11500                 throw e.rethrowFromSystemServer();
11501             }
11502         }
11503     }
11504 
11505     /**
11506       * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
11507       */
11508     public static final int SKIP_SETUP_WIZARD = 0x0001;
11509 
11510     /**
11511      * Flag used by {@link #createAndManageUser} to specify that the user should be created
11512      * ephemeral. Ephemeral users will be removed after switching to another user or rebooting the
11513      * device.
11514      */
11515     public static final int MAKE_USER_EPHEMERAL = 0x0002;
11516 
11517     /**
11518      * Flag used by {@link #createAndManageUser} to specify that the user should be created as a
11519      * demo user.
11520      * @hide
11521      */
11522     public static final int MAKE_USER_DEMO = 0x0004;
11523 
11524     /**
11525      * Flag used by {@link #createAndManageUser} to specify that the newly created user should skip
11526      * the disabling of system apps during provisioning.
11527      */
11528     public static final int LEAVE_ALL_SYSTEM_APPS_ENABLED = 0x0010;
11529 
11530     /**
11531      * @hide
11532      */
11533     @IntDef(flag = true, prefix = { "SKIP_", "MAKE_USER_", "START_", "LEAVE_" }, value = {
11534             SKIP_SETUP_WIZARD,
11535             MAKE_USER_EPHEMERAL,
11536             MAKE_USER_DEMO,
11537             LEAVE_ALL_SYSTEM_APPS_ENABLED
11538     })
11539     @Retention(RetentionPolicy.SOURCE)
11540     public @interface CreateAndManageUserFlags {}
11541 
11542     /**
11543      * Called by a device owner to create a user with the specified name and a given component of
11544      * the calling package as profile owner. The UserHandle returned by this method should not be
11545      * persisted as user handles are recycled as users are removed and created. If you need to
11546      * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
11547      * user will not be started in the background.
11548      * <p>
11549      * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
11550      * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
11551      * be registered as an active admin on the new user. The profile owner package will be installed
11552      * on the new user.
11553      * <p>
11554      * If the adminExtras are not null, they will be stored on the device until the user is started
11555      * for the first time. Then the extras will be passed to the admin when onEnable is called.
11556      * <p>From {@link android.os.Build.VERSION_CODES#P} onwards, if targeting
11557      * {@link android.os.Build.VERSION_CODES#P}, throws {@link UserOperationException} instead of
11558      * returning {@code null} on failure.
11559      *
11560      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11561      * @param name The user's name.
11562      * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
11563      *            same package as admin, otherwise no user is created and an
11564      *            IllegalArgumentException is thrown.
11565      * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
11566      *            user.
11567      * @param flags {@link #SKIP_SETUP_WIZARD}, {@link #MAKE_USER_EPHEMERAL} and
11568      *        {@link #LEAVE_ALL_SYSTEM_APPS_ENABLED} are supported.
11569      * @see UserHandle
11570      * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
11571      *         user could not be created.
11572      * @throws SecurityException if headless device is in
11573      *        {@link DeviceAdminInfo#HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER} mode.
11574      * @throws SecurityException if {@code admin} is not a device owner
11575      * @throws UserOperationException if the user could not be created and the calling app is
11576      * targeting {@link android.os.Build.VERSION_CODES#P} and running on
11577      * {@link android.os.Build.VERSION_CODES#P}.
11578      */
createAndManageUser(@onNull ComponentName admin, @NonNull String name, @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras, @CreateAndManageUserFlags int flags)11579     public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
11580             @NonNull String name,
11581             @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
11582             @CreateAndManageUserFlags int flags) {
11583         throwIfParentInstance("createAndManageUser");
11584         try {
11585             return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
11586         } catch (ServiceSpecificException e) {
11587             throw new UserOperationException(e.getMessage(), e.errorCode);
11588         } catch (RemoteException re) {
11589             throw re.rethrowFromSystemServer();
11590         }
11591     }
11592 
11593     /**
11594      * Called by a device owner to remove a user/profile and all associated data. The primary user
11595      * can not be removed.
11596      *
11597      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11598      * @param userHandle the user to remove.
11599      * @return {@code true} if the user was removed, {@code false} otherwise.
11600      * @throws SecurityException if {@code admin} is not a device owner.
11601      */
removeUser(@onNull ComponentName admin, @NonNull UserHandle userHandle)11602     public boolean removeUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) {
11603         throwIfParentInstance("removeUser");
11604         try {
11605             return mService.removeUser(admin, userHandle);
11606         } catch (RemoteException re) {
11607             throw re.rethrowFromSystemServer();
11608         }
11609     }
11610 
11611     /**
11612      * Called by a device owner to switch the specified secondary user to the foreground.
11613      *
11614      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11615      * @param userHandle the user to switch to; null will switch to primary.
11616      * @return {@code true} if the switch was successful, {@code false} otherwise.
11617      * @throws SecurityException if {@code admin} is not a device owner.
11618      * @see Intent#ACTION_USER_FOREGROUND
11619      * @see #getSecondaryUsers(ComponentName)
11620      */
switchUser(@onNull ComponentName admin, @Nullable UserHandle userHandle)11621     public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
11622         throwIfParentInstance("switchUser");
11623         try {
11624             return mService.switchUser(admin, userHandle);
11625         } catch (RemoteException re) {
11626             throw re.rethrowFromSystemServer();
11627         }
11628     }
11629 
11630     /**
11631      * Called by a device owner to start the specified secondary user in background.
11632      *
11633      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11634      * @param userHandle the user to be started in background.
11635      * @return one of the following result codes:
11636      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
11637      * {@link UserManager#USER_OPERATION_SUCCESS},
11638      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
11639      * {@link UserManager#USER_OPERATION_ERROR_MAX_RUNNING_USERS},
11640      * @throws SecurityException if {@code admin} is not a device owner.
11641      * @see #getSecondaryUsers(ComponentName)
11642      */
startUserInBackground( @onNull ComponentName admin, @NonNull UserHandle userHandle)11643     public @UserOperationResult int startUserInBackground(
11644             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
11645         throwIfParentInstance("startUserInBackground");
11646         try {
11647             return mService.startUserInBackground(admin, userHandle);
11648         } catch (RemoteException re) {
11649             throw re.rethrowFromSystemServer();
11650         }
11651     }
11652 
11653     /**
11654      * Called by a device owner to stop the specified secondary user.
11655      *
11656      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11657      * @param userHandle the user to be stopped.
11658      * @return one of the following result codes:
11659      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
11660      * {@link UserManager#USER_OPERATION_SUCCESS},
11661      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
11662      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
11663      * @throws SecurityException if {@code admin} is not a device owner.
11664      * @see #getSecondaryUsers(ComponentName)
11665      */
stopUser( @onNull ComponentName admin, @NonNull UserHandle userHandle)11666     public @UserOperationResult int stopUser(
11667             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
11668         throwIfParentInstance("stopUser");
11669         try {
11670             return mService.stopUser(admin, userHandle);
11671         } catch (RemoteException re) {
11672             throw re.rethrowFromSystemServer();
11673         }
11674     }
11675 
11676     /**
11677      * Called by a profile owner of secondary user that is affiliated with the device to stop the
11678      * calling user and switch back to primary user (when the user was
11679      * {@link #switchUser(ComponentName, UserHandle)} switched to) or stop the user (when it was
11680      * {@link #startUserInBackground(ComponentName, UserHandle) started in background}.
11681      *
11682      * <p>Notice that on devices running with
11683      * {@link UserManager#isHeadlessSystemUserMode() headless system user mode}, there is no primary
11684      * user, so it switches back to the user that was in the foreground before the first call to
11685      * {@link #switchUser(ComponentName, UserHandle)} (or fails with
11686      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN} if that method was not called prior to this
11687      * call).
11688      *
11689      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11690      * @return one of the following result codes:
11691      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
11692      * {@link UserManager#USER_OPERATION_SUCCESS},
11693      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
11694      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
11695      * @throws SecurityException if {@code admin} is not a profile owner affiliated with the device.
11696      * @see #getSecondaryUsers(ComponentName)
11697      */
logoutUser(@onNull ComponentName admin)11698     public @UserOperationResult int logoutUser(@NonNull ComponentName admin) {
11699         throwIfParentInstance("logoutUser");
11700         try {
11701             return mService.logoutUser(admin);
11702         } catch (RemoteException re) {
11703             throw re.rethrowFromSystemServer();
11704         }
11705     }
11706 
11707     /**
11708      * Called by a profile owner of an organization-owned device to specify {@link
11709      * ManagedSubscriptionsPolicy}
11710      *
11711      * <p>Managed subscriptions policy controls how SIMs would be associated with the
11712      * managed profile. For example a policy of type
11713      * {@link ManagedSubscriptionsPolicy#TYPE_ALL_MANAGED_SUBSCRIPTIONS} assigns all
11714      * SIM-based subscriptions to the managed profile. In this case OEM default
11715      * dialer and messages app are automatically installed in the managed profile
11716      * and all incoming and outgoing calls and text messages are handled by them.
11717      * <p>This API can only be called during device setup.
11718      *
11719      * @param policy {@link ManagedSubscriptionsPolicy} policy, passing null for this resets the
11720      *               policy to be the default.
11721      * @throws SecurityException     if the caller is not a profile owner on an organization-owned
11722      *                               managed profile.
11723      * @throws IllegalStateException if called after the device setup has been completed.
11724      * @throws UnsupportedOperationException if managed subscriptions policy is not explicitly
11725      *         enabled by the device policy management role holder during device setup.
11726      * @see ManagedSubscriptionsPolicy
11727      */
setManagedSubscriptionsPolicy(@ullable ManagedSubscriptionsPolicy policy)11728     public void setManagedSubscriptionsPolicy(@Nullable ManagedSubscriptionsPolicy policy) {
11729         throwIfParentInstance("setManagedSubscriptionsPolicy");
11730         try {
11731             mService.setManagedSubscriptionsPolicy(policy);
11732         } catch (RemoteException re) {
11733             throw re.rethrowFromSystemServer();
11734         }
11735     }
11736 
11737     /**
11738      * Returns the current {@link ManagedSubscriptionsPolicy}.
11739      * If the policy has not been set, it will return a default policy of Type {@link
11740      * ManagedSubscriptionsPolicy#TYPE_ALL_PERSONAL_SUBSCRIPTIONS}.
11741      *
11742      * @see #setManagedSubscriptionsPolicy(ManagedSubscriptionsPolicy)
11743      */
11744     @NonNull
getManagedSubscriptionsPolicy()11745     public ManagedSubscriptionsPolicy getManagedSubscriptionsPolicy() {
11746         throwIfParentInstance("getManagedSubscriptionsPolicy");
11747         try {
11748             return mService.getManagedSubscriptionsPolicy();
11749         } catch (RemoteException re) {
11750             throw re.rethrowFromSystemServer();
11751         }
11752     }
11753 
11754     /**
11755      * Similar to {@link #logoutUser(ComponentName)}, except:
11756      *
11757      * <ul>
11758      *   <li>Called by system (like Settings), not admin.
11759      *   <li>It logs out the current user, not the caller.
11760      * </ul>
11761      *
11762      * @hide
11763      */
11764     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
11765             android.Manifest.permission.INTERACT_ACROSS_USERS})
11766     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
logoutUser()11767     public @UserOperationResult int logoutUser() {
11768         // TODO(b/214336184): add CTS test
11769         try {
11770             return mService.logoutUserInternal();
11771         } catch (RemoteException re) {
11772             throw re.rethrowFromSystemServer();
11773         }
11774     }
11775 
11776     /**
11777      * Gets the user a {@link #logoutUser(ComponentName)} call would switch to,
11778      * or {@code null} if the current user is not in a session (i.e., if it was not
11779      * {@link #switchUser(ComponentName, UserHandle) switched} or
11780      * {@link #startUserInBackground(ComponentName, UserHandle) started in background} by the
11781      * device admin.
11782      *
11783      * @hide
11784      */
11785     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
11786             android.Manifest.permission.INTERACT_ACROSS_USERS})
11787     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
getLogoutUser()11788     public @Nullable UserHandle getLogoutUser() {
11789         // TODO(b/214336184): add CTS test
11790         try {
11791             int userId = mService.getLogoutUserId();
11792             return userId == UserHandle.USER_NULL ? null : UserHandle.of(userId);
11793         } catch (RemoteException re) {
11794             throw re.rethrowFromSystemServer();
11795         }
11796     }
11797 
11798     /**
11799      * Called by a device owner to list all secondary users on the device. Managed profiles are not
11800      * considered as secondary users.
11801      * <p> Used for various user management APIs, including {@link #switchUser}, {@link #removeUser}
11802      * and {@link #stopUser}.
11803      *
11804      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11805      * @return list of other {@link UserHandle}s on the device.
11806      * @throws SecurityException if {@code admin} is not a device owner.
11807      * @see #removeUser(ComponentName, UserHandle)
11808      * @see #switchUser(ComponentName, UserHandle)
11809      * @see #startUserInBackground(ComponentName, UserHandle)
11810      * @see #stopUser(ComponentName, UserHandle)
11811      */
getSecondaryUsers(@onNull ComponentName admin)11812     public List<UserHandle> getSecondaryUsers(@NonNull ComponentName admin) {
11813         throwIfParentInstance("getSecondaryUsers");
11814         try {
11815             return mService.getSecondaryUsers(admin);
11816         } catch (RemoteException re) {
11817             throw re.rethrowFromSystemServer();
11818         }
11819     }
11820 
11821     /**
11822      * Checks if the profile owner is running in an ephemeral user.
11823      *
11824      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11825      * @return whether the profile owner is running in an ephemeral user.
11826      */
isEphemeralUser(@onNull ComponentName admin)11827     public boolean isEphemeralUser(@NonNull ComponentName admin) {
11828         throwIfParentInstance("isEphemeralUser");
11829         try {
11830             return mService.isEphemeralUser(admin);
11831         } catch (RemoteException re) {
11832             throw re.rethrowFromSystemServer();
11833         }
11834     }
11835 
11836     /**
11837      * Retrieves the application restrictions for a given target application running in the calling
11838      * user.
11839      * <p>
11840      * The caller must be a profile or device owner on that user, or the package allowed to manage
11841      * application restrictions via {@link #setDelegatedScopes} with the
11842      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
11843      *
11844      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
11845      *
11846      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
11847      *            {@code null} if called by the application restrictions managing package.
11848      * @param packageName The name of the package to fetch restricted settings of.
11849      * @return {@link Bundle} of settings corresponding to what was set last time
11850      *         {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
11851      *         {@link Bundle} if no restrictions have been set.
11852      * @throws SecurityException if {@code admin} is not a device or profile owner.
11853      * @see #setDelegatedScopes
11854      * @see #DELEGATION_APP_RESTRICTIONS
11855      */
11856     @WorkerThread
getApplicationRestrictions( @ullable ComponentName admin, String packageName)11857     public @NonNull Bundle getApplicationRestrictions(
11858             @Nullable ComponentName admin, String packageName) {
11859         if (!Flags.dmrhSetAppRestrictions()) {
11860             throwIfParentInstance("getApplicationRestrictions");
11861         }
11862 
11863         if (mService != null) {
11864             try {
11865                 return mService.getApplicationRestrictions(admin, mContext.getPackageName(),
11866                         packageName, mParentInstance);
11867             } catch (RemoteException e) {
11868                 throw e.rethrowFromSystemServer();
11869             }
11870         }
11871         return null;
11872     }
11873 
11874     /**
11875      * Called by a profile owner, device owner or a holder of any permission that is associated with
11876      * a user restriction to set a user restriction specified by the key.
11877      * <p>
11878      * The calling device admin must be a profile owner, device owner or holder of any permission
11879      * that is associated with a user restriction; if it is not, a security
11880      * exception will be thrown.
11881      * <p>
11882      * The profile owner of an organization-owned managed profile may invoke this method on
11883      * the {@link DevicePolicyManager} instance it obtained from
11884      * {@link #getParentProfileInstance(ComponentName)}, for enforcing device-wide restrictions.
11885      * <p>
11886      * See the constants in {@link android.os.UserManager} for the list of restrictions that can
11887      * be enforced device-wide. These constants will also state in their documentation which
11888      * permission is required to manage the restriction using this API.
11889      *
11890      * <p>For callers targeting Android {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or
11891      * above, calling this API will result in applying the restriction locally on the calling user,
11892      * or locally on the parent profile if called from the
11893      * {@link DevicePolicyManager} instance obtained from
11894      * {@link #getParentProfileInstance(ComponentName)}. To set a restriction globally, call
11895      * {@link #addUserRestrictionGlobally} instead.
11896      *
11897      * <p>
11898      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the user restriction
11899      * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
11900      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
11901      * successfully set or not. This callback will contain:
11902      * <ul>
11903      * <li> The policy identifier returned from
11904      * {@link DevicePolicyIdentifiers#getIdentifierForUserRestriction(String)}
11905      * <li> The {@link TargetUser} that this policy relates to
11906      * <li> The {@link PolicyUpdateResult}, which will be
11907      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
11908      * reason the policy failed to be set
11909      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
11910      * </ul>
11911      * If there has been a change to the policy,
11912      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
11913      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
11914      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
11915      * will contain the reason why the policy changed.
11916      *
11917      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11918      * @param key   The key of the restriction.
11919      * @throws SecurityException if {@code admin} is not a device or profile owner and if the caller
11920      * has not been granted the permission to set the given user restriction.
11921      */
addUserRestriction(@onNull ComponentName admin, @UserManager.UserRestrictionKey String key)11922     public void addUserRestriction(@NonNull ComponentName admin,
11923             @UserManager.UserRestrictionKey String key) {
11924         if (mService != null) {
11925             try {
11926                 mService.setUserRestriction(
11927                         admin, mContext.getPackageName(), key, true, mParentInstance);
11928             } catch (RemoteException e) {
11929                 throw e.rethrowFromSystemServer();
11930             }
11931         }
11932     }
11933 
11934     /**
11935      * Called by a profile owner, device owner or a holder of any permission that is associated with
11936      *  a user restriction to set a user restriction specified by the provided {@code key} globally
11937      *  on all users. To clear the restriction use {@link #clearUserRestriction}.
11938      *
11939      * <p>For a given user, a restriction will be set if it was applied globally or locally by any
11940      * admin.
11941      *
11942      * <p> The calling device admin must be a profile owner, device owner or or a holder of any
11943      * permission that is associated with a user restriction; if it is not, a security
11944      * exception will be thrown.
11945      *
11946      * <p> See the constants in {@link android.os.UserManager} for the list of restrictions that can
11947      * be enforced device-wide. These constants will also state in their documentation which
11948      * permission is required to manage the restriction using this API.
11949      * <p>
11950      * After the user restriction policy has been set,
11951      * {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, Bundle, TargetUser,
11952      * PolicyUpdateResult)} will notify the admin on whether the policy was successfully set or not.
11953      * This callback will contain:
11954      * <ul>
11955      * <li> The policy identifier returned from
11956      * {@link DevicePolicyIdentifiers#getIdentifierForUserRestriction(String)}
11957      * <li> The {@link TargetUser} that this policy relates to
11958      * <li> The {@link PolicyUpdateResult}, which will be
11959      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
11960      * reason the policy failed to be set
11961      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
11962      * </ul>
11963      * If there has been a change to the policy,
11964      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
11965      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
11966      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
11967      * will contain the reason why the policy changed.
11968      *
11969      * @param key The key of the restriction.
11970      * @throws SecurityException if {@code admin} is not a device or profile owner and if the
11971      * caller has not been granted the permission to set the given user restriction.
11972      * @throws IllegalStateException if caller is not targeting Android
11973      * {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or above.
11974      */
addUserRestrictionGlobally(@onNull @serManager.UserRestrictionKey String key)11975     public void addUserRestrictionGlobally(@NonNull @UserManager.UserRestrictionKey String key) {
11976         throwIfParentInstance("addUserRestrictionGlobally");
11977         if (mService != null) {
11978             try {
11979                 mService.setUserRestrictionGlobally(mContext.getPackageName(), key);
11980             } catch (RemoteException e) {
11981                 throw e.rethrowFromSystemServer();
11982             }
11983         }
11984     }
11985 
11986     /**
11987      * Called by a profile owner, device owner or a holder of any permission that is associated with
11988      * a user restriction to clear a user restriction specified by the key.
11989      * <p>
11990      * The calling device admin must be a profile or device owner; if it is not, a security
11991      * exception will be thrown.
11992      * <p>
11993      * The profile owner of an organization-owned managed profile may invoke this method on
11994      * the {@link DevicePolicyManager} instance it obtained from
11995      * {@link #getParentProfileInstance(ComponentName)}, for clearing device-wide restrictions.
11996      * <p>
11997      * See the constants in {@link android.os.UserManager} for the list of restrictions. These
11998      * constants state in their documentation which permission is required to manage the restriction
11999      * using this API.
12000      *
12001      * <p>For callers targeting Android {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or
12002      * above, calling this API will result in clearing any local and global restriction with the
12003      * specified key that was previously set by the caller.
12004      *
12005      * <p>
12006      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the user restriction
12007      * policy has been cleared, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
12008      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
12009      * successfully cleared or not. This callback will contain:
12010      * <ul>
12011      * <li> The policy identifier returned from
12012      * {@link DevicePolicyIdentifiers#getIdentifierForUserRestriction(String)}
12013      * <li> The {@link TargetUser} that this policy relates to
12014      * <li> The {@link PolicyUpdateResult}, which will be
12015      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully cleared or the
12016      * reason the policy failed to be cleared
12017      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
12018      * </ul>
12019      * If there has been a change to the policy,
12020      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
12021      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
12022      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
12023      * will contain the reason why the policy changed.
12024      *
12025      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12026      * @param key   The key of the restriction.
12027      * @throws SecurityException if {@code admin} is not a device or profile owner  and if the
12028      *  caller has not been granted the permission to set the given user restriction.
12029      */
clearUserRestriction(@onNull ComponentName admin, @UserManager.UserRestrictionKey String key)12030     public void clearUserRestriction(@NonNull ComponentName admin,
12031             @UserManager.UserRestrictionKey String key) {
12032         if (mService != null) {
12033             try {
12034                 mService.setUserRestriction(
12035                         admin, mContext.getPackageName(), key, false, mParentInstance);
12036             } catch (RemoteException e) {
12037                 throw e.rethrowFromSystemServer();
12038             }
12039         }
12040     }
12041 
12042     /**
12043      * Called by an admin to get user restrictions set by themselves with
12044      * {@link #addUserRestriction(ComponentName, String)}.
12045      * <p>
12046      * The target user may have more restrictions set by the system or other admin.
12047      * To get all the user restrictions currently set, use
12048      * {@link UserManager#getUserRestrictions()}.
12049      * <p>
12050      * The profile owner of an organization-owned managed profile may invoke this method on
12051      * the {@link DevicePolicyManager} instance it obtained from
12052      * {@link #getParentProfileInstance(ComponentName)}, for retrieving device-wide restrictions
12053      * it previously set with {@link #addUserRestriction(ComponentName, String)}.
12054      *
12055      * <p>For callers targeting Android {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or
12056      * above, this API will return the local restrictions set on the calling user, or on the parent
12057      * profile if called from the {@link DevicePolicyManager} instance obtained from
12058      * {@link #getParentProfileInstance(ComponentName)}. To get global restrictions set by admin,
12059      * call {@link #getUserRestrictionsGlobally()} instead.
12060      *
12061      * <p>Note that this is different that the returned restrictions for callers targeting pre
12062      * Android {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, were this API returns
12063      * all local/global restrictions set by the admin on the calling user using
12064      * {@link #addUserRestriction(ComponentName, String)} or the parent user if called on the
12065      * {@link DevicePolicyManager} instance it obtained from {@link #getParentProfileInstance}.
12066      *
12067      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12068      * @return a {@link Bundle} whose keys are the user restrictions, and the values a
12069      * {@code boolean} indicating whether the restriction is set.
12070      * @throws SecurityException if {@code admin} is not a device or profile owner.
12071      */
getUserRestrictions(@onNull ComponentName admin)12072     public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
12073         Bundle ret = null;
12074         if (mService != null) {
12075             try {
12076                 ret = mService.getUserRestrictions(
12077                         admin, mContext.getPackageName(), mParentInstance);
12078             } catch (RemoteException e) {
12079                 throw e.rethrowFromSystemServer();
12080             }
12081         }
12082         return ret == null ? new Bundle() : ret;
12083     }
12084 
12085     /**
12086      * Called by a profile or device owner to get global user restrictions set with
12087      * {@link #addUserRestrictionGlobally(String)}.
12088      * <p>
12089      * To get all the user restrictions currently set for a certain user, use
12090      * {@link UserManager#getUserRestrictions()}.
12091      * @return a {@link Bundle} whose keys are the user restrictions, and the values a
12092      * {@code boolean} indicating whether the restriction is set.
12093      * @throws SecurityException if {@code admin} is not a device or profile owner.
12094      * @throws IllegalStateException if caller is not targeting Android
12095      * {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} or above.
12096      */
getUserRestrictionsGlobally()12097     public @NonNull Bundle getUserRestrictionsGlobally() {
12098         throwIfParentInstance("createAdminSupportIntent");
12099         Bundle ret = null;
12100         if (mService != null) {
12101             try {
12102                 ret = mService.getUserRestrictionsGlobally(mContext.getPackageName());
12103             } catch (RemoteException e) {
12104                 throw e.rethrowFromSystemServer();
12105             }
12106         }
12107         return ret == null ? new Bundle() : ret;
12108     }
12109 
12110     /**
12111      * Called by any app to display a support dialog when a feature was disabled by an admin.
12112      * This returns an intent that can be used with {@link Context#startActivity(Intent)} to
12113      * display the dialog. It will tell the user that the feature indicated by {@code restriction}
12114      * was disabled by an admin, and include a link for more information. The default content of
12115      * the dialog can be changed by the restricting admin via
12116      * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not
12117      * set (i.e. the feature is available), then the return value will be {@code null}.
12118      * @param restriction Indicates for which feature the dialog should be displayed. Can be a
12119      *            user restriction from {@link UserManager}, e.g.
12120      *            {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants
12121      *            {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
12122      * @return Intent An intent to be used to start the dialog-activity if the restriction is
12123      *            set by an admin, or null if the restriction does not exist or no admin set it.
12124      */
createAdminSupportIntent(@onNull String restriction)12125     public Intent createAdminSupportIntent(@NonNull String restriction) {
12126         throwIfParentInstance("createAdminSupportIntent");
12127         Intent result = null;
12128         if (mService != null) {
12129             try {
12130                 result = mService.createAdminSupportIntent(restriction);
12131                 if (result != null) {
12132                     result.prepareToEnterProcess(LOCAL_FLAG_FROM_SYSTEM,
12133                             mContext.getAttributionSource());
12134                 }
12135             } catch (RemoteException e) {
12136                 throw e.rethrowFromSystemServer();
12137             }
12138         }
12139         return result;
12140     }
12141 
12142     /**
12143      * @param userId      The user for whom to retrieve information.
12144      * @param restriction The restriction enforced by admin. It could be any user restriction or
12145      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and
12146      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}.
12147      * @return Details of admin and user which enforced the restriction for the userId. If
12148      * restriction is null, profile owner for the user or device owner info is returned.
12149      * @hide
12150      */
getEnforcingAdminAndUserDetails(int userId, @Nullable String restriction)12151     public @Nullable Bundle getEnforcingAdminAndUserDetails(int userId,
12152             @Nullable String restriction) {
12153         if (mService != null) {
12154             try {
12155                 return mService.getEnforcingAdminAndUserDetails(userId, restriction);
12156             } catch (RemoteException e) {
12157                 throw e.rethrowFromSystemServer();
12158             }
12159         }
12160         return null;
12161     }
12162 
12163     /**
12164      * Returns the list of {@link EnforcingAdmin}s who have set this restriction.
12165      *
12166      * <p>Note that for {@link #POLICY_SUSPEND_PACKAGES} it returns the PO or DO to keep the
12167      * behavior the same as before the bug fix for b/192245204.
12168      *
12169      * <p>This API is only callable by the system UID
12170      *
12171      * @param userId      The user for whom to retrieve the information.
12172      * @param restriction The restriction enforced by admins. It could be any user restriction or
12173      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and
12174      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}.
12175      *
12176      * @hide
12177      */
getEnforcingAdminsForRestriction(int userId, @NonNull String restriction)12178     public @NonNull Set<EnforcingAdmin> getEnforcingAdminsForRestriction(int userId,
12179             @NonNull String restriction) {
12180         if (mService != null) {
12181             try {
12182                 return new HashSet<>(mService.getEnforcingAdminsForRestriction(
12183                         userId, restriction));
12184             } catch (RemoteException e) {
12185                 throw e.rethrowFromSystemServer();
12186             }
12187         }
12188         return null;
12189     }
12190 
12191     /**
12192      * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and
12193      * actual package file remain. This function can be called by a device owner, profile owner, or
12194      * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
12195      * {@link #setDelegatedScopes}.
12196      * <p>
12197      * This method can be called on the {@link DevicePolicyManager} instance, returned by
12198      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
12199      * of an organization-owned managed profile and the package must be a system package. If called
12200      * on the parent instance, then the package is hidden or unhidden in the personal profile.
12201      * <p>
12202      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the application hidden
12203      * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
12204      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
12205      * successfully set or not. This callback will contain:
12206      * <ul>
12207      * <li> The policy identifier
12208      * {@link DevicePolicyIdentifiers#APPLICATION_HIDDEN_POLICY}
12209      * <li> The additional policy params bundle, which contains
12210      * {@link PolicyUpdateReceiver#EXTRA_PACKAGE_NAME} the package name the policy applies to
12211      * <li> The {@link TargetUser} that this policy relates to
12212      * <li> The {@link PolicyUpdateResult}, which will be
12213      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
12214      * reason the policy failed to be set
12215      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
12216      * </ul>
12217      * If there has been a change to the policy,
12218      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
12219      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
12220      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
12221      * will contain the reason why the policy changed.
12222      *
12223      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
12224      *            {@code null} if the caller is not a device admin.
12225      * @param packageName The name of the package to hide or unhide.
12226      * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
12227      *            unhidden.
12228      * @return boolean Whether the hidden setting of the package was successfully updated.
12229      * @throws SecurityException if {@code admin} is not a device or profile owner or if called on
12230      *            the parent profile and the {@code admin} is not a profile owner of an
12231      *            organization-owned managed profile.
12232      * @throws IllegalArgumentException if called on the parent profile and the package provided
12233      *            is not a system package.
12234      * @see #setDelegatedScopes
12235      * @see #DELEGATION_PACKAGE_ACCESS
12236      */
12237     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PACKAGE_STATE, conditional = true)
setApplicationHidden(@ullable ComponentName admin, String packageName, boolean hidden)12238     public boolean setApplicationHidden(@Nullable ComponentName admin, String packageName,
12239             boolean hidden) {
12240         if (mService != null) {
12241             try {
12242                 return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName,
12243                         hidden, mParentInstance);
12244             } catch (RemoteException e) {
12245                 throw e.rethrowFromSystemServer();
12246             }
12247         }
12248         return false;
12249     }
12250 
12251     /**
12252      * Determine if a package is hidden. This function can be called by a device owner, profile
12253      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
12254      * {@link #setDelegatedScopes}.
12255      * <p>
12256      * This method can be called on the {@link DevicePolicyManager} instance, returned by
12257      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
12258      * of an organization-owned managed profile and the package must be a system package. If called
12259      * on the parent instance, this will determine whether the package is hidden or unhidden in the
12260      * personal profile.
12261      * <p>
12262      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the returned policy will be the
12263      * current resolved policy rather than the policy set by the calling admin.
12264      *
12265      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
12266      *            {@code null} if the caller is not a device admin.
12267      * @param packageName The name of the package to retrieve the hidden status of.
12268      * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
12269      * @throws SecurityException if {@code admin} is not a device or profile owner or if called on
12270      *            the parent profile and the {@code admin} is not a profile owner of an
12271      *            organization-owned managed profile.
12272      * @throws IllegalArgumentException if called on the parent profile and the package provided
12273      *            is not a system package.
12274      * @see #setDelegatedScopes
12275      * @see #DELEGATION_PACKAGE_ACCESS
12276      */
12277     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PACKAGE_STATE, conditional = true)
isApplicationHidden(@ullable ComponentName admin, String packageName)12278     public boolean isApplicationHidden(@Nullable ComponentName admin, String packageName) {
12279         if (mService != null) {
12280             try {
12281                 return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName,
12282                         mParentInstance);
12283             } catch (RemoteException e) {
12284                 throw e.rethrowFromSystemServer();
12285             }
12286         }
12287         return false;
12288     }
12289 
12290     /**
12291      * Re-enable a system app that was disabled by default when the user was initialized. This
12292      * function can be called by a device owner, profile owner, or by a delegate given the
12293      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
12294      *
12295      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
12296      *            {@code null} if the caller is an enable system app delegate.
12297      * @param packageName The package to be re-enabled in the calling profile.
12298      * @throws SecurityException if {@code admin} is not a device or profile owner.
12299      * @see #setDelegatedScopes
12300      * @see #DELEGATION_PACKAGE_ACCESS
12301      */
enableSystemApp(@onNull ComponentName admin, String packageName)12302     public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
12303         throwIfParentInstance("enableSystemApp");
12304         if (mService != null) {
12305             try {
12306                 mService.enableSystemApp(admin, mContext.getPackageName(), packageName);
12307             } catch (RemoteException e) {
12308                 throw e.rethrowFromSystemServer();
12309             }
12310         }
12311     }
12312 
12313     /**
12314      * Re-enable system apps by intent that were disabled by default when the user was initialized.
12315      * This function can be called by a device owner, profile owner, or by a delegate given the
12316      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
12317      *
12318      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
12319      *            {@code null} if the caller is an enable system app delegate.
12320      * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
12321      *            intent will be re-enabled in the calling profile.
12322      * @return int The number of activities that matched the intent and were installed.
12323      * @throws SecurityException if {@code admin} is not a device or profile owner.
12324      * @see #setDelegatedScopes
12325      * @see #DELEGATION_PACKAGE_ACCESS
12326      */
enableSystemApp(@onNull ComponentName admin, Intent intent)12327     public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
12328         throwIfParentInstance("enableSystemApp");
12329         if (mService != null) {
12330             try {
12331                 return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent);
12332             } catch (RemoteException e) {
12333                 throw e.rethrowFromSystemServer();
12334             }
12335         }
12336         return 0;
12337     }
12338 
12339     /**
12340      * Install an existing package that has been installed in another user, or has been kept after
12341      * removal via {@link #setKeepUninstalledPackages}.
12342      * This function can be called by a device owner, profile owner or a delegate given
12343      * the {@link #DELEGATION_INSTALL_EXISTING_PACKAGE} scope via {@link #setDelegatedScopes}.
12344      * When called in a secondary user or managed profile, the user/profile must be affiliated with
12345      * the device. See {@link #isAffiliatedUser}.
12346      *
12347      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12348      * @param packageName The package to be installed in the calling profile.
12349      * @return {@code true} if the app is installed; {@code false} otherwise.
12350      * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
12351      * an affiliated user or profile.
12352      * @see #setKeepUninstalledPackages
12353      * @see #setDelegatedScopes
12354      * @see #isAffiliatedUser
12355      * @see #DELEGATION_PACKAGE_ACCESS
12356      */
installExistingPackage(@onNull ComponentName admin, String packageName)12357     public boolean installExistingPackage(@NonNull ComponentName admin, String packageName) {
12358         throwIfParentInstance("installExistingPackage");
12359         if (mService != null) {
12360             try {
12361                 return mService.installExistingPackage(admin, mContext.getPackageName(),
12362                         packageName);
12363             } catch (RemoteException e) {
12364                 throw e.rethrowFromSystemServer();
12365             }
12366         }
12367         return false;
12368     }
12369 
12370     /**
12371      * Called by a device owner or profile owner to disable account management for a specific type
12372      * of account.
12373      * <p>
12374      * The calling device admin must be a device owner or profile owner. If it is not, a security
12375      * exception will be thrown.
12376      * <p>
12377      * When account management is disabled for an account type, adding or removing an account of
12378      * that type will not be possible.
12379      * <p>
12380      * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
12381      * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
12382      * management for a specific type is disabled.
12383      * <p>
12384      * This method may be called on the {@code DevicePolicyManager} instance returned from
12385      * {@link #getParentProfileInstance(ComponentName)} by the profile owner on an
12386      * organization-owned device, to restrict accounts that may not be managed on the primary
12387      * profile.
12388      * <p>
12389      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the account management
12390      * disabled policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
12391      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
12392      * successfully set or not. This callback will contain:
12393      * <ul>
12394      * <li> The policy identifier
12395      * {@link DevicePolicyIdentifiers#ACCOUNT_MANAGEMENT_DISABLED_POLICY}
12396      * <li> The additional policy params bundle, which contains
12397      * {@link PolicyUpdateReceiver#EXTRA_ACCOUNT_TYPE} the account type the policy applies to
12398      * <li> The {@link TargetUser} that this policy relates to
12399      * <li> The {@link PolicyUpdateResult}, which will be
12400      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
12401      * reason the policy failed to be set
12402      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
12403      * </ul>
12404      * If there has been a change to the policy,
12405      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
12406      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
12407      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
12408      * will contain the reason why the policy changed.
12409      *
12410      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12411      *              caller is not a device admin.
12412      * @param accountType For which account management is disabled or enabled.
12413      * @param disabled The boolean indicating that account management will be disabled (true) or
12414      *            enabled (false).
12415      * @throws SecurityException if {@code admin} is not a device or profile owner.
12416      */
12417     @RequiresPermission(value = MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT, conditional = true)
setAccountManagementDisabled(@ullable ComponentName admin, String accountType, boolean disabled)12418     public void setAccountManagementDisabled(@Nullable ComponentName admin, String accountType,
12419             boolean disabled) {
12420         if (mService != null) {
12421             try {
12422                 mService.setAccountManagementDisabled(admin, mContext.getPackageName(), accountType,
12423                         disabled, mParentInstance);
12424             } catch (RemoteException e) {
12425                 throw e.rethrowFromSystemServer();
12426             }
12427         }
12428     }
12429 
12430     /**
12431      * Gets the array of accounts for which account management is disabled by the profile owner
12432      * or device owner.
12433      *
12434      * <p> Account management can be disabled/enabled by calling
12435      * {@link #setAccountManagementDisabled}.
12436      * <p>
12437      * This method may be called on the {@code DevicePolicyManager} instance returned from
12438      * {@link #getParentProfileInstance(ComponentName)}. Note that only a profile owner on
12439      * an organization-owned device can affect account types on the parent profile instance.
12440      *
12441      * @return a list of account types for which account management has been disabled.
12442      *
12443      * @see #setAccountManagementDisabled
12444      */
getAccountTypesWithManagementDisabled()12445     public @Nullable String[] getAccountTypesWithManagementDisabled() {
12446         return getAccountTypesWithManagementDisabledAsUser(myUserId(), mParentInstance);
12447     }
12448 
12449     /**
12450      * @see #getAccountTypesWithManagementDisabled()
12451      * Note that calling this method on the parent profile instance will return the same
12452      * value as calling it on the main {@code DevicePolicyManager} instance.
12453      * @hide
12454      */
12455     @RequiresPermission(value = MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT, conditional = true)
getAccountTypesWithManagementDisabledAsUser(int userId)12456     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
12457         return getAccountTypesWithManagementDisabledAsUser(userId, false);
12458     }
12459 
12460     /**
12461      * @see #getAccountTypesWithManagementDisabled()
12462      * @hide
12463      */
getAccountTypesWithManagementDisabledAsUser( int userId, boolean parentInstance)12464     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(
12465             int userId, boolean parentInstance) {
12466         if (mService != null) {
12467             try {
12468                 return mService.getAccountTypesWithManagementDisabledAsUser(userId,
12469                         mContext.getPackageName(), parentInstance);
12470             } catch (RemoteException e) {
12471                 throw e.rethrowFromSystemServer();
12472             }
12473         }
12474 
12475         return null;
12476     }
12477 
12478     /**
12479      * Called by device owner or profile owner to set whether a secondary lockscreen needs to be
12480      * shown.
12481      *
12482      * <p>The secondary lockscreen will by displayed after the primary keyguard security screen
12483      * requirements are met. To provide the lockscreen content the DO/PO will need to provide a
12484      * service handling the {@link #ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE} intent action,
12485      * extending the {@link DevicePolicyKeyguardService} class.
12486      *
12487      * <p>Relevant interactions on the secondary lockscreen should be communicated back to the
12488      * keyguard via {@link IKeyguardCallback}, such as when the screen is ready to be dismissed.
12489      *
12490      * <p>This API, and associated APIs, can only be called by the default supervision app when it
12491      * is set as the device owner or profile owner.
12492      *
12493      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12494      * @param enabled Whether or not the lockscreen needs to be shown.
12495      * @throws SecurityException if {@code admin} is not a device or profile owner.
12496      * @see #isSecondaryLockscreenEnabled
12497      * @hide
12498      **/
12499     @SystemApi
setSecondaryLockscreenEnabled(@onNull ComponentName admin, boolean enabled)12500     public void setSecondaryLockscreenEnabled(@NonNull ComponentName admin, boolean enabled) {
12501         throwIfParentInstance("setSecondaryLockscreenEnabled");
12502         if (mService != null) {
12503             try {
12504                 mService.setSecondaryLockscreenEnabled(admin, enabled);
12505             } catch (RemoteException e) {
12506                 throw e.rethrowFromSystemServer();
12507             }
12508         }
12509     }
12510 
12511     /**
12512      * Returns whether the secondary lock screen needs to be shown.
12513      * @see #setSecondaryLockscreenEnabled
12514      * @hide
12515      */
12516     @SystemApi
isSecondaryLockscreenEnabled(@onNull UserHandle userHandle)12517     public boolean isSecondaryLockscreenEnabled(@NonNull UserHandle userHandle) {
12518         throwIfParentInstance("isSecondaryLockscreenEnabled");
12519         if (mService != null) {
12520             try {
12521                 return mService.isSecondaryLockscreenEnabled(userHandle);
12522             } catch (RemoteException e) {
12523                 throw e.rethrowFromSystemServer();
12524             }
12525         }
12526         return false;
12527     }
12528 
12529     /**
12530      * Sets which packages may enter lock task mode.
12531      * <p>
12532      * Any packages that share uid with an allowed package will also be allowed to activate lock
12533      * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
12534      * package list results in locked tasks belonging to those packages to be finished.
12535      * <p>
12536      * This function can only be called by the device owner, a profile owner of an affiliated user
12537      * or profile, or the profile owner when no device owner is set or holders of the permission
12538      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}. See
12539      * {@link #isAffiliatedUser}.
12540      * Any package set via this method will be cleared if the user becomes unaffiliated.
12541      * <p>
12542      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the lock task policy has
12543      * been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, Bundle, TargetUser,
12544      * PolicyUpdateResult)} will notify the admin on whether the policy was successfully set or not.
12545      * This callback will contain:
12546      * <ul>
12547      * <li> The policy identifier {@link DevicePolicyIdentifiers#LOCK_TASK_POLICY}
12548      * <li> The {@link TargetUser} that this policy relates to
12549      * <li> The {@link PolicyUpdateResult}, which will be
12550      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
12551      * reason the policy failed to be set
12552      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
12553      * </ul>
12554      * If there has been a change to the policy,
12555      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
12556      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
12557      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
12558      * will contain the reason why the policy changed.
12559      * <p>
12560      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, lock task features and lock task
12561      * packages are bundled as one policy. A failure to apply one will result in a failure to apply
12562      * the other.
12563      *
12564      * @param packages The list of packages allowed to enter lock task mode
12565      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12566      *               caller is not a device admin.
12567      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
12568      * affiliated user or profile, or the profile owner when no device owner is set or holder of the
12569      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}.
12570      * @see #isAffiliatedUser
12571      * @see Activity#startLockTask()
12572      * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
12573      * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
12574      * @see UserManager#DISALLOW_CREATE_WINDOWS
12575      */
12576     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true)
12577     @SupportsCoexistence
setLockTaskPackages(@ullable ComponentName admin, @NonNull String[] packages)12578     public void setLockTaskPackages(@Nullable ComponentName admin, @NonNull String[] packages)
12579             throws SecurityException {
12580         throwIfParentInstance("setLockTaskPackages");
12581         if (mService != null) {
12582             try {
12583                 mService.setLockTaskPackages(admin, mContext.getPackageName(),  packages);
12584             } catch (RemoteException e) {
12585                 throw e.rethrowFromSystemServer();
12586             }
12587         }
12588     }
12589 
12590     /**
12591      * Returns the list of packages allowed to start the lock task mode.
12592      * <p>
12593      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the returned policy will be the
12594      * current resolved policy rather than the policy set by the calling admin.
12595      *
12596      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12597      *              caller is not a device admin.
12598      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
12599      * affiliated user or profile, or the profile owner when no device owner is set or holder of the
12600      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}.
12601      * @see #isAffiliatedUser
12602      * @see #setLockTaskPackages
12603      */
12604     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true)
getLockTaskPackages(@ullable ComponentName admin)12605     public @NonNull String[] getLockTaskPackages(@Nullable ComponentName admin) {
12606         throwIfParentInstance("getLockTaskPackages");
12607         if (mService != null) {
12608             try {
12609                 return mService.getLockTaskPackages(admin, mContext.getPackageName());
12610             } catch (RemoteException e) {
12611                 throw e.rethrowFromSystemServer();
12612             }
12613         }
12614         return new String[0];
12615     }
12616 
12617     /**
12618      * This function lets the caller know whether the given component is allowed to start the
12619      * lock task mode.
12620      * @param pkg The package to check
12621      */
isLockTaskPermitted(String pkg)12622     public boolean isLockTaskPermitted(String pkg) {
12623         throwIfParentInstance("isLockTaskPermitted");
12624         if (mService != null) {
12625             try {
12626                 return mService.isLockTaskPermitted(pkg);
12627             } catch (RemoteException e) {
12628                 throw e.rethrowFromSystemServer();
12629             }
12630         }
12631         return false;
12632     }
12633 
12634     /**
12635      * Sets which system features are enabled when the device runs in lock task mode. This method
12636      * doesn't affect the features when lock task mode is inactive. Any system features not included
12637      * in {@code flags} are implicitly disabled when calling this method. By default, only
12638      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS} is enabled; all the other features are disabled. To
12639      * disable the global actions dialog, call this method omitting
12640      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}.
12641      *
12642      * <p>This method can only be called by the device owner, a profile owner of an affiliated
12643      * user or profile, or the profile owner when no device owner is set or holders of the
12644      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}. See
12645      * {@link #isAffiliatedUser}.
12646      * Any features set using this method are cleared if the user becomes unaffiliated.
12647      * <p>
12648      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the lock task features
12649      * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String, Bundle,
12650      * TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
12651      * successfully set or not. This callback will contain:
12652      * <ul>
12653      * <li> The policy identifier {@link DevicePolicyIdentifiers#LOCK_TASK_POLICY}
12654      * <li> The {@link TargetUser} that this policy relates to
12655      * <li> The {@link PolicyUpdateResult}, which will be
12656      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
12657      * reason the policy failed to be set
12658      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
12659      * </ul>
12660      * If there has been a change to the policy,
12661      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
12662      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
12663      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
12664      * will contain the reason why the policy changed.
12665      * <p>
12666      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, lock task features and lock task
12667      * packages are bundled as one policy. A failure to apply one will result in a failure to apply
12668      * the other.
12669      *
12670      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12671      *               caller is not a device admin.
12672      * @param flags The system features enabled during lock task mode.
12673      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
12674      * affiliated user or profile, or the profile owner when no device owner is set or holder of the
12675      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}.
12676      * @see #isAffiliatedUser
12677      **/
12678     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true)
12679     @SupportsCoexistence
setLockTaskFeatures(@ullable ComponentName admin, @LockTaskFeature int flags)12680     public void setLockTaskFeatures(@Nullable ComponentName admin, @LockTaskFeature int flags) {
12681         throwIfParentInstance("setLockTaskFeatures");
12682         if (mService != null) {
12683             try {
12684                 mService.setLockTaskFeatures(admin, mContext.getPackageName(), flags);
12685             } catch (RemoteException e) {
12686                 throw e.rethrowFromSystemServer();
12687             }
12688         }
12689     }
12690 
12691     /**
12692      * Gets which system features are enabled for LockTask mode.
12693      * <p>
12694      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the returned policy will be the
12695      * current resolved policy rather than the policy set by the calling admin.
12696      *
12697      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12698      *               caller is not a device admin.
12699      * @return bitfield of flags. See {@link #setLockTaskFeatures(ComponentName, int)} for a list.
12700      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
12701      * affiliated user or profile, or the profile owner when no device owner is set or holder of the
12702      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_LOCK_TASK}.
12703      * @see #isAffiliatedUser
12704      * @see #setLockTaskFeatures
12705      */
12706     @RequiresPermission(value = MANAGE_DEVICE_POLICY_LOCK_TASK, conditional = true)
getLockTaskFeatures(@ullable ComponentName admin)12707     public @LockTaskFeature int getLockTaskFeatures(@Nullable ComponentName admin) {
12708         throwIfParentInstance("getLockTaskFeatures");
12709         if (mService != null) {
12710             try {
12711                 return mService.getLockTaskFeatures(admin, mContext.getPackageName());
12712             } catch (RemoteException e) {
12713                 throw e.rethrowFromSystemServer();
12714             }
12715         }
12716         return 0;
12717     }
12718 
12719     /**
12720      * Sets whether preferential network service is enabled.
12721      * For example, an organization can have a deal/agreement with a carrier that all of
12722      * the work data from its employees’ devices will be sent via a network service dedicated
12723      * for enterprise use.
12724      *
12725      * An example of a supported preferential network service is the Enterprise
12726      * slice on 5G networks. For devices on 4G networks, the profile owner needs to additionally
12727      * configure enterprise APN to set up data call for the preferential network service.
12728      * These APNs can be added using {@link #addOverrideApn}.
12729      *
12730      * By default, preferential network service is disabled on the work profile and
12731      * fully managed devices, on supported carriers and devices.
12732      * Admins can explicitly enable it with this API.
12733      *
12734      * <p> This method enables preferential network service with a default configuration.
12735      * To fine-tune the configuration, use {@link #setPreferentialNetworkServiceConfigs) instead.
12736      * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
12737      * this method can be called by the profile owner of a managed profile.
12738      * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
12739      * This method can be called by the profile owner of a managed profile
12740      * or device owner.
12741      *
12742      * @param enabled whether preferential network service should be enabled.
12743      * @throws SecurityException if the caller is not the profile owner or device owner.
12744      **/
setPreferentialNetworkServiceEnabled(boolean enabled)12745     public void setPreferentialNetworkServiceEnabled(boolean enabled) {
12746         throwIfParentInstance("setPreferentialNetworkServiceEnabled");
12747         PreferentialNetworkServiceConfig.Builder configBuilder =
12748                 new PreferentialNetworkServiceConfig.Builder();
12749         configBuilder.setEnabled(enabled);
12750         if (enabled) {
12751             configBuilder.setNetworkId(NET_ENTERPRISE_ID_1);
12752         }
12753         setPreferentialNetworkServiceConfigs(List.of(configBuilder.build()));
12754     }
12755 
12756     /**
12757      * Indicates whether preferential network service is enabled.
12758      *
12759      * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
12760      * This method can be called by the profile owner of a managed profile.
12761      * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
12762      * This method can be called by the profile owner of a managed profile
12763      * or device owner.
12764      *
12765      * @return whether preferential network service is enabled.
12766      * @throws SecurityException if the caller is not the profile owner or device owner.
12767      */
isPreferentialNetworkServiceEnabled()12768     public boolean isPreferentialNetworkServiceEnabled() {
12769         throwIfParentInstance("isPreferentialNetworkServiceEnabled");
12770         return getPreferentialNetworkServiceConfigs().stream().anyMatch(c -> c.isEnabled());
12771     }
12772 
12773     /**
12774      * Sets preferential network configurations.
12775      * {@see PreferentialNetworkServiceConfig}
12776      *
12777      * An example of a supported preferential network service is the Enterprise
12778      * slice on 5G networks. For devices on 4G networks, the profile owner needs to additionally
12779      * configure enterprise APN to set up data call for the preferential network service.
12780      * These APNs can be added using {@link #addOverrideApn}.
12781      *
12782      * By default, preferential network service is disabled on the work profile and fully managed
12783      * devices, on supported carriers and devices. Admins can explicitly enable it with this API.
12784      * If admin wants to have multiple enterprise slices,
12785      * it can be configured by passing list of {@link PreferentialNetworkServiceConfig} objects.
12786      *
12787      * @param preferentialNetworkServiceConfigs list of preferential network configurations.
12788      * @throws SecurityException if the caller is not the profile owner or device owner.
12789      **/
setPreferentialNetworkServiceConfigs( @onNull List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs)12790     public void setPreferentialNetworkServiceConfigs(
12791             @NonNull List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs) {
12792         throwIfParentInstance("setPreferentialNetworkServiceConfigs");
12793         if (mService == null) {
12794             return;
12795         }
12796         try {
12797             mService.setPreferentialNetworkServiceConfigs(preferentialNetworkServiceConfigs);
12798         } catch (RemoteException e) {
12799             throw e.rethrowFromSystemServer();
12800         }
12801     }
12802 
12803     /**
12804      * Get preferential network configuration
12805      * {@see PreferentialNetworkServiceConfig}
12806      *
12807      * @return preferential network configuration.
12808      * @throws SecurityException if the caller is not the profile owner or device owner.
12809      */
getPreferentialNetworkServiceConfigs()12810     public @NonNull List<PreferentialNetworkServiceConfig> getPreferentialNetworkServiceConfigs() {
12811         throwIfParentInstance("getPreferentialNetworkServiceConfigs");
12812         if (mService == null) {
12813             return List.of(PreferentialNetworkServiceConfig.DEFAULT);
12814         }
12815         try {
12816             return mService.getPreferentialNetworkServiceConfigs();
12817         } catch (RemoteException e) {
12818             throw e.rethrowFromSystemServer();
12819         }
12820     }
12821 
12822     /**
12823      * This method is mostly deprecated.
12824      * Most of the settings that still have an effect have dedicated setter methods or user
12825      * restrictions. See individual settings for details.
12826      * <p>
12827      * Called by device owner to update {@link android.provider.Settings.Global} settings.
12828      * Validation that the value of the setting is in the correct form for the setting type should
12829      * be performed by the caller.
12830      * <p>
12831      * The settings that can be updated with this method are:
12832      * <ul>
12833      * <li>{@link android.provider.Settings.Global#ADB_ENABLED} : use
12834      * {@link UserManager#DISALLOW_DEBUGGING_FEATURES} instead to restrict users from enabling
12835      * debugging features and this setting to turn adb on.</li>
12836      * <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
12837      * <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only
12838      * available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
12839      * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
12840      * <li>{@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This
12841      * setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
12842      * </ul>
12843      * <p>
12844      * The following settings used to be supported, but can be controlled in other ways:
12845      * <ul>
12846      * <li>{@link android.provider.Settings.Global#AUTO_TIME} : Use {@link #setAutoTimeEnabled} and
12847      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} instead.</li>
12848      * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE} : Use
12849      * {@link #setAutoTimeZoneEnabled} and {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
12850      * instead.</li>
12851      * <li>{@link android.provider.Settings.Global#DATA_ROAMING} : Use
12852      * {@link UserManager#DISALLOW_DATA_ROAMING} instead.</li>
12853      * </ul>
12854      * <p>
12855      * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
12856      * <ul>
12857      * <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use
12858      * {@link android.bluetooth.BluetoothAdapter#enable()} and
12859      * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
12860      * <li>{@link android.provider.Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
12861      * <li>{@link android.provider.Settings.Global#MODE_RINGER}. Use
12862      * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
12863      * <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li>
12864      * <li>{@link android.provider.Settings.Global#WIFI_ON}. Use
12865      * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
12866      * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}. No longer has effect.</li>
12867      * </ul>
12868      *
12869      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12870      * @param setting The name of the setting to update.
12871      * @param value The value to update the setting to.
12872      * @throws SecurityException if {@code admin} is not a device owner.
12873      */
setGlobalSetting(@onNull ComponentName admin, String setting, String value)12874     public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
12875         throwIfParentInstance("setGlobalSetting");
12876         if (mService != null) {
12877             try {
12878                 mService.setGlobalSetting(admin, setting, value);
12879             } catch (RemoteException e) {
12880                 throw e.rethrowFromSystemServer();
12881             }
12882         }
12883     }
12884 
12885     /** @hide */
12886     @StringDef({
12887             Settings.System.SCREEN_BRIGHTNESS_MODE,
12888             Settings.System.SCREEN_BRIGHTNESS,
12889             Settings.System.SCREEN_OFF_TIMEOUT
12890     })
12891     @Retention(RetentionPolicy.SOURCE)
12892     public @interface SystemSettingsWhitelist {}
12893 
12894     /**
12895      * Called by a device or profile owner to update {@link android.provider.Settings.System}
12896      * settings. Validation that the value of the setting is in the correct form for the setting
12897      * type should be performed by the caller.
12898      * <p>
12899      * The settings that can be updated by a device owner or profile owner of secondary user with
12900      * this method are:
12901      * <ul>
12902      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS}</li>
12903      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS_MODE}</li>
12904      * <li>{@link android.provider.Settings.System#SCREEN_OFF_TIMEOUT}</li>
12905      * </ul>
12906      * <p>
12907      * Starting from Android {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}, a
12908      * profile owner on an organization-owned device can call this method on the parent
12909      * {@link DevicePolicyManager} instance returned by
12910      * {@link #getParentProfileInstance(ComponentName)} to set system settings on the parent user.
12911      *
12912      * @see android.provider.Settings.System#SCREEN_OFF_TIMEOUT
12913      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
12914      * @param setting The name of the setting to update.
12915      * @param value The value to update the setting to.
12916      * @throws SecurityException if {@code admin} is not a device or profile owner.
12917      */
setSystemSetting(@onNull ComponentName admin, @NonNull @SystemSettingsWhitelist String setting, String value)12918     public void setSystemSetting(@NonNull ComponentName admin,
12919             @NonNull @SystemSettingsWhitelist String setting, String value) {
12920         if (mService != null) {
12921             try {
12922                 mService.setSystemSetting(admin, setting, value, mParentInstance);
12923             } catch (RemoteException e) {
12924                 throw e.rethrowFromSystemServer();
12925             }
12926         }
12927     }
12928 
12929     /**
12930      * Called by a device owner or a profile owner of an organization-owned managed profile to
12931      * control whether the user can change networks configured by the admin. When this lockdown is
12932      * enabled, the user can still configure and connect to other Wi-Fi networks, or use other Wi-Fi
12933      * capabilities such as tethering.
12934      * <p>
12935      * WiFi network configuration lockdown is controlled by a global settings
12936      * {@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN} and calling
12937      * this API effectively modifies the global settings. Previously device owners can also
12938      * control this directly via {@link #setGlobalSetting} but they are recommended to switch
12939      * to this API.
12940      *
12941      * @param admin             admin Which {@link DeviceAdminReceiver} this request is associated
12942      *                          with. Null if the caller is not a device admin.
12943      * @param lockdown Whether the admin configured networks should be unmodifiable by the
12944      *                          user.
12945      * @throws SecurityException if caller is not a device owner or a profile owner of an
12946      *                           organization-owned managed profile.
12947      */
12948     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true)
setConfiguredNetworksLockdownState( @ullable ComponentName admin, boolean lockdown)12949     public void setConfiguredNetworksLockdownState(
12950             @Nullable ComponentName admin, boolean lockdown) {
12951         throwIfParentInstance("setConfiguredNetworksLockdownState");
12952         if (mService != null) {
12953             try {
12954                 mService.setConfiguredNetworksLockdownState(
12955                         admin, mContext.getPackageName(), lockdown);
12956             } catch (RemoteException e) {
12957                 throw e.rethrowFromSystemServer();
12958             }
12959         }
12960     }
12961 
12962     /**
12963      * Called by a device owner or a profile owner of an organization-owned managed profile to
12964      * determine whether the user is prevented from modifying networks configured by the admin.
12965      *
12966      * @param admin             admin Which {@link DeviceAdminReceiver} this request is associated
12967      *                          with.
12968      * @throws SecurityException if caller is not a device owner or a profile owner of an
12969      *                           organization-owned managed profile.
12970      */
12971     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true)
hasLockdownAdminConfiguredNetworks(@ullable ComponentName admin)12972     public boolean hasLockdownAdminConfiguredNetworks(@Nullable ComponentName admin) {
12973         throwIfParentInstance("hasLockdownAdminConfiguredNetworks");
12974         if (mService != null) {
12975             try {
12976                 return mService.hasLockdownAdminConfiguredNetworks(admin);
12977             } catch (RemoteException e) {
12978                 throw e.rethrowFromSystemServer();
12979             }
12980         }
12981         return false;
12982     }
12983 
12984     /**
12985      * Called by a device owner or a profile owner of an organization-owned managed
12986      * profile to set the system wall clock time. This only takes effect if called when
12987      * {@link android.provider.Settings.Global#AUTO_TIME} is 0, otherwise {@code false}
12988      * will be returned.
12989      *
12990      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
12991      *               caller is not a device admin.
12992      * @param millis time in milliseconds since the Epoch
12993      * @return {@code true} if set time succeeded, {@code false} otherwise.
12994      * @throws SecurityException if {@code admin} is not a device owner or a profile owner
12995      * of an organization-owned managed profile.
12996      */
12997     @RequiresPermission(value = SET_TIME, conditional = true)
setTime(@ullable ComponentName admin, long millis)12998     public boolean setTime(@Nullable ComponentName admin, long millis) {
12999         throwIfParentInstance("setTime");
13000         if (mService != null) {
13001             try {
13002                 return mService.setTime(admin, mContext.getPackageName(), millis);
13003             } catch (RemoteException e) {
13004                 throw e.rethrowFromSystemServer();
13005             }
13006         }
13007         return false;
13008     }
13009 
13010     /**
13011      * Called by a device owner or a profile owner of an organization-owned managed
13012      * profile to set the system's persistent default time zone. This only takes
13013      * effect if called when {@link android.provider.Settings.Global#AUTO_TIME_ZONE}
13014      * is 0, otherwise {@code false} will be returned.
13015      *
13016      * @see android.app.AlarmManager#setTimeZone(String)
13017      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
13018      *               caller is not a device admin.
13019      * @param timeZone one of the Olson ids from the list returned by
13020      *     {@link java.util.TimeZone#getAvailableIDs}
13021      * @return {@code true} if set timezone succeeded, {@code false} otherwise.
13022      * @throws SecurityException if {@code admin} is not a device owner or a profile owner
13023      * of an organization-owned managed profile.
13024      */
13025     @RequiresPermission(value = SET_TIME_ZONE, conditional = true)
setTimeZone(@ullable ComponentName admin, String timeZone)13026     public boolean setTimeZone(@Nullable ComponentName admin, String timeZone) {
13027         throwIfParentInstance("setTimeZone");
13028         if (mService != null) {
13029             try {
13030                 return mService.setTimeZone(admin, mContext.getPackageName(), timeZone);
13031             } catch (RemoteException e) {
13032                 throw e.rethrowFromSystemServer();
13033             }
13034         }
13035         return false;
13036     }
13037 
13038     /**
13039      * Called by device owners to set the user's global location setting.
13040      *
13041      *
13042      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
13043      * @param locationEnabled whether location should be enabled or disabled. <b>Note: </b> on
13044      * {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, calls to
13045      * disable will be ignored.
13046      * @throws SecurityException if {@code admin} is not a device owner.
13047      */
setLocationEnabled(@onNull ComponentName admin, boolean locationEnabled)13048     public void setLocationEnabled(@NonNull ComponentName admin, boolean locationEnabled) {
13049         throwIfParentInstance("setLocationEnabled");
13050         if (mService != null) {
13051             try {
13052                 mService.setLocationEnabled(admin, locationEnabled);
13053             } catch (RemoteException e) {
13054                 throw e.rethrowFromSystemServer();
13055             }
13056         }
13057     }
13058 
13059     /**
13060      * This method is mostly deprecated.
13061      * Most of the settings that still have an effect have dedicated setter methods
13062      * (e.g. {@link #setLocationEnabled}) or user restrictions.
13063      * <p>
13064      *
13065      * Called by profile or device owners to update {@link android.provider.Settings.Secure}
13066      * settings. Validation that the value of the setting is in the correct form for the setting
13067      * type should be performed by the caller.
13068      * <p>
13069      * The settings that can be updated by a profile or device owner with this method are:
13070      * <ul>
13071      * <li>{@link android.provider.Settings.Secure#DEFAULT_INPUT_METHOD}</li>
13072      * <li>{@link android.provider.Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
13073      * </ul>
13074      * <p>
13075      * A device owner can additionally update the following settings:
13076      * <ul>
13077      * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}, but see note below.</li>
13078      * </ul>
13079      *
13080      * <strong>Note: Starting from Android O, apps should no longer call this method with the
13081      * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is
13082      * deprecated. Instead, device owners or profile owners should use the restriction
13083      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}.
13084      * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method
13085      * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS},
13086      * an {@link UnsupportedOperationException} is thrown.
13087      *
13088      * Starting from Android Q, the device and profile owner can also call
13089      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY} to restrict unknown sources for
13090      * all users.
13091      * </strong>
13092      *
13093      * <strong>Note: Starting from Android R, apps should no longer call this method with the
13094      * setting {@link android.provider.Settings.Secure#LOCATION_MODE}, which is deprecated. Instead,
13095      * device owners should call {@link #setLocationEnabled(ComponentName, boolean)}. This will be
13096      * enforced for all apps targeting Android R or above.
13097      * </strong>
13098      *
13099      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13100      * @param setting The name of the setting to update.
13101      * @param value The value to update the setting to.
13102      * @throws SecurityException if {@code admin} is not a device or profile owner.
13103      */
setSecureSetting(@onNull ComponentName admin, String setting, String value)13104     public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
13105         throwIfParentInstance("setSecureSetting");
13106 
13107         if (mService != null) {
13108             try {
13109                 mService.setSecureSetting(admin, setting, value);
13110             } catch (RemoteException e) {
13111                 throw e.rethrowFromSystemServer();
13112             }
13113         }
13114     }
13115 
13116     /**
13117      * Designates a specific service component as the provider for making permission requests of a
13118      * local or remote administrator of the user.
13119      * <p/>
13120      * Only a device owner or profile owner can designate the restrictions provider.
13121      *
13122      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13123      * @param provider The component name of the service that implements
13124      *            {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
13125      *            provider previously assigned.
13126      * @throws SecurityException if {@code admin} is not a device or profile owner.
13127      */
setRestrictionsProvider(@onNull ComponentName admin, @Nullable ComponentName provider)13128     public void setRestrictionsProvider(@NonNull ComponentName admin,
13129             @Nullable ComponentName provider) {
13130         throwIfParentInstance("setRestrictionsProvider");
13131         if (mService != null) {
13132             try {
13133                 mService.setRestrictionsProvider(admin, provider);
13134             } catch (RemoteException re) {
13135                 throw re.rethrowFromSystemServer();
13136             }
13137         }
13138     }
13139 
13140     /**
13141      * Called by profile or device owners to set the global volume mute on or off.
13142      * This has no effect when set on a managed profile.
13143      *
13144      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13145      * @param on {@code true} to mute global volume, {@code false} to turn mute off.
13146      * @throws SecurityException if {@code admin} is not a device or profile owner.
13147      */
setMasterVolumeMuted(@onNull ComponentName admin, boolean on)13148     public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
13149         throwIfParentInstance("setMasterVolumeMuted");
13150         if (mService != null) {
13151             try {
13152                 mService.setMasterVolumeMuted(admin, on);
13153             } catch (RemoteException re) {
13154                 throw re.rethrowFromSystemServer();
13155             }
13156         }
13157     }
13158 
13159     /**
13160      * Called by profile or device owners to check whether the global volume mute is on or off.
13161      *
13162      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13163      * @return {@code true} if global volume is muted, {@code false} if it's not.
13164      * @throws SecurityException if {@code admin} is not a device or profile owner.
13165      */
isMasterVolumeMuted(@onNull ComponentName admin)13166     public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
13167         throwIfParentInstance("isMasterVolumeMuted");
13168         if (mService != null) {
13169             try {
13170                 return mService.isMasterVolumeMuted(admin);
13171             } catch (RemoteException re) {
13172                 throw re.rethrowFromSystemServer();
13173             }
13174         }
13175         return false;
13176     }
13177 
13178     /**
13179      * Change whether a user can uninstall a package. This function can be called by a device owner,
13180      * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via
13181      * {@link #setDelegatedScopes} or holders of the permission
13182      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL}.
13183      * <p>
13184      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the set uninstall blocked
13185      * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
13186      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
13187      * successfully set or not. This callback will contain:
13188      * <ul>
13189      * <li> The policy identifier
13190      * {@link DevicePolicyIdentifiers#PACKAGE_UNINSTALL_BLOCKED_POLICY}
13191      * <li> The additional policy params bundle, which contains
13192      * {@link PolicyUpdateReceiver#EXTRA_PACKAGE_NAME} the package name the policy applies to
13193      * <li> The {@link TargetUser} that this policy relates to
13194      * <li> The {@link PolicyUpdateResult}, which will be
13195      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
13196      * reason the policy failed to be set
13197      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
13198      * </ul>
13199      * If there has been a change to the policy,
13200      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
13201      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
13202      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
13203      * will contain the reason why the policy changed.
13204      *
13205      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
13206      *               caller is not a device admin.
13207      * @param packageName package to change.
13208      * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
13209      * @throws SecurityException if {@code admin} is not a device or profile owner or holder of the
13210      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL}.
13211      * @see #setDelegatedScopes
13212      * @see #DELEGATION_BLOCK_UNINSTALL
13213      */
13214     @RequiresPermission(value = MANAGE_DEVICE_POLICY_APPS_CONTROL, conditional = true)
13215     @SupportsCoexistence
setUninstallBlocked(@ullable ComponentName admin, String packageName, boolean uninstallBlocked)13216     public void setUninstallBlocked(@Nullable ComponentName admin, String packageName,
13217             boolean uninstallBlocked) {
13218         throwIfParentInstance("setUninstallBlocked");
13219         if (mService != null) {
13220             try {
13221                 mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName,
13222                     uninstallBlocked);
13223             } catch (RemoteException re) {
13224                 throw re.rethrowFromSystemServer();
13225             }
13226         }
13227     }
13228 
13229     /**
13230      * Check whether the user has been blocked by device policy from uninstalling a package.
13231      * Requires the caller to be the profile owner if checking a specific admin's policy.
13232      * <p>
13233      * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
13234      * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
13235      * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
13236      * will cause a NullPointerException to be raised.
13237      * <p>
13238      * <strong>Note:</strong> If your app targets Android 11 (API level 30) or higher,
13239      * this method returns a filtered result. Learn more about how to
13240      * <a href="/training/basics/intents/package-visibility">manage package visibility</a>.
13241      * <p>
13242      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the returned policy will be the
13243      * current resolved policy rather than the policy set by the calling admin.
13244      *
13245      * @param admin The name of the admin component whose blocking policy will be checked, or
13246      *            {@code null} to check whether any admin has blocked the uninstallation. Starting
13247      *              from {@link android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE} admin will be
13248      *              ignored and assumed {@code null}.
13249      * @param packageName package to check.
13250      * @return true if uninstallation is blocked and the given package is visible to you, false
13251      *         otherwise if uninstallation isn't blocked or the given package isn't visible to you.
13252      * @throws SecurityException if {@code admin} is not a device or profile owner.
13253      */
isUninstallBlocked(@ullable ComponentName admin, String packageName)13254     public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
13255         throwIfParentInstance("isUninstallBlocked");
13256         if (mService != null) {
13257             try {
13258                 return mService.isUninstallBlocked(packageName);
13259             } catch (RemoteException re) {
13260                 throw re.rethrowFromSystemServer();
13261             }
13262         }
13263         return false;
13264     }
13265 
13266     /**
13267      * Called by the profile owner of a managed profile or a holder of the permission
13268      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION} to enable
13269      * widget providers from a given package to be available in the parent profile. As a result the
13270      * user will be able to add widgets from the allowlisted package running under the profile to a
13271      * widget host which runs under the parent profile, for example the home screen. Note that a
13272      * package may have zero or more provider components, where each component provides a different
13273      * widget type.
13274      * <p>
13275      * <strong>Note:</strong> By default no widget provider package is allowlisted.
13276      *
13277      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
13278      *              caller is not a device admin.
13279      * @param packageName The package from which widget providers are allowlisted.
13280      * @return Whether the package was added.
13281      * @throws SecurityException if {@code admin} is not a profile owner and not a holder of the
13282      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION}.
13283      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
13284      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
13285      */
13286     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PROFILE_INTERACTION, conditional = true)
addCrossProfileWidgetProvider(@ullable ComponentName admin, String packageName)13287     public boolean addCrossProfileWidgetProvider(@Nullable ComponentName admin,
13288             String packageName) {
13289         throwIfParentInstance("addCrossProfileWidgetProvider");
13290         if (mService != null) {
13291             try {
13292                 return mService.addCrossProfileWidgetProvider(admin,
13293                         mContext.getPackageName(), packageName);
13294             } catch (RemoteException re) {
13295                 throw re.rethrowFromSystemServer();
13296             }
13297         }
13298         return false;
13299     }
13300 
13301     /**
13302      * Called by the profile owner of a managed profile or a holder of the permission
13303      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION} to disable
13304      * widget providers from a given package to be available in the parent profile. For this method
13305      * to take effect the package should have been added via
13306      * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
13307      * <p>
13308      * <strong>Note:</strong> By default no widget provider package is allowlisted.
13309      *
13310      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
13311      *              caller is not a device admin.
13312      * @param packageName The package from which widget providers are no longer allowlisted.
13313      * @return Whether the package was removed.
13314      * @throws SecurityException if {@code admin} is not a profile owner and not a holder of the
13315      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION}.
13316      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
13317      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
13318      */
13319     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PROFILE_INTERACTION, conditional = true)
removeCrossProfileWidgetProvider(@ullable ComponentName admin, String packageName)13320     public boolean removeCrossProfileWidgetProvider(@Nullable ComponentName admin,
13321             String packageName) {
13322         throwIfParentInstance("removeCrossProfileWidgetProvider");
13323         if (mService != null) {
13324             try {
13325                 return mService.removeCrossProfileWidgetProvider(admin, mContext.getPackageName(),
13326                         packageName);
13327             } catch (RemoteException re) {
13328                 throw re.rethrowFromSystemServer();
13329             }
13330         }
13331         return false;
13332     }
13333 
13334     /**
13335      * Called by the profile owner of a managed profile or a holder of the permission
13336      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION} to query
13337      * providers from which packages are available in the parent profile.
13338      *
13339      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
13340      *              caller is not a device admin.
13341      * @return The allowlisted package list.
13342      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
13343      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
13344      * @throws SecurityException if {@code admin} is not a profile owner and not a holder of the
13345      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_PROFILE_INTERACTION}.
13346      */
13347     @RequiresPermission(value = MANAGE_DEVICE_POLICY_PROFILE_INTERACTION, conditional = true)
getCrossProfileWidgetProviders(@ullable ComponentName admin)13348     public @NonNull List<String> getCrossProfileWidgetProviders(@Nullable ComponentName admin) {
13349         throwIfParentInstance("getCrossProfileWidgetProviders");
13350         if (mService != null) {
13351             try {
13352                 List<String> providers = mService.getCrossProfileWidgetProviders(admin,
13353                         mContext.getPackageName());
13354                 if (providers != null) {
13355                     return providers;
13356                 }
13357             } catch (RemoteException re) {
13358                 throw re.rethrowFromSystemServer();
13359             }
13360         }
13361         return Collections.emptyList();
13362     }
13363 
13364     /**
13365      * Called by profile or device owners to set the user's photo.
13366      *
13367      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13368      * @param icon the bitmap to set as the photo.
13369      * @throws SecurityException if {@code admin} is not a device or profile owner.
13370      */
setUserIcon(@onNull ComponentName admin, Bitmap icon)13371     public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
13372         throwIfParentInstance("setUserIcon");
13373         try {
13374             mService.setUserIcon(admin, icon);
13375         } catch (RemoteException re) {
13376             throw re.rethrowFromSystemServer();
13377         }
13378     }
13379 
13380     /**
13381      * Called by device owners or profile owners of an organization-owned managed profile to set
13382      * a local system update policy. When a new policy is set,
13383      * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcast.
13384      * <p>
13385      * If the supplied system update policy has freeze periods set but the freeze periods do not
13386      * meet 90-day maximum length or 60-day minimum separation requirement set out in
13387      * {@link SystemUpdatePolicy#setFreezePeriods},
13388      * {@link SystemUpdatePolicy.ValidationFailedException} will the thrown. Note that the system
13389      * keeps a record of freeze periods the device experienced previously, and combines them with
13390      * the new freeze periods to be set when checking the maximum freeze length and minimum freeze
13391      * separation constraints. As a result, freeze periods that passed validation during
13392      * {@link SystemUpdatePolicy#setFreezePeriods} might fail the additional checks here due to
13393      * the freeze period history. If this is causing issues during development,
13394      * {@code adb shell dpm clear-freeze-period-record} can be used to clear the record.
13395      *
13396      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
13397      *            components in the package can set system update policies and the most
13398      *            recent policy takes effect. This should be null if the caller is not a device
13399      *              admin.
13400      * @param policy the new policy, or {@code null} to clear the current policy.
13401      * @throws SecurityException if {@code admin} is not a device owner or a profile owner of an
13402      *      organization-owned managed profile, or the caller is not permitted to set this policy
13403      * @throws IllegalArgumentException if the policy type or maintenance window is not valid.
13404      * @throws SystemUpdatePolicy.ValidationFailedException if the policy's freeze period does not
13405      *             meet the requirement.
13406      * @see SystemUpdatePolicy
13407      * @see SystemUpdatePolicy#setFreezePeriods(List)
13408      */
13409     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SYSTEM_UPDATES, conditional = true)
setSystemUpdatePolicy(@onNull ComponentName admin, SystemUpdatePolicy policy)13410     public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
13411         throwIfParentInstance("setSystemUpdatePolicy");
13412         if (mService != null) {
13413             try {
13414                 mService.setSystemUpdatePolicy(admin, mContext.getPackageName(), policy);
13415             } catch (RemoteException re) {
13416                 throw re.rethrowFromSystemServer();
13417             }
13418         }
13419     }
13420 
13421     /**
13422      * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
13423      *
13424      * @return The current policy object, or {@code null} if no policy is set.
13425      */
getSystemUpdatePolicy()13426     public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
13427         throwIfParentInstance("getSystemUpdatePolicy");
13428         if (mService != null) {
13429             try {
13430                 return mService.getSystemUpdatePolicy();
13431             } catch (RemoteException re) {
13432                 throw re.rethrowFromSystemServer();
13433             }
13434         }
13435         return null;
13436     }
13437 
13438     /**
13439      * Reset record of previous system update freeze period the device went through.
13440      * @hide
13441      */
13442     @TestApi
13443     @RequiresPermission(android.Manifest.permission.CLEAR_FREEZE_PERIOD)
clearSystemUpdatePolicyFreezePeriodRecord()13444     public void clearSystemUpdatePolicyFreezePeriodRecord() {
13445         throwIfParentInstance("clearSystemUpdatePolicyFreezePeriodRecord");
13446         if (mService == null) {
13447             return;
13448         }
13449         try {
13450             mService.clearSystemUpdatePolicyFreezePeriodRecord();
13451         } catch (RemoteException re) {
13452             throw re.rethrowFromSystemServer();
13453         }
13454     }
13455 
13456     /**
13457      * Called by a device owner or profile owner of secondary users that is affiliated with the
13458      * device to disable the keyguard altogether.
13459      * <p>
13460      * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
13461      * type. However, this call has no effect if a password, pin or pattern is currently set. If a
13462      * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
13463      * disabled.
13464      *
13465      * <p>
13466      * As of {@link android.os.Build.VERSION_CODES#P}, this call also dismisses the
13467      * keyguard if it is currently shown.
13468      *
13469      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
13470      * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
13471      * @return {@code false} if attempting to disable the keyguard while a lock password was in
13472      *         place. {@code true} otherwise.
13473      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
13474      * secondary user that is affiliated with the device.
13475      * @see #isAffiliatedUser
13476      * @see #getSecondaryUsers
13477      */
setKeyguardDisabled(@onNull ComponentName admin, boolean disabled)13478     public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
13479         throwIfParentInstance("setKeyguardDisabled");
13480         try {
13481             return mService.setKeyguardDisabled(admin, disabled);
13482         } catch (RemoteException re) {
13483             throw re.rethrowFromSystemServer();
13484         }
13485     }
13486 
13487     /**
13488      * Called by device owner or profile owner of secondary users that is affiliated with the
13489      * device to disable the status bar. Disabling the status bar blocks notifications and quick
13490      * settings.
13491      * <p>
13492      * <strong>Note:</strong> This method has no effect for LockTask mode. The behavior of the
13493      * status bar in LockTask mode can be configured with
13494      * {@link #setLockTaskFeatures(ComponentName, int)}. Calls to this method when the device is in
13495      * LockTask mode will be registered, but will only take effect when the device leaves LockTask
13496      * mode.
13497      *
13498      * <p>This policy does not have any effect while on the lock screen, where the status bar will
13499      * not be disabled. Using LockTask instead of this method is recommended.
13500      *
13501      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
13502      *              caller is not a device admin.
13503      * @param disabled {@code true} disables the status bar, {@code false} reenables it.
13504      * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
13505      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
13506      * secondary user that is affiliated with the device.
13507      * @see #isAffiliatedUser
13508      * @see #getSecondaryUsers
13509      */
13510     @RequiresPermission(value = MANAGE_DEVICE_POLICY_STATUS_BAR, conditional = true)
setStatusBarDisabled(@ullable ComponentName admin, boolean disabled)13511     public boolean setStatusBarDisabled(@Nullable ComponentName admin, boolean disabled) {
13512         throwIfParentInstance("setStatusBarDisabled");
13513         try {
13514             return mService.setStatusBarDisabled(admin, mContext.getPackageName(), disabled);
13515         } catch (RemoteException re) {
13516             throw re.rethrowFromSystemServer();
13517         }
13518     }
13519 
13520     /**
13521      * Returns whether the status bar is disabled/enabled, see {@link #setStatusBarDisabled}.
13522      *
13523      * <p>Callable by device owner or profile owner of secondary users that is affiliated with the
13524      * device owner.
13525      *
13526      * <p>This policy has no effect in LockTask mode. The behavior of the
13527      * status bar in LockTask mode can be configured with
13528      * {@link #setLockTaskFeatures(ComponentName, int)}.
13529      *
13530      * <p>This policy also does not have any effect while on the lock screen, where the status bar
13531      * will not be disabled.
13532      *
13533      * @throws SecurityException if the caller is not the device owner, or a profile owner of
13534      * secondary user that is affiliated with the device.
13535      * @see #isAffiliatedUser
13536      * @see #getSecondaryUsers
13537      */
isStatusBarDisabled()13538     public boolean isStatusBarDisabled() {
13539         throwIfParentInstance("isStatusBarDisabled");
13540         try {
13541             return mService.isStatusBarDisabled(mContext.getPackageName());
13542         } catch (RemoteException re) {
13543             throw re.rethrowFromSystemServer();
13544         }
13545     }
13546 
13547     /**
13548      * Called by the system update service to notify device and profile owners of pending system
13549      * updates.
13550      *
13551      * This method should only be used when it is unknown whether the pending system
13552      * update is a security patch. Otherwise, use
13553      * {@link #notifyPendingSystemUpdate(long, boolean)}.
13554      *
13555      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
13556      *         indicating when the current pending update was first available. {@code -1} if no
13557      *         update is available.
13558      * @see #notifyPendingSystemUpdate(long, boolean)
13559      * @hide
13560      */
13561     @SystemApi
13562     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime)13563     public void notifyPendingSystemUpdate(long updateReceivedTime) {
13564         throwIfParentInstance("notifyPendingSystemUpdate");
13565         if (mService != null) {
13566             try {
13567                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime));
13568             } catch (RemoteException re) {
13569                 throw re.rethrowFromSystemServer();
13570             }
13571         }
13572     }
13573 
13574     /**
13575      * Called by the system update service to notify device and profile owners of pending system
13576      * updates.
13577      *
13578      * This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
13579      * when it is known whether the pending system update is a security patch.
13580      *
13581      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
13582      *         indicating when the current pending update was first available. {@code -1} if no
13583      *         update is available.
13584      * @param isSecurityPatch {@code true} if this system update is purely a security patch;
13585      *         {@code false} if not.
13586      * @see #notifyPendingSystemUpdate(long)
13587      * @hide
13588      */
13589     @SystemApi
13590     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch)13591     public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) {
13592         throwIfParentInstance("notifyPendingSystemUpdate");
13593         if (mService != null) {
13594             try {
13595                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime,
13596                         isSecurityPatch));
13597             } catch (RemoteException re) {
13598                 throw re.rethrowFromSystemServer();
13599             }
13600         }
13601     }
13602 
13603     /**
13604      * Get information about a pending system update.
13605      *
13606      * Can be called by device or profile owners, and starting from Android
13607      * {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}, holders of the permission
13608      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_QUERY_SYSTEM_UPDATES}.
13609      *
13610      * @param admin Which profile or device owner this request is associated with.
13611      * @return Information about a pending system update or {@code null} if no update pending.
13612      * @throws SecurityException if {@code admin} is not a device, profile owner or holders of
13613      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_QUERY_SYSTEM_UPDATES}.
13614      * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long)
13615      */
13616     @RequiresPermission(value = MANAGE_DEVICE_POLICY_QUERY_SYSTEM_UPDATES, conditional = true)
13617     @SuppressLint("RequiresPermission")
getPendingSystemUpdate(@ullable ComponentName admin)13618     public @Nullable SystemUpdateInfo getPendingSystemUpdate(@Nullable ComponentName admin) {
13619         throwIfParentInstance("getPendingSystemUpdate");
13620         try {
13621             return mService.getPendingSystemUpdate(admin, mContext.getPackageName());
13622         } catch (RemoteException re) {
13623             throw re.rethrowFromSystemServer();
13624         }
13625     }
13626 
13627     /**
13628      * Set the default response for future runtime permission requests by applications. This
13629      * function can be called by a device owner, profile owner, or by a delegate given the
13630      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
13631      * The policy can allow for normal operation which prompts the user to grant a permission, or
13632      * can allow automatic granting or denying of runtime permission requests by an application.
13633      * This also applies to new permissions declared by app updates. When a permission is denied or
13634      * granted this way, the effect is equivalent to setting the permission * grant state via
13635      * {@link #setPermissionGrantState}.
13636      * <p/>
13637      * As this policy only acts on runtime permission requests, it only applies to applications
13638      * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
13639      *
13640      * <p>
13641      * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, an auto-grant
13642      * policy will not apply to certain sensors-related permissions on some configurations.
13643      * See {@link #setPermissionGrantState(ComponentName, String, String, int)} for the list of
13644      * permissions affected, and the behavior change for managed profiles and fully-managed
13645      * devices.
13646      *
13647      * @param admin Which profile or device owner this request is associated with.
13648      * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
13649      *            {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
13650      * @throws SecurityException if {@code admin} is not a device or profile owner.
13651      * @see #setPermissionGrantState
13652      * @see #setDelegatedScopes
13653      * @see #DELEGATION_PERMISSION_GRANT
13654      */
setPermissionPolicy(@onNull ComponentName admin, int policy)13655     public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
13656         throwIfParentInstance("setPermissionPolicy");
13657         try {
13658             mService.setPermissionPolicy(admin, mContext.getPackageName(), policy);
13659         } catch (RemoteException re) {
13660             throw re.rethrowFromSystemServer();
13661         }
13662     }
13663 
13664     /**
13665      * Returns the current runtime permission policy set by the device or profile owner. The
13666      * default is {@link #PERMISSION_POLICY_PROMPT}.
13667      *
13668      * @param admin Which profile or device owner this request is associated with.
13669      * @return the current policy for future permission requests.
13670      */
getPermissionPolicy(ComponentName admin)13671     public int getPermissionPolicy(ComponentName admin) {
13672         throwIfParentInstance("getPermissionPolicy");
13673         try {
13674             return mService.getPermissionPolicy(admin);
13675         } catch (RemoteException re) {
13676             throw re.rethrowFromSystemServer();
13677         }
13678     }
13679 
13680     /**
13681      * Sets the grant state of a runtime permission for a specific application. The state can be
13682      * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
13683      * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
13684      * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
13685      * the permission is granted and the user cannot manage it through the UI. This method can only
13686      * be called by a profile owner, device owner, or a delegate given the
13687      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
13688      * <p/>
13689      * Note that user cannot manage other permissions in the affected group through the UI
13690      * either and their granted state will be kept as the current value. Thus, it's recommended that
13691      * you set the grant state of all the permissions in the affected group.
13692      * <p/>
13693      * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
13694      * the permission. It retains the previous grant, if any.
13695      * <p/>
13696      * Device admins with a {@code targetSdkVersion} &lt; {@link android.os.Build.VERSION_CODES#Q}
13697      * cannot grant and revoke permissions for applications built with a {@code targetSdkVersion}
13698      * &lt; {@link android.os.Build.VERSION_CODES#M}.
13699      * <p/>
13700      * Admins with a {@code targetSdkVersion} &ge; {@link android.os.Build.VERSION_CODES#Q} can
13701      * grant and revoke permissions of all apps. Similar to the user revoking a permission from a
13702      * application built with a {@code targetSdkVersion} &lt;
13703      * {@link android.os.Build.VERSION_CODES#M} the app-op matching the permission is set to
13704      * {@link android.app.AppOpsManager#MODE_IGNORED}, but the permission stays granted.
13705      * <p>
13706      * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, control over
13707      * the following, sensors-related, permissions is restricted:
13708      * <ul>
13709      *    <li>Manifest.permission.ACCESS_FINE_LOCATION</li>
13710      *    <li>Manifest.permission.ACCESS_BACKGROUND_LOCATION</li>
13711      *    <li>Manifest.permission.ACCESS_COARSE_LOCATION</li>
13712      *    <li>Manifest.permission.CAMERA</li>
13713      *    <li>Manifest.permission.RECORD_AUDIO</li>
13714      *    <li>Manifest.permission.RECORD_BACKGROUND_AUDIO</li>
13715      *    <li>Manifest.permission.ACTIVITY_RECOGNITION</li>
13716      *    <li>Manifest.permission.BODY_SENSORS</li>
13717      * </ul>
13718      * <p>
13719      * A profile owner may not grant these permissions (i.e. call this method with any of the
13720      * permissions listed above and {@code grantState} of {@code #PERMISSION_GRANT_STATE_GRANTED}),
13721      * but may deny them.
13722      * <p>
13723      * A device owner, by default, may continue granting these permissions. However, for increased
13724      * user control, the admin may opt out of controlling grants for these permissions by including
13725      * {@link #EXTRA_PROVISIONING_SENSORS_PERMISSION_GRANT_OPT_OUT} in the provisioning parameters.
13726      * In that case the device owner's control will be limited to denying these permissions.
13727      * <p>
13728      * When sensor-related permissions aren't grantable due to the above cases, calling this method
13729      * to grant these permissions will silently fail, if device admins are built with
13730      * {@code targetSdkVersion} &lt; {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}. If
13731      * they are built with {@code targetSdkVersion} &gt;=
13732      * {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}, this method will throw a
13733      * {@link SecurityException}.
13734      * <p>
13735      * NOTE: On devices running {@link android.os.Build.VERSION_CODES#S} and above, control over
13736      * the following permissions are restricted for managed profile owners:
13737      * <ul>
13738      *    <li>Manifest.permission.READ_SMS</li>
13739      * </ul>
13740      * <p>
13741      * A managed profile owner may not grant these permissions (i.e. call this method with any of
13742      * the permissions listed above and {@code grantState} of
13743      * {@code #PERMISSION_GRANT_STATE_GRANTED}), but may deny them.
13744      * <p>
13745      * Attempts by the admin to grant these permissions, when the admin is restricted from doing
13746      * so, will be silently ignored (no exception will be thrown).
13747      *
13748      * Control over the following permissions are restricted for managed profile owners:
13749      * <ul>
13750      *  <li>Manifest.permission.READ_SMS</li>
13751      * </ul>
13752      * <p>
13753      * A managed profile owner may not grant these permissions (i.e. call this method with any of
13754      * the permissions listed above and {@code grantState} of
13755      * {@code #PERMISSION_GRANT_STATE_GRANTED}), but may deny them.
13756      *
13757      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
13758      *               caller is not a device admin.
13759      * @param packageName The application to grant or revoke a permission to.
13760      * @param permission The permission to grant or revoke.
13761      * @param grantState The permission grant state which is one of
13762      *            {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
13763      *            {@link #PERMISSION_GRANT_STATE_GRANTED},
13764      * @return whether the permission was successfully granted or revoked.
13765      * @throws SecurityException if {@code admin} is not a device or profile owner.
13766      * @see #PERMISSION_GRANT_STATE_DENIED
13767      * @see #PERMISSION_GRANT_STATE_DEFAULT
13768      * @see #PERMISSION_GRANT_STATE_GRANTED
13769      * @see #setDelegatedScopes
13770      * @see #DELEGATION_PERMISSION_GRANT
13771      */
13772     @RequiresPermission(value = MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS, conditional = true)
13773     @SupportsCoexistence
setPermissionGrantState(@ullable ComponentName admin, @NonNull String packageName, @NonNull String permission, @PermissionGrantState int grantState)13774     public boolean setPermissionGrantState(@Nullable ComponentName admin,
13775             @NonNull String packageName, @NonNull String permission,
13776             @PermissionGrantState int grantState) {
13777         throwIfParentInstance("setPermissionGrantState");
13778         try {
13779             CompletableFuture<Boolean> result = new CompletableFuture<>();
13780 
13781             mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName,
13782                     permission, grantState, new RemoteCallback((b) -> result.complete(b != null)));
13783 
13784             // Timeout
13785             BackgroundThread.getHandler().sendMessageDelayed(
13786                     obtainMessage(CompletableFuture::complete, result, false),
13787                     20_000);
13788 
13789             return result.get();
13790         } catch (RemoteException re) {
13791             throw re.rethrowFromSystemServer();
13792         } catch (InterruptedException | ExecutionException e) {
13793             throw new RuntimeException(e);
13794         }
13795     }
13796 
13797     /**
13798      * Returns the current grant state of a runtime permission for a specific application. This
13799      * function can be called by a device owner, profile owner, or by a delegate given the
13800      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
13801      *
13802      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
13803      *               caller is not a device admin.
13804      * @param packageName The application to check the grant state for.
13805      * @param permission The permission to check for.
13806      * @return the current grant state specified by device policy. If admins have not set a grant
13807      *         has not set a grant state, the return value is
13808      *         {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
13809      *         permission is currently granted for the package.
13810      *         <p/>
13811      *         If a grant state was set by the profile or device owner, then the return value will
13812      *         be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
13813      *         {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
13814      *         currently denied or granted.
13815      * @throws SecurityException if {@code admin} is not a device or profile owner.
13816      * @see #setPermissionGrantState(ComponentName, String, String, int)
13817      * @see PackageManager#checkPermission(String, String)
13818      * @see #setDelegatedScopes
13819      * @see #DELEGATION_PERMISSION_GRANT
13820      */
13821     @RequiresPermission(value = MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS, conditional = true)
getPermissionGrantState(@ullable ComponentName admin, @NonNull String packageName, @NonNull String permission)13822     public @PermissionGrantState int getPermissionGrantState(@Nullable ComponentName admin,
13823             @NonNull String packageName, @NonNull String permission) {
13824         throwIfParentInstance("getPermissionGrantState");
13825         try {
13826             return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName,
13827                     permission);
13828         } catch (RemoteException re) {
13829             throw re.rethrowFromSystemServer();
13830         }
13831     }
13832 
13833     /**
13834      * Returns whether it is possible for the caller to initiate provisioning of a managed profile
13835      * or device, setting itself as the device or profile owner.
13836      *
13837      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
13838      * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
13839      * @return whether provisioning a managed profile or device is possible.
13840      * @throws IllegalArgumentException if the supplied action is not valid.
13841      */
isProvisioningAllowed(@onNull String action)13842     public boolean isProvisioningAllowed(@NonNull String action) {
13843         throwIfParentInstance("isProvisioningAllowed");
13844         try {
13845             return mService.isProvisioningAllowed(action, mContext.getPackageName());
13846         } catch (RemoteException re) {
13847             throw re.rethrowFromSystemServer();
13848         }
13849     }
13850 
13851     /**
13852      * Checks whether it is possible to initiate provisioning a managed device,
13853      * profile or user, setting the given package as owner.
13854      *
13855      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
13856      *        {@link #ACTION_PROVISION_MANAGED_PROFILE}
13857      * @param packageName The package of the component that would be set as device, user, or profile
13858      *        owner.
13859      * @return An int constant value indicating whether provisioning is allowed.
13860      * @hide
13861      */
13862     @SystemApi
13863     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
13864     @ProvisioningPrecondition
checkProvisioningPrecondition( @onNull String action, @NonNull String packageName)13865     public int checkProvisioningPrecondition(
13866             @NonNull String action, @NonNull String packageName) {
13867         try {
13868             return mService.checkProvisioningPrecondition(action, packageName);
13869         } catch (RemoteException re) {
13870             throw re.rethrowFromSystemServer();
13871         }
13872     }
13873 
13874     /**
13875      * Return if this user is a managed profile of another user. An admin can become the profile
13876      * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
13877      * user with {@link #createAndManageUser}
13878      * @param admin Which profile owner this request is associated with.
13879      * @return if this user is a managed profile of another user.
13880      */
isManagedProfile(@onNull ComponentName admin)13881     public boolean isManagedProfile(@NonNull ComponentName admin) {
13882         throwIfParentInstance("isManagedProfile");
13883         try {
13884             return mService.isManagedProfile(admin);
13885         } catch (RemoteException re) {
13886             throw re.rethrowFromSystemServer();
13887         }
13888     }
13889 
13890     /**
13891      * Called by a device owner or profile owner on organization-owned device to get the MAC
13892      * address of the Wi-Fi device.
13893      *
13894      * NOTE: The MAC address returned here should only be used for inventory management and is
13895      * not likely to be the MAC address used by the device to connect to Wi-Fi networks: MAC
13896      * addresses used for scanning and connecting to Wi-Fi networks are randomized by default.
13897      * To get the randomized MAC address used, call
13898      * {@link android.net.wifi.WifiConfiguration#getRandomizedMacAddress}.
13899      *
13900      * @param admin Which admin this request is associated with. Null if the caller is not a device
13901      *              admin
13902      * @return the MAC address of the Wi-Fi device, or null when the information is not available.
13903      *         (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
13904      *         <p>
13905      *         The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
13906      * @throws SecurityException if {@code admin} is not permitted to get wifi mac addresses
13907      */
13908 //    @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true)
getWifiMacAddress(@ullable ComponentName admin)13909     public @Nullable String getWifiMacAddress(@Nullable ComponentName admin) {
13910         throwIfParentInstance("getWifiMacAddress");
13911         try {
13912             return mService.getWifiMacAddress(admin, mContext.getPackageName());
13913         } catch (RemoteException re) {
13914             throw re.rethrowFromSystemServer();
13915         }
13916     }
13917 
13918     /**
13919      * Called by device owner to reboot the device. If there is an ongoing call on the device,
13920      * throws an {@link IllegalStateException}.
13921      * @param admin Which device owner the request is associated with.
13922      * @throws IllegalStateException if device has an ongoing call.
13923      * @throws SecurityException if {@code admin} is not a device owner.
13924      * @see TelephonyManager#CALL_STATE_IDLE
13925      */
reboot(@onNull ComponentName admin)13926     public void reboot(@NonNull ComponentName admin) {
13927         throwIfParentInstance("reboot");
13928         try {
13929             mService.reboot(admin);
13930         } catch (RemoteException re) {
13931             throw re.rethrowFromSystemServer();
13932         }
13933     }
13934 
13935     /**
13936      * Called by a device admin to set the short support message. This will be displayed to the user
13937      * in settings screens where functionality has been disabled by the admin. The message should be
13938      * limited to a short statement such as "This setting is disabled by your administrator. Contact
13939      * someone@example.com for support." If the message is longer than 200 characters it may be
13940      * truncated.
13941      * <p>
13942      * If the short support message needs to be localized, it is the responsibility of the
13943      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
13944      * and set a new version of this string accordingly.
13945      *
13946      * @see #setLongSupportMessage
13947      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
13948      *               caller is not a device admin.
13949      * @param message Short message to be displayed to the user in settings or null to clear the
13950      *            existing message.
13951      * @throws SecurityException if {@code admin} is not an active administrator.
13952      */
13953     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE, conditional = true)
setShortSupportMessage(@ullable ComponentName admin, @Nullable CharSequence message)13954     public void setShortSupportMessage(@Nullable ComponentName admin,
13955             @Nullable CharSequence message) {
13956         throwIfParentInstance("setShortSupportMessage");
13957         if (mService != null) {
13958             try {
13959                 mService.setShortSupportMessage(admin, mContext.getPackageName(), message);
13960             } catch (RemoteException e) {
13961                 throw e.rethrowFromSystemServer();
13962             }
13963         }
13964     }
13965 
13966     /**
13967      * Called by a device admin or holder of the permission
13968      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE} to get the short
13969      * support message.
13970      *
13971      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
13972      *               caller is not a device admin.
13973      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
13974      *         null if no message has been set.
13975      * @throws SecurityException if {@code admin} is not an active administrator and not a holder of
13976      * the permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE}..
13977      */
13978     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE, conditional = true)
getShortSupportMessage(@ullable ComponentName admin)13979     public CharSequence getShortSupportMessage(@Nullable ComponentName admin) {
13980         throwIfParentInstance("getShortSupportMessage");
13981         if (mService != null) {
13982             try {
13983                 return mService.getShortSupportMessage(admin, mContext.getPackageName());
13984             } catch (RemoteException e) {
13985                 throw e.rethrowFromSystemServer();
13986             }
13987         }
13988         return null;
13989     }
13990 
13991     /**
13992      * Called by a device admin to set the long support message. This will be displayed to the user
13993      * in the device administrators settings screen. If the message is longer than 20000 characters
13994      * it may be truncated.
13995      * <p>
13996      * If the long support message needs to be localized, it is the responsibility of the
13997      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
13998      * and set a new version of this string accordingly.
13999      *
14000      * @see #setShortSupportMessage
14001      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
14002      * @param message Long message to be displayed to the user in settings or null to clear the
14003      *            existing message.
14004      * @throws SecurityException if {@code admin} is not an active administrator.
14005      */
setLongSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)14006     public void setLongSupportMessage(@NonNull ComponentName admin,
14007             @Nullable CharSequence message) {
14008         throwIfParentInstance("setLongSupportMessage");
14009         if (mService != null) {
14010             try {
14011                 mService.setLongSupportMessage(admin, message);
14012             } catch (RemoteException e) {
14013                 throw e.rethrowFromSystemServer();
14014             }
14015         }
14016     }
14017 
14018     /**
14019      * Called by a device admin to get the long support message.
14020      *
14021      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
14022      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
14023      *         null if no message has been set.
14024      * @throws SecurityException if {@code admin} is not an active administrator.
14025      */
getLongSupportMessage(@onNull ComponentName admin)14026     public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
14027         throwIfParentInstance("getLongSupportMessage");
14028         if (mService != null) {
14029             try {
14030                 return mService.getLongSupportMessage(admin);
14031             } catch (RemoteException e) {
14032                 throw e.rethrowFromSystemServer();
14033             }
14034         }
14035         return null;
14036     }
14037 
14038     /**
14039      * Called by the system to get the short support message.
14040      *
14041      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
14042      * @param userHandle user id the admin is running as.
14043      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
14044      *
14045      * @hide
14046      */
getShortSupportMessageForUser(@onNull ComponentName admin, int userHandle)14047     public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
14048             int userHandle) {
14049         if (mService != null) {
14050             try {
14051                 return mService.getShortSupportMessageForUser(admin, userHandle);
14052             } catch (RemoteException e) {
14053                 throw e.rethrowFromSystemServer();
14054             }
14055         }
14056         return null;
14057     }
14058 
14059 
14060     /**
14061      * Called by the system to get the long support message.
14062      *
14063      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
14064      * @param userHandle user id the admin is running as.
14065      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
14066      *
14067      * @hide
14068      */
getLongSupportMessageForUser( @onNull ComponentName admin, int userHandle)14069     public @Nullable CharSequence getLongSupportMessageForUser(
14070             @NonNull ComponentName admin, int userHandle) {
14071         if (mService != null) {
14072             try {
14073                 return mService.getLongSupportMessageForUser(admin, userHandle);
14074             } catch (RemoteException e) {
14075                 throw e.rethrowFromSystemServer();
14076             }
14077         }
14078         return null;
14079     }
14080 
14081     /**
14082      * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
14083      * whose calls act on the parent profile.
14084      *
14085      * <p>The following methods are supported for the parent instance, all other methods will
14086      * throw a SecurityException when called on the parent instance:
14087      * <ul>
14088      * <li>{@link #getPasswordQuality}</li>
14089      * <li>{@link #setPasswordQuality}</li>
14090      * <li>{@link #getPasswordMinimumLength}</li>
14091      * <li>{@link #setPasswordMinimumLength}</li>
14092      * <li>{@link #getPasswordMinimumUpperCase}</li>
14093      * <li>{@link #setPasswordMinimumUpperCase}</li>
14094      * <li>{@link #getPasswordMinimumLowerCase}</li>
14095      * <li>{@link #setPasswordMinimumLowerCase}</li>
14096      * <li>{@link #getPasswordMinimumLetters}</li>
14097      * <li>{@link #setPasswordMinimumLetters}</li>
14098      * <li>{@link #getPasswordMinimumNumeric}</li>
14099      * <li>{@link #setPasswordMinimumNumeric}</li>
14100      * <li>{@link #getPasswordMinimumSymbols}</li>
14101      * <li>{@link #setPasswordMinimumSymbols}</li>
14102      * <li>{@link #getPasswordMinimumNonLetter}</li>
14103      * <li>{@link #setPasswordMinimumNonLetter}</li>
14104      * <li>{@link #getPasswordHistoryLength}</li>
14105      * <li>{@link #setPasswordHistoryLength}</li>
14106      * <li>{@link #getPasswordExpirationTimeout}</li>
14107      * <li>{@link #setPasswordExpirationTimeout}</li>
14108      * <li>{@link #getPasswordExpiration}</li>
14109      * <li>{@link #getPasswordMaximumLength}</li>
14110      * <li>{@link #isActivePasswordSufficient}</li>
14111      * <li>{@link #getCurrentFailedPasswordAttempts}</li>
14112      * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
14113      * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
14114      * <li>{@link #getMaximumTimeToLock}</li>
14115      * <li>{@link #setMaximumTimeToLock}</li>
14116      * <li>{@link #lockNow}</li>
14117      * <li>{@link #getKeyguardDisabledFeatures}</li>
14118      * <li>{@link #setKeyguardDisabledFeatures}</li>
14119      * <li>{@link #getTrustAgentConfiguration}</li>
14120      * <li>{@link #setTrustAgentConfiguration}</li>
14121      * <li>{@link #getRequiredStrongAuthTimeout}</li>
14122      * <li>{@link #setRequiredStrongAuthTimeout}</li>
14123      * <li>{@link #getAccountTypesWithManagementDisabled}</li>
14124      * <li>{@link #setRequiredPasswordComplexity(int)} </li>
14125      * <li>{@link #getRequiredPasswordComplexity()}</li>
14126      * </ul>
14127      * <p>
14128      * The following methods are supported for the parent instance but can only be called by the
14129      * profile owner of a managed profile that was created during the device provisioning flow:
14130      * <ul>
14131      * <li>{@link #getPasswordComplexity}</li>
14132      * <li>{@link #setCameraDisabled}</li>
14133      * <li>{@link #getCameraDisabled}</li>
14134      * <li>{@link #setAccountManagementDisabled(ComponentName, String, boolean)}</li>
14135      * <li>{@link #setPermittedInputMethods}</li>
14136      * <li>{@link #getPermittedInputMethods}</li>
14137      * </ul>
14138      *
14139      * <p>The following methods can be called by the profile owner of a managed profile
14140      * on an organization-owned device:
14141      * <ul>
14142      * <li>{@link #wipeData}</li>
14143      * </ul>
14144      *
14145      * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
14146      * @throws SecurityException if {@code admin} is not a profile owner.
14147      */
getParentProfileInstance(@onNull ComponentName admin)14148     public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
14149         throwIfParentInstance("getParentProfileInstance");
14150         try {
14151             if (Flags.dmrhSetAppRestrictions()) {
14152                 UserManager um = mContext.getSystemService(UserManager.class);
14153                 if (!um.isManagedProfile()) {
14154                     throw new SecurityException("The current user does not have a parent profile.");
14155                 }
14156             } else {
14157                 if (!mService.isManagedProfile(admin)) {
14158                     throw new SecurityException("The current user does not have a parent profile.");
14159                 }
14160             }
14161             return new DevicePolicyManager(mContext, mService, true);
14162         } catch (RemoteException e) {
14163             throw e.rethrowFromSystemServer();
14164         }
14165     }
14166 
14167     /**
14168      * Called by device owner or a profile owner of an organization-owned managed profile to
14169      * control the security logging feature.
14170      *
14171      * <p> Security logs contain various information intended for security auditing purposes.
14172      * When security logging is enabled by any app other than the device owner, certain security
14173      * logs are not visible (for example personal app launch events) or they will be redacted
14174      * (for example, details of the physical volume mount events).
14175      * Please see {@link SecurityEvent} for details.
14176      *
14177      * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there
14178      * are unaffiliated secondary users or profiles on the device, regardless of whether the
14179      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
14180      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
14181      * new users as soon as possible after provisioning via {@link #setAffiliationIds}. Non device
14182      * owners are not subject to this restriction since all
14183      * privacy-sensitive events happening outside the managed profile would have been redacted
14184      * already.
14185      *
14186      * Starting from {@link Build.VERSION_CODES#VANILLA_ICE_CREAM}, after the security logging
14187      * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
14188      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
14189      * successfully set or not. This callback will contain:
14190      * <ul>
14191      * <li> The policy identifier {@link DevicePolicyIdentifiers#SECURITY_LOGGING_POLICY}
14192      * <li> The {@link TargetUser} that this policy relates to
14193      * <li> The {@link PolicyUpdateResult}, which will be
14194      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
14195      * reason the policy failed to be set
14196      * e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
14197      * </ul>
14198      * If there has been a change to the policy,
14199      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
14200      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
14201      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
14202      * will contain the reason why the policy changed.
14203      *
14204      * @param admin Which device admin this request is associated with, or {@code null}
14205      *              if called by a delegated app.
14206      * @param enabled whether security logging should be enabled or not.
14207      * @throws SecurityException if the caller is not permitted to control security logging.
14208      * @see #setAffiliationIds
14209      * @see #retrieveSecurityLogs
14210      */
14211     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SECURITY_LOGGING, conditional = true)
setSecurityLoggingEnabled(@ullable ComponentName admin, boolean enabled)14212     public void setSecurityLoggingEnabled(@Nullable ComponentName admin, boolean enabled) {
14213         throwIfParentInstance("setSecurityLoggingEnabled");
14214         try {
14215             mService.setSecurityLoggingEnabled(admin, mContext.getPackageName(), enabled);
14216         } catch (RemoteException re) {
14217             throw re.rethrowFromSystemServer();
14218         }
14219     }
14220 
14221     /**
14222      * Return whether security logging is enabled or not by the admin.
14223      *
14224      * <p>Can only be called by the device owner or a profile owner of an organization-owned
14225      * managed profile, otherwise a {@link SecurityException} will be thrown.
14226      *
14227      * @param admin Which device admin this request is associated with. Null if the caller is not
14228      *              a device admin
14229      * @return {@code true} if security logging is enabled, {@code false} otherwise.
14230      * @throws SecurityException if the caller is not allowed to control security logging.
14231      */
14232     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SECURITY_LOGGING, conditional = true)
isSecurityLoggingEnabled(@ullable ComponentName admin)14233     public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) {
14234         throwIfParentInstance("isSecurityLoggingEnabled");
14235         try {
14236             return mService.isSecurityLoggingEnabled(admin, mContext.getPackageName());
14237         } catch (RemoteException re) {
14238             throw re.rethrowFromSystemServer();
14239         }
14240     }
14241 
14242     /**
14243      * Controls whether audit logging is enabled.
14244      *
14245      * @hide
14246      */
14247     @SystemApi
14248     @FlaggedApi(FLAG_SECURITY_LOG_V2_ENABLED)
14249     @RequiresPermission(permission.MANAGE_DEVICE_POLICY_AUDIT_LOGGING)
setAuditLogEnabled(boolean enabled)14250     public void setAuditLogEnabled(boolean enabled) {
14251         throwIfParentInstance("setAuditLogEnabled");
14252         try {
14253             mService.setAuditLogEnabled(mContext.getPackageName(), enabled);
14254         } catch (RemoteException re) {
14255             re.rethrowFromSystemServer();
14256         }
14257     }
14258 
14259     /**
14260      * @return Whether audit logging is enabled.
14261      *
14262      * @hide
14263      */
14264     @SystemApi
14265     @FlaggedApi(FLAG_SECURITY_LOG_V2_ENABLED)
14266     @RequiresPermission(permission.MANAGE_DEVICE_POLICY_AUDIT_LOGGING)
isAuditLogEnabled()14267     public boolean isAuditLogEnabled() {
14268         throwIfParentInstance("isAuditLogEnabled");
14269         try {
14270             return mService.isAuditLogEnabled(mContext.getPackageName());
14271         } catch (RemoteException re) {
14272             throw re.rethrowFromSystemServer();
14273         }
14274     }
14275 
14276     /**
14277      * Sets audit log event callback. Only one callback per UID is active at any time, when a new
14278      * callback is set, the previous one is forgotten. Should only be called when audit log policy
14279      * is enforced by the caller. Disabling the policy clears the callback. Each time a new callback
14280      * is set, it will first be invoked with all the audit log events available at the time.
14281      *
14282      * @param callback The callback to invoke when new audit log events become available.
14283      * @param executor The executor through which the callback should be invoked.
14284      * @hide
14285      */
14286     @SystemApi
14287     @FlaggedApi(FLAG_SECURITY_LOG_V2_ENABLED)
14288     @RequiresPermission(permission.MANAGE_DEVICE_POLICY_AUDIT_LOGGING)
setAuditLogEventCallback( @onNull @allbackExecutor Executor executor, @NonNull Consumer<List<SecurityEvent>> callback)14289     public void setAuditLogEventCallback(
14290             @NonNull @CallbackExecutor Executor executor,
14291             @NonNull Consumer<List<SecurityEvent>> callback) {
14292         throwIfParentInstance("setAuditLogEventCallback");
14293         final IAuditLogEventsCallback wrappedCallback =
14294                 new IAuditLogEventsCallback.Stub() {
14295                     @Override
14296                     public void onNewAuditLogEvents(List<SecurityEvent> events) {
14297                         executor.execute(() -> callback.accept(events));
14298                     }
14299                 };
14300         try {
14301             mService.setAuditLogEventsCallback(mContext.getPackageName(), wrappedCallback);
14302         } catch (RemoteException re) {
14303             throw re.rethrowFromSystemServer();
14304         }
14305     }
14306 
14307     /**
14308      * Clears audit log event callback. If a callback was set previously, it may still get invoked
14309      * after this call returns if it was already scheduled.
14310      *
14311      * @hide
14312      */
14313     @SystemApi
14314     @FlaggedApi(FLAG_SECURITY_LOG_V2_ENABLED)
14315     @RequiresPermission(permission.MANAGE_DEVICE_POLICY_AUDIT_LOGGING)
clearAuditLogEventCallback()14316     public void clearAuditLogEventCallback() {
14317         throwIfParentInstance("clearAuditLogEventCallback");
14318         try {
14319             mService.setAuditLogEventsCallback(mContext.getPackageName(), null);
14320         } catch (RemoteException re) {
14321             throw re.rethrowFromSystemServer();
14322         }
14323     }
14324 
14325     /**
14326      * Called by device owner or profile owner of an organization-owned managed profile to retrieve
14327      * all new security logging entries since the last call to this API after device boots.
14328      *
14329      * <p> Access to the logs is rate limited and it will only return new logs after the admin has
14330      * been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
14331      *
14332      * <p> When called by a device owner, if there is any other user or profile on the device,
14333      * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown.
14334      * See {@link #isAffiliatedUser}.
14335      *
14336      * @param admin Which device admin this request is associated with, or {@code null}
14337      *              if called by a delegated app.
14338      * @return the new batch of security logs which is a list of {@link SecurityEvent},
14339      * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
14340      * @throws SecurityException if the caller is not allowed to access security logging,
14341      * or there is at least one profile or secondary user that is not affiliated with the device.
14342      * @see #isAffiliatedUser
14343      * @see DeviceAdminReceiver#onSecurityLogsAvailable
14344      */
14345     @SuppressLint("NullableCollection")
14346     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SECURITY_LOGGING, conditional = true)
retrieveSecurityLogs(@ullable ComponentName admin)14347     public @Nullable List<SecurityEvent> retrieveSecurityLogs(@Nullable ComponentName admin) {
14348         throwIfParentInstance("retrieveSecurityLogs");
14349         try {
14350             ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(
14351                     admin, mContext.getPackageName());
14352             if (list != null) {
14353                 return list.getList();
14354             } else {
14355                 // Rate limit exceeded.
14356                 return null;
14357             }
14358         } catch (RemoteException re) {
14359             throw re.rethrowFromSystemServer();
14360         }
14361     }
14362 
14363     /**
14364      * Makes all accumulated network logs available to DPC in a new batch.
14365      * If throttled, returns time to wait in milliseconds, otherwise 0.
14366      * @hide
14367      */
14368     @TestApi
14369     @RequiresPermission(android.Manifest.permission.FORCE_DEVICE_POLICY_MANAGER_LOGS)
forceNetworkLogs()14370     public long forceNetworkLogs() {
14371         if (mService == null) {
14372             return -1;
14373         }
14374         try {
14375             return mService.forceNetworkLogs();
14376         } catch (RemoteException re) {
14377             throw re.rethrowFromSystemServer();
14378         }
14379     }
14380 
14381     /**
14382      * Forces a batch of security logs to be fetched from logd and makes it available for DPC.
14383      * If throttled, returns time to wait in milliseconds, otherwise 0.
14384      * @hide
14385      */
14386     @TestApi
14387     @RequiresPermission(android.Manifest.permission.FORCE_DEVICE_POLICY_MANAGER_LOGS)
forceSecurityLogs()14388     public long forceSecurityLogs() {
14389         if (mService == null) {
14390             return 0;
14391         }
14392         try {
14393             return mService.forceSecurityLogs();
14394         } catch (RemoteException re) {
14395             throw re.rethrowFromSystemServer();
14396         }
14397     }
14398 
14399     /**
14400      * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
14401      * profile.
14402      *
14403      * @hide
14404      */
getParentProfileInstance(UserInfo uInfo)14405     public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
14406         mContext.checkSelfPermission(
14407                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
14408         if (!uInfo.isManagedProfile()) {
14409             throw new SecurityException("The user " + uInfo.id
14410                     + " does not have a parent profile.");
14411         }
14412         return new DevicePolicyManager(mContext, mService, true);
14413     }
14414 
14415     /**
14416      * Called by a device or profile owner to restrict packages from using metered data.
14417      *
14418      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
14419      * @param packageNames the list of package names to be restricted.
14420      * @return a list of package names which could not be restricted.
14421      * @throws SecurityException if {@code admin} is not a device or profile owner.
14422      */
setMeteredDataDisabledPackages(@onNull ComponentName admin, @NonNull List<String> packageNames)14423     public @NonNull List<String> setMeteredDataDisabledPackages(@NonNull ComponentName admin,
14424             @NonNull List<String> packageNames) {
14425         throwIfParentInstance("setMeteredDataDisabled");
14426         if (mService != null) {
14427             try {
14428                 return mService.setMeteredDataDisabledPackages(admin, packageNames);
14429             } catch (RemoteException re) {
14430                 throw re.rethrowFromSystemServer();
14431             }
14432         }
14433         return packageNames;
14434     }
14435 
14436     /**
14437      * Called by a device or profile owner to retrieve the list of packages which are restricted
14438      * by the admin from using metered data.
14439      *
14440      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
14441      * @return the list of restricted package names.
14442      * @throws SecurityException if {@code admin} is not a device or profile owner.
14443      */
getMeteredDataDisabledPackages(@onNull ComponentName admin)14444     public @NonNull List<String> getMeteredDataDisabledPackages(@NonNull ComponentName admin) {
14445         throwIfParentInstance("getMeteredDataDisabled");
14446         if (mService != null) {
14447             try {
14448                 return mService.getMeteredDataDisabledPackages(admin);
14449             } catch (RemoteException re) {
14450                 throw re.rethrowFromSystemServer();
14451             }
14452         }
14453         return new ArrayList<>();
14454     }
14455 
14456     /**
14457      * Called by the system to check if a package is restricted from using metered data
14458      * by {@param admin}.
14459      *
14460      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
14461      * @param packageName the package whose restricted status is needed.
14462      * @param userId the user to which {@param packageName} belongs.
14463      * @return {@code true} if the package is restricted by admin, otherwise {@code false}
14464      * @throws SecurityException if the caller doesn't run with {@link Process#SYSTEM_UID}
14465      * @hide
14466      */
isMeteredDataDisabledPackageForUser(@onNull ComponentName admin, String packageName, @UserIdInt int userId)14467     public boolean isMeteredDataDisabledPackageForUser(@NonNull ComponentName admin,
14468             String packageName, @UserIdInt int userId) {
14469         throwIfParentInstance("getMeteredDataDisabledForUser");
14470         if (mService != null) {
14471             try {
14472                 return mService.isMeteredDataDisabledPackageForUser(admin, packageName, userId);
14473             } catch (RemoteException re) {
14474                 throw re.rethrowFromSystemServer();
14475             }
14476         }
14477         return false;
14478     }
14479 
14480     /**
14481      * Called by device owner or profile owner of an organization-owned managed profile to retrieve
14482      * device logs from before the device's last reboot.
14483      * <p>
14484      * <strong> This API is not supported on all devices. Calling this API on unsupported devices
14485      * will result in {@code null} being returned. The device logs are retrieved from a RAM region
14486      * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
14487      * about data corruption when parsing. </strong>
14488      *
14489      * <p> When called by a device owner, if there is any other user or profile on the device,
14490      * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown.
14491      * See {@link #isAffiliatedUser}.
14492      *
14493      * @param admin Which device admin this request is associated with, or {@code null}
14494      *             if called by a delegated app.
14495      * @return Device logs from before the latest reboot of the system, or {@code null} if this API
14496      *         is not supported on the device.
14497      * @throws SecurityException if the caller is not allowed to access security logging, or
14498      * there is at least one profile or secondary user that is not affiliated with the device.
14499      * @see #isAffiliatedUser
14500      * @see #retrieveSecurityLogs
14501      */
14502     @SuppressLint("NullableCollection")
14503     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SECURITY_LOGGING, conditional = true)
retrievePreRebootSecurityLogs( @ullable ComponentName admin)14504     public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
14505             @Nullable ComponentName admin) {
14506         throwIfParentInstance("retrievePreRebootSecurityLogs");
14507         try {
14508             ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(
14509                     admin, mContext.getPackageName());
14510             if (list != null) {
14511                 return list.getList();
14512             } else {
14513                 return null;
14514             }
14515         } catch (RemoteException re) {
14516             throw re.rethrowFromSystemServer();
14517         }
14518     }
14519 
14520     /**
14521      * Called by a profile owner of a managed profile to set the color used for customization. This
14522      * color is used as background color of the confirm credentials screen for that user. The
14523      * default color is teal (#00796B).
14524      * <p>
14525      * The confirm credentials screen can be created using
14526      * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
14527      * <p>
14528      * Starting from Android R, the organization color will no longer be used as the background
14529      * color of the confirm credentials screen.
14530      *
14531      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
14532      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
14533      * @throws SecurityException if {@code admin} is not a profile owner.
14534      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
14535      * used as the background color of the confirm credentials screen.
14536      */
14537     @Deprecated
setOrganizationColor(@onNull ComponentName admin, int color)14538     public void setOrganizationColor(@NonNull ComponentName admin, int color) {
14539         throwIfParentInstance("setOrganizationColor");
14540         try {
14541             // always enforce alpha channel to have 100% opacity
14542             color |= 0xFF000000;
14543             mService.setOrganizationColor(admin, color);
14544         } catch (RemoteException re) {
14545             throw re.rethrowFromSystemServer();
14546         }
14547     }
14548 
14549     /**
14550      * @hide
14551      *
14552      * Sets the color used for customization.
14553      *
14554      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
14555      * @param userId which user to set the color to.
14556      * @RequiresPermission(allOf = {
14557      *       Manifest.permission.MANAGE_USERS,
14558      *       Manifest.permission.INTERACT_ACROSS_USERS_FULL})
14559      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
14560      * used as the background color of the confirm credentials screen.
14561      */
14562     @Deprecated
setOrganizationColorForUser(@olorInt int color, @UserIdInt int userId)14563     public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
14564         try {
14565             // always enforce alpha channel to have 100% opacity
14566             color |= 0xFF000000;
14567             mService.setOrganizationColorForUser(color, userId);
14568         } catch (RemoteException re) {
14569             throw re.rethrowFromSystemServer();
14570         }
14571     }
14572 
14573     /**
14574      * Called by a profile owner of a managed profile to retrieve the color used for customization.
14575      * This color is used as background color of the confirm credentials screen for that user.
14576      *
14577      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
14578      * @return The 24bit (0xRRGGBB) representation of the color to be used.
14579      * @throws SecurityException if {@code admin} is not a profile owner.
14580      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
14581      * used as the background color of the confirm credentials screen.
14582      */
14583     @Deprecated
getOrganizationColor(@onNull ComponentName admin)14584     public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
14585         throwIfParentInstance("getOrganizationColor");
14586         try {
14587             return mService.getOrganizationColor(admin);
14588         } catch (RemoteException re) {
14589             throw re.rethrowFromSystemServer();
14590         }
14591     }
14592 
14593     /**
14594      * @hide
14595      * Retrieve the customization color for a given user.
14596      *
14597      * @param userHandle The user id of the user we're interested in.
14598      * @return The 24bit (0xRRGGBB) representation of the color to be used.
14599      * @deprecated From {@link android.os.Build.VERSION_CODES#R}, the organization color is never
14600      * used as the background color of the confirm credentials screen.
14601      */
14602     @Deprecated
getOrganizationColorForUser(int userHandle)14603     public @ColorInt int getOrganizationColorForUser(int userHandle) {
14604         try {
14605             return mService.getOrganizationColorForUser(userHandle);
14606         } catch (RemoteException re) {
14607             throw re.rethrowFromSystemServer();
14608         }
14609     }
14610 
14611     /**
14612      * Called by the device owner (since API 26) or profile owner (since API 24) to set the name of
14613      * the organization under management.
14614      *
14615      * <p>If the organization name needs to be localized, it is the responsibility of the caller
14616      * to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast and set a new version of this
14617      * string accordingly.
14618      *
14619      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
14620      *               caller is not a device admin.
14621      * @param title The organization name or {@code null} to clear a previously set name.
14622      * @throws SecurityException if {@code admin} is not a device or profile owner.
14623      */
14624     @RequiresPermission(value = MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY, conditional = true)
setOrganizationName(@ullable ComponentName admin, @Nullable CharSequence title)14625     public void setOrganizationName(@Nullable ComponentName admin, @Nullable CharSequence title) {
14626         throwIfParentInstance("setOrganizationName");
14627         try {
14628             mService.setOrganizationName(admin, mContext.getPackageName(), title);
14629         } catch (RemoteException re) {
14630             throw re.rethrowFromSystemServer();
14631         }
14632     }
14633 
14634     /**
14635      * Called by the device owner (since API 26) or profile owner (since API 24) or holders of the
14636      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY
14637      * to retrieve the name of the organization under management.
14638      *
14639      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
14640      *               caller is not a device admin.
14641      * @return The organization name or {@code null} if none is set.
14642      * @throws SecurityException if {@code admin} if {@code admin} is not a device or profile
14643      * owner or holder of the
14644      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY}.
14645      */
14646     @RequiresPermission(value = MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY, conditional = true)
getOrganizationName(@ullable ComponentName admin)14647     public @Nullable CharSequence getOrganizationName(@Nullable ComponentName admin) {
14648         throwIfParentInstance("getOrganizationName");
14649         try {
14650             return mService.getOrganizationName(admin, mContext.getPackageName());
14651         } catch (RemoteException re) {
14652             throw re.rethrowFromSystemServer();
14653         }
14654     }
14655 
14656     private final IpcDataCache<Void, CharSequence> mGetDeviceOwnerOrganizationNameCache =
14657             new IpcDataCache(sDpmCaches.child("getDeviceOwnerOrganizationName"),
14658                     (query) -> getService().getDeviceOwnerOrganizationName());
14659 
14660     /**
14661      * Called by the system to retrieve the name of the organization managing the device.
14662      *
14663      * @return The organization name or {@code null} if none is set.
14664      * @throws SecurityException if the caller is not the device owner, does not hold the
14665      *         MANAGE_USERS permission and is not the system.
14666      *
14667      * @hide
14668      */
14669     @SystemApi
14670     @SuppressLint("RequiresPermission")
getDeviceOwnerOrganizationName()14671     public @Nullable CharSequence getDeviceOwnerOrganizationName() {
14672         return mGetDeviceOwnerOrganizationNameCache.query(null);
14673     }
14674 
14675     private final IpcDataCache<Integer, CharSequence> mGetOrganizationNameForUserCache =
14676             new IpcDataCache<>(sDpmCaches.child("getOrganizationNameForUser"),
14677                     (query) -> getService().getOrganizationNameForUser(query));
14678 
14679     /**
14680      * Retrieve the default title message used in the confirm credentials screen for a given user.
14681      *
14682      * @param userHandle The user id of the user we're interested in.
14683      * @return The organization name or {@code null} if none is set.
14684      *
14685      * @hide
14686      */
getOrganizationNameForUser(int userHandle)14687     public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
14688         return mGetOrganizationNameForUserCache.query(userHandle);
14689     }
14690 
14691     /**
14692      * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
14693      *         return {@link #STATE_USER_UNMANAGED}
14694      * @hide
14695      */
14696     @SystemApi
14697     @RequiresPermission(anyOf = {
14698             android.Manifest.permission.MANAGE_USERS,
14699             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
14700     })
14701     @UserProvisioningState
14702     @UserHandleAware(
14703             enabledSinceTargetSdkVersion = UPSIDE_DOWN_CAKE,
14704             requiresPermissionIfNotCaller = INTERACT_ACROSS_USERS)
getUserProvisioningState()14705     public int getUserProvisioningState() {
14706         throwIfParentInstance("getUserProvisioningState");
14707         if (mService != null) {
14708             try {
14709                 return mService.getUserProvisioningState(mContext.getUserId());
14710             } catch (RemoteException e) {
14711                 throw e.rethrowFromSystemServer();
14712             }
14713         }
14714         return STATE_USER_UNMANAGED;
14715     }
14716 
14717     /**
14718      * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
14719      *
14720      * @param state to store
14721      * @param userHandle for user
14722      *
14723      * @hide
14724      */
14725     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setUserProvisioningState(@serProvisioningState int state, int userHandle)14726     public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
14727         if (mService != null) {
14728             try {
14729                 mService.setUserProvisioningState(state, userHandle);
14730             } catch (RemoteException e) {
14731                 throw e.rethrowFromSystemServer();
14732             }
14733         }
14734     }
14735 
14736     /**
14737      * Set the {@link UserProvisioningState} for the supplied user. The supplied user has to be
14738      * manged, otherwise it will throw an {@link IllegalStateException}.
14739      *
14740      * <p> For managed users/profiles/devices, only the following state changes are allowed:
14741      * <ul>
14742      *     <li>{@link #STATE_USER_UNMANAGED} can change to any other state except itself
14743      *     <li>{@link #STATE_USER_SETUP_INCOMPLETE} and {@link #STATE_USER_SETUP_COMPLETE} can only
14744      *     change to {@link #STATE_USER_SETUP_FINALIZED}</li>
14745      *     <li>{@link #STATE_USER_PROFILE_COMPLETE} can only change to
14746      *     {@link #STATE_USER_PROFILE_FINALIZED}</li>
14747      *     <li>{@link #STATE_USER_SETUP_FINALIZED} can't be changed to any other state</li>
14748      *     <li>{@link #STATE_USER_PROFILE_FINALIZED} can only change to
14749      *     {@link #STATE_USER_UNMANAGED}</li>
14750      * </ul>
14751      * @param state to store
14752      * @param userHandle for user
14753      * @throws IllegalStateException if called with an invalid state change.
14754      *
14755      * @hide
14756      */
14757     @SystemApi
14758     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setUserProvisioningState( @serProvisioningState int state, @NonNull UserHandle userHandle)14759     public void setUserProvisioningState(
14760             @UserProvisioningState int state, @NonNull UserHandle userHandle) {
14761         setUserProvisioningState(state, userHandle.getIdentifier());
14762     }
14763 
14764     /**
14765      * Indicates the entity that controls the device. Two users are
14766      * affiliated if the set of ids set by the device owner and the admin of the secondary user.
14767      *
14768      * <p>A user that is affiliated with the device owner user is considered to be
14769      * affiliated with the device.
14770      *
14771      * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
14772      * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user
14773      * is created, until it becomes affiliated. Therefore it is recommended that the appropriate
14774      * affiliation ids are set by its owner as soon as possible after the user is
14775      * created.
14776      * <p>
14777      * Note: This method used to be available for affiliating device owner and profile
14778      * owner. However, since Android 11, this combination is not possible. This method is now
14779      * only useful for affiliating the primary user with managed secondary users.
14780      *
14781      * @param admin Which device owner, or owner of secondary user, this request is associated with.
14782      * @param ids A set of opaque non-empty affiliation ids.
14783      *
14784      * @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
14785      * @see #isAffiliatedUser
14786      */
setAffiliationIds(@onNull ComponentName admin, @NonNull Set<String> ids)14787     public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) {
14788         throwIfParentInstance("setAffiliationIds");
14789         if (ids == null) {
14790             throw new IllegalArgumentException("ids must not be null");
14791         }
14792         try {
14793             mService.setAffiliationIds(admin, new ArrayList<>(ids));
14794         } catch (RemoteException e) {
14795             throw e.rethrowFromSystemServer();
14796         }
14797     }
14798 
14799     /**
14800      * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
14801      * empty set if none have been set.
14802      */
getAffiliationIds(@onNull ComponentName admin)14803     public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
14804         throwIfParentInstance("getAffiliationIds");
14805         try {
14806             return new ArraySet<>(mService.getAffiliationIds(admin));
14807         } catch (RemoteException e) {
14808             throw e.rethrowFromSystemServer();
14809         }
14810     }
14811 
14812     /**
14813      * Returns whether this user is affiliated with the device.
14814      * <p>
14815      * By definition, the user that the device owner runs on is always affiliated with the device.
14816      * Any other user is considered affiliated with the device if the set specified by its
14817      * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
14818      * @see #setAffiliationIds
14819      */
isAffiliatedUser()14820     public boolean isAffiliatedUser() {
14821         throwIfParentInstance("isAffiliatedUser");
14822         try {
14823             return mService.isCallingUserAffiliated();
14824         } catch (RemoteException e) {
14825             throw e.rethrowFromSystemServer();
14826         }
14827     }
14828 
14829     /**
14830      * @hide
14831      * Returns whether target user is affiliated with the device.
14832      */
isAffiliatedUser(@serIdInt int userId)14833     public boolean isAffiliatedUser(@UserIdInt int userId) {
14834         try {
14835             return mService.isAffiliatedUser(userId);
14836         } catch (RemoteException e) {
14837             throw e.rethrowFromSystemServer();
14838         }
14839     }
14840 
14841     /**
14842      * @hide
14843      * Returns whether the uninstall for {@code packageName} for the current user is in queue
14844      * to be started
14845      * @param packageName the package to check for
14846      * @return whether the uninstall intent for {@code packageName} is pending
14847      */
isUninstallInQueue(String packageName)14848     public boolean isUninstallInQueue(String packageName) {
14849         try {
14850             return mService.isUninstallInQueue(packageName);
14851         } catch (RemoteException re) {
14852             throw re.rethrowFromSystemServer();
14853         }
14854     }
14855 
14856     /**
14857      * @hide
14858      * @param packageName the package containing active DAs to be uninstalled
14859      */
uninstallPackageWithActiveAdmins(String packageName)14860     public void uninstallPackageWithActiveAdmins(String packageName) {
14861         try {
14862             mService.uninstallPackageWithActiveAdmins(packageName);
14863         } catch (RemoteException re) {
14864             throw re.rethrowFromSystemServer();
14865         }
14866     }
14867 
14868     /**
14869      * @hide
14870      * Remove a test admin synchronously without sending it a broadcast about being removed.
14871      * If the admin is a profile owner or device owner it will still be removed.
14872      *
14873      * @param userHandle user id to remove the admin for.
14874      * @param admin The administration compononent to remove.
14875      * @throws SecurityException if the caller is not shell / root or the admin package
14876      *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
14877      */
14878     @TestApi
14879     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
forceRemoveActiveAdmin( @onNull ComponentName adminReceiver, @UserIdInt int userHandle)14880     public void forceRemoveActiveAdmin(
14881             @NonNull ComponentName adminReceiver, @UserIdInt int userHandle) {
14882         try {
14883             mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
14884         } catch (RemoteException re) {
14885             throw re.rethrowFromSystemServer();
14886         }
14887     }
14888 
14889     /**
14890      * Returns whether the device has been provisioned.
14891      *
14892      * <p>Not for use by third-party applications.
14893      *
14894      * @hide
14895      */
14896     @SystemApi
14897     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioned()14898     public boolean isDeviceProvisioned() {
14899         try {
14900             return mService.isDeviceProvisioned();
14901         } catch (RemoteException re) {
14902             throw re.rethrowFromSystemServer();
14903         }
14904     }
14905 
14906     /**
14907       * Writes that the provisioning configuration has been applied.
14908       *
14909       * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
14910       * permission.
14911       *
14912       * <p>Not for use by third-party applications.
14913       *
14914       * @hide
14915       */
14916     @SystemApi
14917     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
setDeviceProvisioningConfigApplied()14918     public void setDeviceProvisioningConfigApplied() {
14919         try {
14920             mService.setDeviceProvisioningConfigApplied();
14921         } catch (RemoteException re) {
14922             throw re.rethrowFromSystemServer();
14923         }
14924     }
14925 
14926     /**
14927      * Returns whether the provisioning configuration has been applied.
14928      *
14929      * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
14930      *
14931      * <p>Not for use by third-party applications.
14932      *
14933      * @return whether the provisioning configuration has been applied.
14934      *
14935      * @hide
14936      */
14937     @SystemApi
14938     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioningConfigApplied()14939     public boolean isDeviceProvisioningConfigApplied() {
14940         try {
14941             return mService.isDeviceProvisioningConfigApplied();
14942         } catch (RemoteException re) {
14943             throw re.rethrowFromSystemServer();
14944         }
14945     }
14946 
14947     /**
14948      * @hide
14949      * Force update user setup completed status for the given {@code userId}.
14950      * @throws {@link SecurityException} if the caller has no
14951      *         {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS}.
14952      */
14953     @TestApi
forceUpdateUserSetupComplete(@serIdInt int userId)14954     public void forceUpdateUserSetupComplete(@UserIdInt int userId) {
14955         try {
14956             mService.forceUpdateUserSetupComplete(userId);
14957         } catch (RemoteException re) {
14958             throw re.rethrowFromSystemServer();
14959         }
14960     }
14961 
14962     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
throwIfParentInstance(String functionName)14963     private void throwIfParentInstance(String functionName) {
14964         if (mParentInstance) {
14965             throw new SecurityException(functionName + " cannot be called on the parent instance");
14966         }
14967     }
14968 
14969     /**
14970      * Allows the device owner or profile owner to enable or disable the backup service.
14971      *
14972      * <p> Each user has its own backup service which manages the backup and restore mechanisms in
14973      * that user. Disabling the backup service will prevent data from being backed up or restored.
14974      *
14975      * <p> Device owner calls this API to control backup services across all users on the device.
14976      * Profile owner can use this API to enable or disable the profile's backup service. However,
14977      * for a managed profile its backup functionality is only enabled if both the device owner
14978      * and the profile owner have enabled the backup service.
14979      *
14980      * <p> By default, backup service is disabled on a device with device owner, and within a
14981      * managed profile.
14982      *
14983      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
14984      * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
14985      * @throws SecurityException if {@code admin} is not a device owner or a profile owner.
14986      */
setBackupServiceEnabled(@onNull ComponentName admin, boolean enabled)14987     public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
14988         throwIfParentInstance("setBackupServiceEnabled");
14989         try {
14990             mService.setBackupServiceEnabled(admin, enabled);
14991         } catch (RemoteException re) {
14992             throw re.rethrowFromSystemServer();
14993         }
14994     }
14995 
14996     /**
14997      * Return whether the backup service is enabled by the device owner or profile owner for the
14998      * current user, as previously set by {@link #setBackupServiceEnabled(ComponentName, boolean)}.
14999      *
15000      * <p> Whether the backup functionality is actually enabled or not depends on settings from both
15001      * the current user and the device owner, please see
15002      * {@link #setBackupServiceEnabled(ComponentName, boolean)} for details.
15003      *
15004      * <p> Backup service manages all backup and restore mechanisms on the device.
15005      *
15006      * @return {@code true} if backup service is enabled, {@code false} otherwise.
15007      * @see #setBackupServiceEnabled
15008      */
isBackupServiceEnabled(@onNull ComponentName admin)15009     public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
15010         throwIfParentInstance("isBackupServiceEnabled");
15011         try {
15012             return mService.isBackupServiceEnabled(admin);
15013         } catch (RemoteException re) {
15014             throw re.rethrowFromSystemServer();
15015         }
15016     }
15017 
15018     /**
15019      * Called by a device owner, profile owner of a managed profile or delegated app with
15020      * {@link #DELEGATION_NETWORK_LOGGING} to control the network logging feature.
15021      *
15022      * <p> Supported for a device owner from Android 8 and a delegated app granted by a device
15023      * owner from Android 10. Supported for a profile owner of a managed profile and a delegated
15024      * app granted by a profile owner from Android 12. When network logging is enabled by a
15025      * profile owner, the network logs will only include work profile network activity, not
15026      * activity on the personal profile.
15027      *
15028      * <p> Network logs contain DNS lookup and connect() library call events. The following library
15029      *     functions are recorded while network logging is active:
15030      *     <ul>
15031      *       <li>{@code getaddrinfo()}</li>
15032      *       <li>{@code gethostbyname()}</li>
15033      *       <li>{@code connect()}</li>
15034      *     </ul>
15035      *
15036      * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
15037      *     full system call logging; event reporting is enabled by default for all processes but not
15038      *     strongly enforced.
15039      *     Events from applications using alternative implementations of libc, making direct kernel
15040      *     calls, or deliberately obfuscating traffic may not be recorded.
15041      *
15042      * <p> Some common network events may not be reported. For example:
15043      *     <ul>
15044      *       <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
15045      *           an alternative system for name resolution, and so avoid calling
15046      *           {@code getaddrinfo()} or {@code gethostbyname}.</li>
15047      *       <li>Applications may use datagram sockets for performance reasons, for example
15048      *           for a game client. Calling {@code connect()} is unnecessary for this kind of
15049      *           socket, so it will not trigger a network event.</li>
15050      *     </ul>
15051      *
15052      * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
15053      *     always-on VPN service.
15054      *     See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
15055      *     and {@link android.net.VpnService} for details.
15056      *
15057      * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
15058      * are unaffiliated secondary users or profiles on the device, regardless of whether the
15059      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
15060      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
15061      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
15062      *
15063      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
15064      *        {@code null} if called by a delegated app.
15065      * @param enabled whether network logging should be enabled or not.
15066      * @throws SecurityException if {@code admin} is not a device owner or profile owner.
15067      * @see #setAffiliationIds
15068      * @see #retrieveNetworkLogs
15069      */
setNetworkLoggingEnabled(@ullable ComponentName admin, boolean enabled)15070     public void setNetworkLoggingEnabled(@Nullable ComponentName admin, boolean enabled) {
15071         throwIfParentInstance("setNetworkLoggingEnabled");
15072         try {
15073             mService.setNetworkLoggingEnabled(admin, mContext.getPackageName(), enabled);
15074         } catch (RemoteException re) {
15075             throw re.rethrowFromSystemServer();
15076         }
15077     }
15078 
15079     private IpcDataCache<ComponentName, Boolean> mIsNetworkLoggingEnabledCache =
15080             new IpcDataCache<>(sDpmCaches.child("isNetworkLoggingEnabled"),
15081                     (admin) -> getService().isNetworkLoggingEnabled(admin,
15082                             getContext().getPackageName()));
15083 
15084     /**
15085      * Return whether network logging is enabled by a device owner or profile owner of
15086      * a managed profile.
15087      *
15088      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
15089      * be {@code null} if the caller is a delegated app with {@link #DELEGATION_NETWORK_LOGGING}
15090      * or has MANAGE_USERS permission.
15091      * @return {@code true} if network logging is enabled by device owner or profile owner,
15092      * {@code false} otherwise.
15093      * @throws SecurityException if {@code admin} is not a device owner or profile owner and
15094      * caller has no MANAGE_USERS permission
15095      */
isNetworkLoggingEnabled(@ullable ComponentName admin)15096     public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
15097         throwIfParentInstance("isNetworkLoggingEnabled");
15098         return mIsNetworkLoggingEnabledCache.query(admin);
15099     }
15100 
15101     /**
15102      * Called by device owner, profile owner of a managed profile or delegated app with
15103      * {@link #DELEGATION_NETWORK_LOGGING} to retrieve the most recent batch of
15104      * network logging events.
15105      *
15106      * <p> When network logging is enabled by a profile owner, the network logs will only include
15107      * work profile network activity, not activity on the personal profile.
15108      *
15109      * A device owner or profile owner has to provide a batchToken provided as part of
15110      * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
15111      * token of the most recent available batch of logs, {@code null} will be returned.
15112      *
15113      * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
15114      *
15115      * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
15116      *
15117      * <p> Access to the logs is rate limited and this method will only return a new batch of logs
15118      * after the device device owner has been notified via
15119      * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
15120      *
15121      * <p>If the caller is not a profile owner and a secondary user or profile is created, calling
15122      * this method will throw a {@link SecurityException} until all users become affiliated again.
15123      * It will also no longer be possible to retrieve the network logs batch with the most recent
15124      * batchToken provided by {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
15125      * See {@link DevicePolicyManager#setAffiliationIds}.
15126      *
15127      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
15128      *        {@code null} if called by a delegated app.
15129      * @param batchToken A token of the batch to retrieve
15130      * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
15131      *        {@code null} if the batch represented by batchToken is no longer available or if
15132      *        logging is disabled.
15133      * @throws SecurityException if {@code admin} is not a device owner, profile owner or if the
15134      * {@code admin} is not a profile owner and there is at least one profile or secondary user
15135      * that is not affiliated with the device.
15136      * @see #setAffiliationIds
15137      * @see DeviceAdminReceiver#onNetworkLogsAvailable
15138      */
retrieveNetworkLogs(@ullable ComponentName admin, long batchToken)15139     public @Nullable List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin,
15140             long batchToken) {
15141         throwIfParentInstance("retrieveNetworkLogs");
15142         try {
15143             return mService.retrieveNetworkLogs(admin, mContext.getPackageName(), batchToken);
15144         } catch (RemoteException re) {
15145             throw re.rethrowFromSystemServer();
15146         }
15147     }
15148 
15149     /**
15150      * Called by a device owner to bind to a service from a secondary managed user or vice versa.
15151      * See {@link #getBindDeviceAdminTargetUsers} for the pre-requirements of a
15152      * device owner to bind to services of another managed user.
15153      * <p>
15154      * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
15155      * Note that the {@link Context} used to obtain this
15156      * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
15157      * to bind to the {@link android.app.Service}.
15158      * <p>
15159      * Note: This method used to be available for communication between device owner and profile
15160      * owner. However, since Android 11, this combination is not possible. This method is now
15161      * only useful for communication between device owner and managed secondary users.
15162      *
15163      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
15164      * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
15165      *        explicit component name or a package name to match an
15166      *        {@link IntentFilter} published by a service.
15167      * @param conn Receives information as the service is started and stopped in main thread. This
15168      *        must be a valid {@link ServiceConnection} object; it must not be {@code null}.
15169      * @param flags Operation options for the binding operation. See
15170      *        {@link Context#bindService(Intent, ServiceConnection, int)}.
15171      * @param targetUser Which user to bind to. Must be one of the users returned by
15172      *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
15173      *        be thrown.
15174      * @return If you have successfully bound to the service, {@code true} is returned;
15175      *         {@code false} is returned if the connection is not made and you will not
15176      *         receive the service object.
15177      *
15178      * @see Context#bindService(Intent, ServiceConnection, int)
15179      * @see #getBindDeviceAdminTargetUsers(ComponentName)
15180      */
bindDeviceAdminServiceAsUser(@onNull ComponentName admin, @NonNull Intent serviceIntent, @NonNull ServiceConnection conn, @Context.BindServiceFlagsBits int flags, @NonNull UserHandle targetUser)15181     public boolean bindDeviceAdminServiceAsUser(@NonNull ComponentName admin,
15182             @NonNull Intent serviceIntent, @NonNull ServiceConnection conn,
15183             @Context.BindServiceFlagsBits int flags, @NonNull UserHandle targetUser) {
15184         throwIfParentInstance("bindDeviceAdminServiceAsUser");
15185         // Keep this in sync with ContextImpl.bindServiceCommon.
15186         try {
15187             final IServiceConnection sd = mContext.getServiceDispatcher(
15188                     conn, mContext.getMainThreadHandler(), Integer.toUnsignedLong(flags));
15189             serviceIntent.prepareToLeaveProcess(mContext);
15190             return mService.bindDeviceAdminServiceAsUser(admin,
15191                     mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
15192                     sd, Integer.toUnsignedLong(flags), targetUser.getIdentifier());
15193         } catch (RemoteException re) {
15194             throw re.rethrowFromSystemServer();
15195         }
15196     }
15197 
15198     /**
15199      * See {@link #bindDeviceAdminServiceAsUser(ComponentName, Intent, ServiceConnection, int,
15200      *       UserHandle)}.
15201      * Call {@link Context.BindServiceFlags#of(long)} to obtain a BindServiceFlags object.
15202      */
bindDeviceAdminServiceAsUser(@onNull ComponentName admin, @NonNull Intent serviceIntent, @NonNull ServiceConnection conn, @NonNull Context.BindServiceFlags flags, @NonNull UserHandle targetUser)15203     public boolean bindDeviceAdminServiceAsUser(@NonNull ComponentName admin,
15204             @NonNull Intent serviceIntent, @NonNull ServiceConnection conn,
15205             @NonNull Context.BindServiceFlags flags, @NonNull UserHandle targetUser) {
15206         throwIfParentInstance("bindDeviceAdminServiceAsUser");
15207         // Keep this in sync with ContextImpl.bindServiceCommon.
15208         try {
15209             final IServiceConnection sd = mContext.getServiceDispatcher(
15210                     conn, mContext.getMainThreadHandler(), flags.getValue());
15211             serviceIntent.prepareToLeaveProcess(mContext);
15212             return mService.bindDeviceAdminServiceAsUser(admin,
15213                     mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
15214                     sd, flags.getValue(), targetUser.getIdentifier());
15215         } catch (RemoteException re) {
15216             throw re.rethrowFromSystemServer();
15217         }
15218     }
15219 
15220     /**
15221      * Returns the list of target users that the calling device owner or owner of secondary user
15222      * can use when calling {@link #bindDeviceAdminServiceAsUser}.
15223      * <p>
15224      * A device owner can bind to a service from a secondary managed user and vice versa, provided
15225      * that both users are affiliated. See {@link #setAffiliationIds}.
15226      */
getBindDeviceAdminTargetUsers(@onNull ComponentName admin)15227     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
15228         throwIfParentInstance("getBindDeviceAdminTargetUsers");
15229         try {
15230             return mService.getBindDeviceAdminTargetUsers(admin);
15231         } catch (RemoteException re) {
15232             throw re.rethrowFromSystemServer();
15233         }
15234     }
15235 
15236     /**
15237      * Called by the system to get the time at which the device owner last retrieved security
15238      * logging entries.
15239      *
15240      * @return the time at which the device owner most recently retrieved security logging entries,
15241      *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
15242      * @throws SecurityException if the caller is not the device owner, does not hold the
15243      *         MANAGE_USERS permission and is not the system.
15244      *
15245      * @hide
15246      */
15247     @TestApi
getLastSecurityLogRetrievalTime()15248     public long getLastSecurityLogRetrievalTime() {
15249         try {
15250             return mService.getLastSecurityLogRetrievalTime();
15251         } catch (RemoteException re) {
15252             throw re.rethrowFromSystemServer();
15253         }
15254     }
15255 
15256     /**
15257      * Called by the system to get the time at which the device owner last requested a bug report.
15258      *
15259      * @return the time at which the device owner most recently requested a bug report, in
15260      *         milliseconds since epoch; -1 if a bug report was never requested.
15261      * @throws SecurityException if the caller is not the device owner, does not hold the
15262      *         MANAGE_USERS permission and is not the system.
15263      *
15264      * @hide
15265      */
15266     @TestApi
getLastBugReportRequestTime()15267     public long getLastBugReportRequestTime() {
15268         try {
15269             return mService.getLastBugReportRequestTime();
15270         } catch (RemoteException re) {
15271             throw re.rethrowFromSystemServer();
15272         }
15273     }
15274 
15275     /**
15276      * Called by the system to get the time at which the device owner or profile owner of a
15277      * managed profile last retrieved network logging events.
15278      *
15279      * @return the time at which the device owner or profile owner most recently retrieved network
15280      *         logging events, in milliseconds since epoch; -1 if network logging events were
15281      *         never retrieved.
15282      * @throws SecurityException if the caller is not the device owner, does not hold the
15283      *         MANAGE_USERS permission and is not the system.
15284      *
15285      * @hide
15286      */
15287     @TestApi
getLastNetworkLogRetrievalTime()15288     public long getLastNetworkLogRetrievalTime() {
15289         try {
15290             return mService.getLastNetworkLogRetrievalTime();
15291         } catch (RemoteException re) {
15292             throw re.rethrowFromSystemServer();
15293         }
15294     }
15295 
15296     /**
15297      * Returns true if the current user's IME was set by an admin.
15298      *
15299      * <p>Requires the caller to be the system server, a device owner or profile owner, or a holder
15300      * of the QUERY_ADMIN_POLICY permission.
15301      *
15302      * @throws SecurityException if the caller is not authorized
15303      *
15304      * @hide
15305      */
15306     @TestApi
isCurrentInputMethodSetByOwner()15307     public boolean isCurrentInputMethodSetByOwner() {
15308         try {
15309             return mService.isCurrentInputMethodSetByOwner();
15310         } catch (RemoteException re) {
15311             throw re.rethrowFromSystemServer();
15312         }
15313     }
15314 
15315     /**
15316      * Called by the system to get a list of CA certificates that were installed by the device or
15317      * profile owner.
15318      *
15319      * <p> The caller must be the target user's device owner/profile Owner or hold the
15320      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
15321      *
15322      * @param user The user for whom to retrieve information.
15323      * @return list of aliases identifying CA certificates installed by the device or profile owner
15324      * @throws SecurityException if the caller does not have permission to retrieve information
15325      *         about the given user's CA certificates.
15326      *
15327      * @hide
15328      */
15329     @TestApi
getOwnerInstalledCaCerts(@onNull UserHandle user)15330     public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
15331         try {
15332             return mService.getOwnerInstalledCaCerts(user).getList();
15333         } catch (RemoteException re) {
15334             throw re.rethrowFromSystemServer();
15335         }
15336     }
15337 
15338     /**
15339      * Returns whether factory reset protection policy is supported on the device.
15340      *
15341      * @return {@code true} if the device support factory reset protection policy.
15342      *
15343      * @hide
15344      */
15345     @TestApi
isFactoryResetProtectionPolicySupported()15346     public boolean isFactoryResetProtectionPolicySupported() {
15347         try {
15348             return mService.isFactoryResetProtectionPolicySupported();
15349         } catch (RemoteException re) {
15350             throw re.rethrowFromSystemServer();
15351         }
15352     }
15353 
15354     /**
15355      * Called by the device owner or profile owner to clear application user data of a given
15356      * package. The behaviour of this is equivalent to the target application calling
15357      * {@link android.app.ActivityManager#clearApplicationUserData()}.
15358      *
15359      * <p><strong>Note:</strong> an application can store data outside of its application data, e.g.
15360      * external storage or user dictionary. This data will not be wiped by calling this API.
15361      *
15362      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
15363      * @param packageName The name of the package which will have its user data wiped.
15364      * @param executor The executor through which the listener should be invoked.
15365      * @param listener A callback object that will inform the caller when the clearing is done.
15366      * @throws SecurityException if the caller is not the device owner/profile owner.
15367      */
clearApplicationUserData(@onNull ComponentName admin, @NonNull String packageName, @NonNull @CallbackExecutor Executor executor, @NonNull OnClearApplicationUserDataListener listener)15368     public void clearApplicationUserData(@NonNull ComponentName admin,
15369             @NonNull String packageName, @NonNull @CallbackExecutor Executor executor,
15370             @NonNull OnClearApplicationUserDataListener listener) {
15371         throwIfParentInstance("clearAppData");
15372         Objects.requireNonNull(executor);
15373         Objects.requireNonNull(listener);
15374         try {
15375             mService.clearApplicationUserData(admin, packageName,
15376                     new IPackageDataObserver.Stub() {
15377                         public void onRemoveCompleted(String pkg, boolean succeeded) {
15378                             executor.execute(() ->
15379                                     listener.onApplicationUserDataCleared(pkg, succeeded));
15380                         }
15381                     });
15382         } catch (RemoteException re) {
15383             throw re.rethrowFromSystemServer();
15384         }
15385     }
15386 
15387     /**
15388      * Called by a device owner to specify whether logout is enabled for all secondary users. The
15389      * system may show a logout button that stops the user and switches back to the primary user.
15390      *
15391      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
15392      * @param enabled whether logout should be enabled or not.
15393      * @throws SecurityException if {@code admin} is not a device owner.
15394      */
setLogoutEnabled(@onNull ComponentName admin, boolean enabled)15395     public void setLogoutEnabled(@NonNull ComponentName admin, boolean enabled) {
15396         throwIfParentInstance("setLogoutEnabled");
15397         try {
15398             mService.setLogoutEnabled(admin, enabled);
15399         } catch (RemoteException re) {
15400             throw re.rethrowFromSystemServer();
15401         }
15402     }
15403 
15404     /**
15405      * Returns whether logout is enabled by a device owner.
15406      *
15407      * @return {@code true} if logout is enabled by device owner, {@code false} otherwise.
15408      */
isLogoutEnabled()15409     public boolean isLogoutEnabled() {
15410         throwIfParentInstance("isLogoutEnabled");
15411         try {
15412             return mService.isLogoutEnabled();
15413         } catch (RemoteException re) {
15414             throw re.rethrowFromSystemServer();
15415         }
15416     }
15417 
15418     /**
15419      * Callback used in {@link #clearApplicationUserData}
15420      * to indicate that the clearing of an application's user data is done.
15421      */
15422     public interface OnClearApplicationUserDataListener {
15423         /**
15424          * Method invoked when clearing the application user data has completed.
15425          *
15426          * @param packageName The name of the package which had its user data cleared.
15427          * @param succeeded Whether the clearing succeeded. Clearing fails for device administrator
15428          *                  apps and protected system packages.
15429          */
onApplicationUserDataCleared(String packageName, boolean succeeded)15430         void onApplicationUserDataCleared(String packageName, boolean succeeded);
15431     }
15432 
15433     /**
15434      * Returns set of system apps that should be removed during provisioning.
15435      *
15436      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
15437      * @param userId ID of the user to be provisioned.
15438      * @param provisioningAction action indicating type of provisioning, should be one of
15439      * {@link #ACTION_PROVISION_MANAGED_DEVICE}, {@link #ACTION_PROVISION_MANAGED_PROFILE} or
15440      * {@link #ACTION_PROVISION_MANAGED_USER}.
15441      *
15442      * @hide
15443      */
15444     @TestApi
getDisallowedSystemApps(@onNull ComponentName admin, @UserIdInt int userId, @NonNull String provisioningAction)15445     public @NonNull Set<String> getDisallowedSystemApps(@NonNull ComponentName admin,
15446             @UserIdInt int userId, @NonNull String provisioningAction) {
15447         try {
15448             return new ArraySet<>(
15449                     mService.getDisallowedSystemApps(admin, userId, provisioningAction));
15450         } catch (RemoteException re) {
15451             throw re.rethrowFromSystemServer();
15452         }
15453     }
15454 
15455     /**
15456      * Changes the current administrator to another one. All policies from the current
15457      * administrator are migrated to the new administrator. The whole operation is atomic -
15458      * the transfer is either complete or not done at all.
15459      *
15460      * <p>Depending on the current administrator (device owner, profile owner), you have the
15461      * following expected behaviour:
15462      * <ul>
15463      *     <li>A device owner can only be transferred to a new device owner</li>
15464      *     <li>A profile owner can only be transferred to a new profile owner</li>
15465      * </ul>
15466      *
15467      * <p>Use the {@code bundle} parameter to pass data to the new administrator. The data
15468      * will be received in the
15469      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}
15470      * callback of the new administrator.
15471      *
15472      * <p>The transfer has failed if the original administrator is still the corresponding owner
15473      * after calling this method.
15474      *
15475      * <p>The incoming target administrator must have the
15476      * <code>&lt;support-transfer-ownership /&gt;</code> tag inside the
15477      * <code>&lt;device-admin&gt;&lt;/device-admin&gt;</code> tags in the xml file referenced by
15478      * {@link DeviceAdminReceiver#DEVICE_ADMIN_META_DATA}. Otherwise an
15479      * {@link IllegalArgumentException} will be thrown.
15480      *
15481      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15482      * @param target which {@link DeviceAdminReceiver} we want the new administrator to be.
15483      * @param bundle data to be sent to the new administrator.
15484      * @throws SecurityException if {@code admin} is not a device owner nor a profile owner.
15485      * @throws IllegalArgumentException if {@code admin} or {@code target} is {@code null}, they
15486      * are components in the same package or {@code target} is not an active admin.
15487      */
transferOwnership(@onNull ComponentName admin, @NonNull ComponentName target, @Nullable PersistableBundle bundle)15488     public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
15489             @Nullable PersistableBundle bundle) {
15490         throwIfParentInstance("transferOwnership");
15491         try {
15492             mService.transferOwnership(admin, target, bundle);
15493         } catch (RemoteException re) {
15494             throw re.rethrowFromSystemServer();
15495         }
15496     }
15497 
15498     /**
15499      * Called by a device owner to specify the user session start message. This may be displayed
15500      * during a user switch.
15501      * <p>
15502      * The message should be limited to a short statement or it may be truncated.
15503      * <p>
15504      * If the message needs to be localized, it is the responsibility of the
15505      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
15506      * and set a new version of this message accordingly.
15507      *
15508      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15509      * @param startUserSessionMessage message for starting user session, or {@code null} to use
15510      * system default message.
15511      * @throws SecurityException if {@code admin} is not a device owner.
15512      */
setStartUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence startUserSessionMessage)15513     public void setStartUserSessionMessage(
15514             @NonNull ComponentName admin, @Nullable CharSequence startUserSessionMessage) {
15515         throwIfParentInstance("setStartUserSessionMessage");
15516         try {
15517             mService.setStartUserSessionMessage(admin, startUserSessionMessage);
15518         } catch (RemoteException re) {
15519             throw re.rethrowFromSystemServer();
15520         }
15521     }
15522 
15523     /**
15524      * Called by a device owner to specify the user session end message. This may be displayed
15525      * during a user switch.
15526      * <p>
15527      * The message should be limited to a short statement or it may be truncated.
15528      * <p>
15529      * If the message needs to be localized, it is the responsibility of the
15530      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
15531      * and set a new version of this message accordingly.
15532      *
15533      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15534      * @param endUserSessionMessage message for ending user session, or {@code null} to use system
15535      * default message.
15536      * @throws SecurityException if {@code admin} is not a device owner.
15537      */
setEndUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence endUserSessionMessage)15538     public void setEndUserSessionMessage(
15539             @NonNull ComponentName admin, @Nullable CharSequence endUserSessionMessage) {
15540         throwIfParentInstance("setEndUserSessionMessage");
15541         try {
15542             mService.setEndUserSessionMessage(admin, endUserSessionMessage);
15543         } catch (RemoteException re) {
15544             throw re.rethrowFromSystemServer();
15545         }
15546     }
15547 
15548     /**
15549      * Returns the user session start message.
15550      *
15551      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15552      * @throws SecurityException if {@code admin} is not a device owner.
15553      */
getStartUserSessionMessage(@onNull ComponentName admin)15554     public CharSequence getStartUserSessionMessage(@NonNull ComponentName admin) {
15555         throwIfParentInstance("getStartUserSessionMessage");
15556         try {
15557             return mService.getStartUserSessionMessage(admin);
15558         } catch (RemoteException re) {
15559             throw re.rethrowFromSystemServer();
15560         }
15561     }
15562 
15563     /**
15564      * Returns the user session end message.
15565      *
15566      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15567      * @throws SecurityException if {@code admin} is not a device owner.
15568      */
getEndUserSessionMessage(@onNull ComponentName admin)15569     public CharSequence getEndUserSessionMessage(@NonNull ComponentName admin) {
15570         throwIfParentInstance("getEndUserSessionMessage");
15571         try {
15572             return mService.getEndUserSessionMessage(admin);
15573         } catch (RemoteException re) {
15574             throw re.rethrowFromSystemServer();
15575         }
15576     }
15577 
15578     /**
15579      * Called by device owner or managed profile owner to add an override APN.
15580      *
15581      * <p>This method may returns {@code -1} if {@code apnSetting} conflicts with an existing
15582      * override APN. Update the existing conflicted APN with
15583      * {@link #updateOverrideApn(ComponentName, int, ApnSetting)} instead of adding a new entry.
15584      * <p>Two override APNs are considered to conflict when all the following APIs return
15585      * the same values on both override APNs:
15586      * <ul>
15587      *   <li>{@link ApnSetting#getOperatorNumeric()}</li>
15588      *   <li>{@link ApnSetting#getApnName()}</li>
15589      *   <li>{@link ApnSetting#getProxyAddressAsString()}</li>
15590      *   <li>{@link ApnSetting#getProxyPort()}</li>
15591      *   <li>{@link ApnSetting#getMmsProxyAddressAsString()}</li>
15592      *   <li>{@link ApnSetting#getMmsProxyPort()}</li>
15593      *   <li>{@link ApnSetting#getMmsc()}</li>
15594      *   <li>{@link ApnSetting#isEnabled()}</li>
15595      *   <li>{@link ApnSetting#getMvnoType()}</li>
15596      *   <li>{@link ApnSetting#getProtocol()}</li>
15597      *   <li>{@link ApnSetting#getRoamingProtocol()}</li>
15598      * </ul>
15599      *
15600      * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
15601      * Only device owners can add APNs.
15602      * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
15603      * Both device owners and managed profile owners can add enterprise APNs
15604      * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can add other type of APNs.
15605      * Enterprise APNs are specific to the managed profile and do not override any user-configured
15606      * VPNs. They are prerequisites for enabling preferential network service on the managed
15607      * profile on 4G networks ({@link #setPreferentialNetworkServiceConfigs}).
15608      *
15609      * @param admin which {@link DeviceAdminReceiver} this request is associated with
15610      * @param apnSetting the override APN to insert
15611      * @return The {@code id} of inserted override APN. Or {@code -1} when failed to insert into
15612      *         the database.
15613      * @throws SecurityException If request is for enterprise APN {@code admin} is either device
15614      * owner or profile owner and in all other types of APN if {@code admin} is not a device owner.
15615      *
15616      * @see #setOverrideApnsEnabled(ComponentName, boolean)
15617      */
addOverrideApn(@onNull ComponentName admin, @NonNull ApnSetting apnSetting)15618     public int addOverrideApn(@NonNull ComponentName admin, @NonNull ApnSetting apnSetting) {
15619         throwIfParentInstance("addOverrideApn");
15620         if (mService != null) {
15621             try {
15622                 return mService.addOverrideApn(admin, apnSetting);
15623             } catch (RemoteException e) {
15624                 throw e.rethrowFromSystemServer();
15625             }
15626         }
15627         return -1;
15628     }
15629 
15630     /**
15631      * Called by device owner or managed profile owner to update an override APN.
15632      *
15633      * <p>This method may returns {@code false} if there is no override APN with the given
15634      * {@code apnId}.
15635      * <p>This method may also returns {@code false} if {@code apnSetting} conflicts with an
15636      * existing override APN. Update the existing conflicted APN instead.
15637      * <p>See {@link #addOverrideApn} for the definition of conflict.
15638      * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
15639      * Only device owners can update APNs.
15640      * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
15641      * Both device owners and managed profile owners can update enterprise APNs
15642      * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can update other type of APNs.
15643      *
15644      * @param admin which {@link DeviceAdminReceiver} this request is associated with
15645      * @param apnId the {@code id} of the override APN to update
15646      * @param apnSetting the override APN to update
15647      * @return {@code true} if the required override APN is successfully updated,
15648      *         {@code false} otherwise.
15649      * @throws SecurityException If request is for enterprise APN {@code admin} is either device
15650      * owner or profile owner and in all other types of APN if {@code admin} is not a device owner.
15651      *
15652      * @see #setOverrideApnsEnabled(ComponentName, boolean)
15653      */
updateOverrideApn(@onNull ComponentName admin, int apnId, @NonNull ApnSetting apnSetting)15654     public boolean updateOverrideApn(@NonNull ComponentName admin, int apnId,
15655             @NonNull ApnSetting apnSetting) {
15656         throwIfParentInstance("updateOverrideApn");
15657         if (mService != null) {
15658             try {
15659                 return mService.updateOverrideApn(admin, apnId, apnSetting);
15660             } catch (RemoteException e) {
15661                 throw e.rethrowFromSystemServer();
15662             }
15663         }
15664         return false;
15665     }
15666 
15667     /**
15668      * Called by device owner or managed profile owner to remove an override APN.
15669      *
15670      * <p>This method may returns {@code false} if there is no override APN with the given
15671      * {@code apnId}.
15672      * <p> Before Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
15673      * Only device owners can remove APNs.
15674      * <p> Starting from Android version {@link android.os.Build.VERSION_CODES#TIRAMISU}:
15675      * Both device owners and managed profile owners can remove enterprise APNs
15676      * ({@link ApnSetting#TYPE_ENTERPRISE}), while only device owners can remove other type of APNs.
15677      *
15678      * @param admin which {@link DeviceAdminReceiver} this request is associated with
15679      * @param apnId the {@code id} of the override APN to remove
15680      * @return {@code true} if the required override APN is successfully removed, {@code false}
15681      *         otherwise.
15682      * @throws SecurityException If request is for enterprise APN {@code admin} is either device
15683      * owner or profile owner and in all other types of APN if {@code admin} is not a device owner.
15684      *
15685      * @see #setOverrideApnsEnabled(ComponentName, boolean)
15686      */
removeOverrideApn(@onNull ComponentName admin, int apnId)15687     public boolean removeOverrideApn(@NonNull ComponentName admin, int apnId) {
15688         throwIfParentInstance("removeOverrideApn");
15689         if (mService != null) {
15690             try {
15691                 return mService.removeOverrideApn(admin, apnId);
15692             } catch (RemoteException e) {
15693                 throw e.rethrowFromSystemServer();
15694             }
15695         }
15696         return false;
15697     }
15698 
15699     /**
15700      * Called by device owner or managed profile owner to get all override APNs inserted by
15701      * device owner or managed profile owner previously using {@link #addOverrideApn}.
15702      *
15703      * @param admin which {@link DeviceAdminReceiver} this request is associated with
15704      * @return A list of override APNs inserted by device owner.
15705      * @throws SecurityException if {@code admin} is not a device owner.
15706      *
15707      * @see #setOverrideApnsEnabled(ComponentName, boolean)
15708      */
getOverrideApns(@onNull ComponentName admin)15709     public List<ApnSetting> getOverrideApns(@NonNull ComponentName admin) {
15710         throwIfParentInstance("getOverrideApns");
15711         if (mService != null) {
15712             try {
15713                 return mService.getOverrideApns(admin);
15714             } catch (RemoteException e) {
15715                 throw e.rethrowFromSystemServer();
15716             }
15717         }
15718         return Collections.emptyList();
15719     }
15720 
15721     /**
15722      * Called by device owner to set if override APNs should be enabled.
15723      * <p> Override APNs are separated from other APNs on the device, and can only be inserted or
15724      * modified by the device owner. When enabled, only override APNs are in use, any other APNs
15725      * are ignored.
15726      * <p>Note: Enterprise APNs added by managed profile owners do not need to be enabled by
15727      * this API. They are part of the preferential network service config and is controlled by
15728      * {@link #setPreferentialNetworkServiceConfigs}.
15729      *
15730      * @param admin which {@link DeviceAdminReceiver} this request is associated with
15731      * @param enabled {@code true} if override APNs should be enabled, {@code false} otherwise
15732      * @throws SecurityException if {@code admin} is not a device owner.
15733      */
setOverrideApnsEnabled(@onNull ComponentName admin, boolean enabled)15734     public void setOverrideApnsEnabled(@NonNull ComponentName admin, boolean enabled) {
15735         throwIfParentInstance("setOverrideApnEnabled");
15736         if (mService != null) {
15737             try {
15738                 mService.setOverrideApnsEnabled(admin, enabled);
15739             } catch (RemoteException e) {
15740                 throw e.rethrowFromSystemServer();
15741             }
15742         }
15743     }
15744 
15745     /**
15746      * Called by device owner to check if override APNs are currently enabled.
15747      *
15748      * @param admin which {@link DeviceAdminReceiver} this request is associated with
15749      * @return {@code true} if override APNs are currently enabled, {@code false} otherwise.
15750      * @throws SecurityException if {@code admin} is not a device owner.
15751      *
15752      * @see #setOverrideApnsEnabled(ComponentName, boolean)
15753      */
isOverrideApnEnabled(@onNull ComponentName admin)15754     public boolean isOverrideApnEnabled(@NonNull ComponentName admin) {
15755         throwIfParentInstance("isOverrideApnEnabled");
15756         if (mService != null) {
15757             try {
15758                 return mService.isOverrideApnEnabled(admin);
15759             } catch (RemoteException e) {
15760                 throw e.rethrowFromSystemServer();
15761             }
15762         }
15763         return false;
15764     }
15765 
15766     /**
15767      * Returns the data passed from the current administrator to the new administrator during an
15768      * ownership transfer. This is the same {@code bundle} passed in
15769      * {@link #transferOwnership(ComponentName, ComponentName, PersistableBundle)}. The bundle is
15770      * persisted until the profile owner or device owner is removed.
15771      *
15772      * <p>This is the same <code>bundle</code> received in the
15773      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}.
15774      * Use this method to retrieve it after the transfer as long as the new administrator is the
15775      * active device or profile owner.
15776      *
15777      * <p>Returns <code>null</code> if no ownership transfer was started for the calling user.
15778      *
15779      * @see #transferOwnership
15780      * @see DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)
15781      * @throws SecurityException if the caller is not a device or profile owner.
15782      */
15783     @Nullable
getTransferOwnershipBundle()15784     public PersistableBundle getTransferOwnershipBundle() {
15785         throwIfParentInstance("getTransferOwnershipBundle");
15786         try {
15787             return mService.getTransferOwnershipBundle();
15788         } catch (RemoteException re) {
15789             throw re.rethrowFromSystemServer();
15790         }
15791     }
15792 
15793     /**
15794      * Sets the global Private DNS mode to opportunistic.
15795      * May only be called by the device owner.
15796      *
15797      * <p>In this mode, the DNS subsystem will attempt a TLS handshake to the network-supplied
15798      * resolver prior to attempting name resolution in cleartext.
15799      *
15800      * <p>Note: The device owner won't be able to set the global private DNS mode if there are
15801      * unaffiliated secondary users or profiles on the device. It's recommended that affiliation
15802      * ids are set for new users as soon as possible after provisioning via
15803      * {@link #setAffiliationIds}.
15804      *
15805      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15806      *
15807      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully, or
15808      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set.
15809      *
15810      * @throws SecurityException if the caller is not the device owner.
15811      */
setGlobalPrivateDnsModeOpportunistic( @onNull ComponentName admin)15812     public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeOpportunistic(
15813             @NonNull ComponentName admin) {
15814         throwIfParentInstance("setGlobalPrivateDnsModeOpportunistic");
15815 
15816         if (mService == null) {
15817             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
15818         }
15819 
15820         try {
15821             return mService.setGlobalPrivateDns(admin, PRIVATE_DNS_MODE_OPPORTUNISTIC, null);
15822         } catch (RemoteException re) {
15823             throw re.rethrowFromSystemServer();
15824         }
15825     }
15826 
15827     /**
15828      * Sets the global Private DNS host to be used.
15829      * May only be called by the device owner.
15830      *
15831      * <p>Note that the method is blocking as it will perform a connectivity check to the resolver,
15832      * to ensure it is valid. Because of that, the method should not be called on any thread that
15833      * relates to user interaction, such as the UI thread.
15834      *
15835      * <p>In case a VPN is used in conjunction with Private DNS resolver, the Private DNS resolver
15836      * must be reachable both from within and outside the VPN. Otherwise, the device may lose
15837      * the ability to resolve hostnames as system traffic to the resolver may not go through the
15838      * VPN.
15839      *
15840      * <p>Note: The device owner won't be able to set the global private DNS mode if there are
15841      * unaffiliated secondary users or profiles on the device. It's recommended that affiliation
15842      * ids are set for new users as soon as possible after provisioning via
15843      * {@link #setAffiliationIds}.
15844      *
15845      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15846      * @param privateDnsHost The hostname of a server that implements DNS over TLS (RFC7858).
15847      *
15848      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully,
15849      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set or
15850      *         {@code PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING} if the specified host does not
15851      *         implement RFC7858.
15852      *
15853      * @throws IllegalArgumentException if the {@code privateDnsHost} is not a valid hostname.
15854      *
15855      * @throws SecurityException if the caller is not the device owner.
15856      */
setGlobalPrivateDnsModeSpecifiedHost( @onNull ComponentName admin, @NonNull String privateDnsHost)15857     @WorkerThread public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeSpecifiedHost(
15858             @NonNull ComponentName admin, @NonNull String privateDnsHost) {
15859         throwIfParentInstance("setGlobalPrivateDnsModeSpecifiedHost");
15860         Objects.requireNonNull(privateDnsHost, "dns resolver is null");
15861 
15862         if (mService == null) {
15863             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
15864         }
15865 
15866         if (NetworkUtilsInternal.isWeaklyValidatedHostname(privateDnsHost)) {
15867             if (!PrivateDnsConnectivityChecker.canConnectToPrivateDnsServer(privateDnsHost)) {
15868                 return PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING;
15869             }
15870         }
15871 
15872         try {
15873             return mService.setGlobalPrivateDns(
15874                     admin, PRIVATE_DNS_MODE_PROVIDER_HOSTNAME, privateDnsHost);
15875         } catch (RemoteException re) {
15876             throw re.rethrowFromSystemServer();
15877         }
15878     }
15879 
15880     /**
15881      * Called by device owner or profile owner of an organization-owned managed profile to install
15882      * a system update from the given file. The device will be
15883      * rebooted in order to finish installing the update. Note that if the device is rebooted, this
15884      * doesn't necessarily mean that the update has been applied successfully. The caller should
15885      * additionally check the system version with {@link android.os.Build#FINGERPRINT} or {@link
15886      * android.os.Build.VERSION}. If an error occurs during processing the OTA before the reboot,
15887      * the caller will be notified by {@link InstallSystemUpdateCallback}. If device does not have
15888      * sufficient battery level, the installation will fail with error {@link
15889      * InstallSystemUpdateCallback#UPDATE_ERROR_BATTERY_LOW}.
15890      *
15891      * @param admin The {@link DeviceAdminReceiver} that this request is associated with. Null if
15892      *              the caller is not a device admin
15893      * @param updateFilePath A Uri of the file that contains the update. The file should be
15894      * readable by the calling app.
15895      * @param executor The executor through which the callback should be invoked.
15896      * @param callback A callback object that will inform the caller when installing an update
15897      * fails.
15898      */
15899     @RequiresPermission(value = MANAGE_DEVICE_POLICY_SYSTEM_UPDATES, conditional = true)
installSystemUpdate( @ullable ComponentName admin, @NonNull Uri updateFilePath, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)15900     public void installSystemUpdate(
15901             @Nullable ComponentName admin, @NonNull Uri updateFilePath,
15902             @NonNull @CallbackExecutor Executor executor,
15903             @NonNull InstallSystemUpdateCallback callback) {
15904         throwIfParentInstance("installUpdate");
15905         if (mService == null) {
15906             return;
15907         }
15908         try (ParcelFileDescriptor fileDescriptor = mContext.getContentResolver()
15909                     .openFileDescriptor(updateFilePath, "r")) {
15910             mService.installUpdateFromFile(
15911                     admin, mContext.getPackageName(), fileDescriptor,
15912                     new StartInstallingUpdateCallback.Stub() {
15913                         @Override
15914                         public void onStartInstallingUpdateError(
15915                                 int errorCode, String errorMessage) {
15916                             executeCallback(errorCode, errorMessage, executor, callback);
15917                         }
15918                     });
15919         } catch (RemoteException e) {
15920             throw e.rethrowFromSystemServer();
15921         } catch (FileNotFoundException e) {
15922             Log.w(TAG, e);
15923             executeCallback(
15924                     InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
15925                     Log.getStackTraceString(e),
15926                     executor, callback);
15927         } catch (IOException e) {
15928             Log.w(TAG, e);
15929             executeCallback(
15930                     InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN, Log.getStackTraceString(e),
15931                     executor, callback);
15932         }
15933     }
15934 
executeCallback(int errorCode, String errorMessage, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)15935     private void executeCallback(int errorCode, String errorMessage,
15936             @NonNull @CallbackExecutor Executor executor,
15937             @NonNull InstallSystemUpdateCallback callback) {
15938         executor.execute(() -> callback.onInstallUpdateError(errorCode, errorMessage));
15939     }
15940 
15941     /**
15942      * Returns the system-wide Private DNS mode.
15943      *
15944      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15945      * @return one of {@code PRIVATE_DNS_MODE_OFF}, {@code PRIVATE_DNS_MODE_OPPORTUNISTIC},
15946      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} or {@code PRIVATE_DNS_MODE_UNKNOWN}.
15947      * @throws SecurityException if the caller is not the device owner.
15948      */
getGlobalPrivateDnsMode(@onNull ComponentName admin)15949     public int getGlobalPrivateDnsMode(@NonNull ComponentName admin) {
15950         throwIfParentInstance("setGlobalPrivateDns");
15951         if (mService == null) {
15952             return PRIVATE_DNS_MODE_UNKNOWN;
15953         }
15954 
15955         try {
15956             return mService.getGlobalPrivateDnsMode(admin);
15957         } catch (RemoteException re) {
15958             throw re.rethrowFromSystemServer();
15959         }
15960     }
15961 
15962     /**
15963      * Returns the system-wide Private DNS host.
15964      *
15965      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
15966      * @return The hostname used for Private DNS queries, null if none is set.
15967      * @throws SecurityException if the caller is not the device owner.
15968      */
getGlobalPrivateDnsHost(@onNull ComponentName admin)15969     public @Nullable String getGlobalPrivateDnsHost(@NonNull ComponentName admin) {
15970         throwIfParentInstance("setGlobalPrivateDns");
15971         if (mService == null) {
15972             return null;
15973         }
15974 
15975         try {
15976             return mService.getGlobalPrivateDnsHost(admin);
15977         } catch (RemoteException re) {
15978             throw re.rethrowFromSystemServer();
15979         }
15980     }
15981 
15982     /**
15983      * Deprecated. Use {@code markProfileOwnerOnOrganizationOwnedDevice} instead.
15984      * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#Q} or
15985      * below, will behave the same as {@link #setProfileOwnerOnOrganizationOwnedDevice}.
15986      *
15987      * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#R}
15988      * or above, will throw an UnsupportedOperationException when called.
15989      *
15990      * @deprecated Use {@link #setProfileOwnerOnOrganizationOwnedDevice} instead.
15991      *
15992      * @hide
15993      */
15994     @Deprecated
15995     @SystemApi
15996     @RequiresPermission(value = android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS,
15997             conditional = true)
setProfileOwnerCanAccessDeviceIds(@onNull ComponentName who)15998     public void setProfileOwnerCanAccessDeviceIds(@NonNull ComponentName who) {
15999         ApplicationInfo ai = mContext.getApplicationInfo();
16000         if (ai.targetSdkVersion > Build.VERSION_CODES.Q) {
16001             throw new UnsupportedOperationException(
16002                     "This method is deprecated. use markProfileOwnerOnOrganizationOwnedDevice"
16003                     + " instead.");
16004         } else {
16005             setProfileOwnerOnOrganizationOwnedDevice(who, true);
16006         }
16007     }
16008 
16009     /**
16010      * Sets whether the profile owner of the given user as managing an organization-owned device.
16011      * Managing an organization-owned device will give it access to device identifiers (such as
16012      * serial number, IMEI and MEID) as well as other privileges.
16013      *
16014      * @hide
16015      */
16016     @TestApi
16017     @RequiresPermission(anyOf = {
16018             android.Manifest.permission.MARK_DEVICE_ORGANIZATION_OWNED,
16019             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
16020             }, conditional = true)
setProfileOwnerOnOrganizationOwnedDevice(@onNull ComponentName who, boolean isProfileOwnerOnOrganizationOwnedDevice)16021     public void setProfileOwnerOnOrganizationOwnedDevice(@NonNull ComponentName who,
16022             boolean isProfileOwnerOnOrganizationOwnedDevice) {
16023         if (mService == null) {
16024             return;
16025         }
16026         try {
16027             mService.setProfileOwnerOnOrganizationOwnedDevice(who, myUserId(),
16028                     isProfileOwnerOnOrganizationOwnedDevice);
16029         } catch (RemoteException re) {
16030             throw re.rethrowFromSystemServer();
16031         }
16032     }
16033 
16034     /**
16035      * Allows a set of packages to access cross-profile calendar APIs.
16036      *
16037      * <p>Called by a profile owner of a managed profile.
16038      *
16039      * <p>Calling with a {@code null} value for the set disables the restriction so that all
16040      * packages are allowed to access cross-profile calendar APIs. Calling with an empty set
16041      * disallows all packages from accessing cross-profile calendar APIs. If this method isn't
16042      * called, no package is allowed to access cross-profile calendar APIs by default.
16043      *
16044      * @param admin which {@link DeviceAdminReceiver} this request is associated with
16045      * @param packageNames set of packages to be allowlisted
16046      * @throws SecurityException if {@code admin} is not a profile owner
16047      *
16048      * @see #getCrossProfileCalendarPackages(ComponentName)
16049      * @deprecated Use {@link #setCrossProfilePackages(ComponentName, Set)}.
16050      */
16051     @Deprecated
setCrossProfileCalendarPackages(@onNull ComponentName admin, @Nullable Set<String> packageNames)16052     public void setCrossProfileCalendarPackages(@NonNull ComponentName admin,
16053             @Nullable Set<String> packageNames) {
16054         throwIfParentInstance("setCrossProfileCalendarPackages");
16055         if (mService != null) {
16056             try {
16057                 mService.setCrossProfileCalendarPackages(admin, packageNames == null ? null
16058                         : new ArrayList<>(packageNames));
16059             } catch (RemoteException e) {
16060                 throw e.rethrowFromSystemServer();
16061             }
16062         }
16063     }
16064 
16065     /**
16066      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
16067      *
16068      * <p>Called by a profile owner of a managed profile.
16069      *
16070      * @param admin which {@link DeviceAdminReceiver} this request is associated with
16071      * @return the set of names of packages that were previously allowed via
16072      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
16073      * empty set if none have been allowed
16074      * @throws SecurityException if {@code admin} is not a profile owner
16075      *
16076      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
16077      * @deprecated Use {@link #setCrossProfilePackages(ComponentName, Set)}.
16078      */
16079     @Deprecated
getCrossProfileCalendarPackages(@onNull ComponentName admin)16080     public @Nullable Set<String> getCrossProfileCalendarPackages(@NonNull ComponentName admin) {
16081         throwIfParentInstance("getCrossProfileCalendarPackages");
16082         if (mService != null) {
16083             try {
16084                 final List<String> packageNames = mService.getCrossProfileCalendarPackages(admin);
16085                 return packageNames == null ? null : new ArraySet<>(packageNames);
16086             } catch (RemoteException e) {
16087                 throw e.rethrowFromSystemServer();
16088             }
16089         }
16090         return Collections.emptySet();
16091     }
16092 
16093     /**
16094      * Returns if a package is allowed to access cross-profile calendar APIs.
16095      *
16096      * <p>A package is allowed to access cross-profile calendar APIs if it's allowed by
16097      * admins via {@link #setCrossProfileCalendarPackages(ComponentName, Set)} and
16098      * {@link android.provider.Settings.Secure#CROSS_PROFILE_CALENDAR_ENABLED}
16099      * is turned on in the managed profile.
16100      *
16101      * <p>To query for a specific user, use
16102      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
16103      * that user, and get a {@link DevicePolicyManager} from this context.
16104      *
16105      * @param packageName the name of the package
16106      * @return {@code true} if the package is allowed to access cross-profile calendar APIs,
16107      * {@code false} otherwise
16108      *
16109      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
16110      * @see #getCrossProfileCalendarPackages(ComponentName)
16111      * @hide
16112      */
16113     @RequiresPermission(anyOf = {
16114             INTERACT_ACROSS_USERS_FULL,
16115             permission.INTERACT_ACROSS_USERS
16116     }, conditional = true)
isPackageAllowedToAccessCalendar(@onNull String packageName)16117     public boolean isPackageAllowedToAccessCalendar(@NonNull  String packageName) {
16118         throwIfParentInstance("isPackageAllowedToAccessCalendar");
16119         if (mService != null) {
16120             try {
16121                 return mService.isPackageAllowedToAccessCalendarForUser(packageName,
16122                         myUserId());
16123             } catch (RemoteException e) {
16124                 throw e.rethrowFromSystemServer();
16125             }
16126         }
16127         return false;
16128     }
16129 
16130     /**
16131      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
16132      *
16133      * <p>To query for a specific user, use
16134      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
16135      * that user, and get a {@link DevicePolicyManager} from this context.
16136      *
16137      * @return the set of names of packages that were previously allowed via
16138      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
16139      * empty set if none have been allowed
16140      *
16141      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
16142      * @see #getCrossProfileCalendarPackages(ComponentName)
16143      * @hide
16144      */
16145     @RequiresPermission(anyOf = {
16146             INTERACT_ACROSS_USERS_FULL,
16147             permission.INTERACT_ACROSS_USERS
16148     })
getCrossProfileCalendarPackages()16149     public @Nullable Set<String> getCrossProfileCalendarPackages() {
16150         throwIfParentInstance("getCrossProfileCalendarPackages");
16151         if (mService != null) {
16152             try {
16153                 final List<String> packageNames = mService.getCrossProfileCalendarPackagesForUser(
16154                         myUserId());
16155                 return packageNames == null ? null : new ArraySet<>(packageNames);
16156             } catch (RemoteException e) {
16157                 throw e.rethrowFromSystemServer();
16158             }
16159         }
16160         return Collections.emptySet();
16161     }
16162 
16163     /**
16164      * Sets the set of admin-allowlisted package names that are allowed to request user consent for
16165      * cross-profile communication.
16166      *
16167      * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
16168      *
16169      * <p>Previous calls are overridden by each subsequent call to this method.
16170      *
16171      * <p>Note that other apps may be able to request user consent for cross-profile communication
16172      * if they have been explicitly allowlisted by the OEM.
16173      *
16174      * <p>When previously-set cross-profile packages are missing from {@code packageNames}, the
16175      * app-op for {@code INTERACT_ACROSS_PROFILES} will be reset for those packages. This will not
16176      * occur for packages that are allowlisted by the OEM.
16177      *
16178      * @param admin the {@link DeviceAdminReceiver} this request is associated with
16179      * @param packageNames the new cross-profile package names
16180      */
setCrossProfilePackages( @onNull ComponentName admin, @NonNull Set<String> packageNames)16181     public void setCrossProfilePackages(
16182             @NonNull ComponentName admin, @NonNull Set<String> packageNames) {
16183         throwIfParentInstance("setCrossProfilePackages");
16184         if (mService != null) {
16185             try {
16186                 mService.setCrossProfilePackages(admin, new ArrayList<>(packageNames));
16187             } catch (RemoteException e) {
16188                 throw e.rethrowFromSystemServer();
16189             }
16190         }
16191     }
16192 
16193     /**
16194      * Returns the set of package names that the admin has previously set as allowed to request user
16195      * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
16196      * Set)}.
16197      *
16198      * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
16199      *
16200      * <p>Note that other apps not included in the returned set may be able to request user consent
16201      * for cross-profile communication if they have been explicitly allowlisted by the OEM.
16202      *
16203      * @param admin the {@link DeviceAdminReceiver} this request is associated with
16204      * @return the set of package names the admin has previously set as allowed to request user
16205      * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
16206      * Set)}
16207      */
getCrossProfilePackages(@onNull ComponentName admin)16208     public @NonNull Set<String> getCrossProfilePackages(@NonNull ComponentName admin) {
16209         throwIfParentInstance("getCrossProfilePackages");
16210         if (mService != null) {
16211             try {
16212                 return new ArraySet<>(mService.getCrossProfilePackages(admin));
16213             } catch (RemoteException e) {
16214                 throw e.rethrowFromSystemServer();
16215             }
16216         }
16217         return Collections.emptySet();
16218     }
16219 
16220     /**
16221      * Returns the combined set of the following:
16222      * <ul>
16223      * <li>The package names that the admin has previously set as allowed to request user consent
16224      * for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
16225      * Set)}.</li>
16226      * <li>The default package names set by the OEM that are allowed to request user consent for
16227      * cross-profile communication without being explicitly enabled by the admin, via {@link
16228      * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array
16229      * #vendor_cross_profile_apps}.</li>
16230      * </ul>
16231      *
16232      * @return the combined set of allowlisted package names set via
16233      * {@link #setCrossProfilePackages(ComponentName, Set)}, {@link com.android.internal.R.array
16234      * #cross_profile_apps}, and {@link com.android.internal.R.array#vendor_cross_profile_apps}.
16235      *
16236      * @hide
16237      */
16238     @RequiresPermission(anyOf = {
16239             INTERACT_ACROSS_USERS_FULL,
16240             permission.INTERACT_ACROSS_USERS,
16241             permission.INTERACT_ACROSS_PROFILES
16242     })
getAllCrossProfilePackages()16243     public @NonNull Set<String> getAllCrossProfilePackages() {
16244         throwIfParentInstance("getAllCrossProfilePackages");
16245         if (mService != null) {
16246             try {
16247                 return new ArraySet<>(mService.getAllCrossProfilePackages(mContext.getUserId()));
16248             } catch (RemoteException e) {
16249                 throw e.rethrowFromSystemServer();
16250             }
16251         }
16252         return Collections.emptySet();
16253     }
16254 
16255     /**
16256      * Returns the default package names set by the OEM that are allowed to communicate
16257      * cross-profile without being explicitly enabled by the admin, via {@link
16258      * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array
16259      * #vendor_cross_profile_apps}.
16260      *
16261      * @hide
16262      */
16263     @TestApi
getDefaultCrossProfilePackages()16264     public @NonNull Set<String> getDefaultCrossProfilePackages() {
16265         throwIfParentInstance("getDefaultCrossProfilePackages");
16266         if (mService != null) {
16267             try {
16268                 return new ArraySet<>(mService.getDefaultCrossProfilePackages());
16269             } catch (RemoteException e) {
16270                 throw e.rethrowFromSystemServer();
16271             }
16272         }
16273         return Collections.emptySet();
16274     }
16275 
16276     /**
16277      * Returns whether the device is being used as a managed kiosk. These requirements are as
16278      * follows:
16279      * <ul>
16280      *     <li>The device is in Lock Task (therefore there is also a Device Owner app on the
16281      *     device)</li>
16282      *     <li>The Lock Task feature {@link DevicePolicyManager#LOCK_TASK_FEATURE_SYSTEM_INFO} is
16283      *     not enabled, so the system info in the status bar is not visible</li>
16284      *     <li>The device does not have a secure lock screen (e.g. it has no lock screen or has
16285      *     swipe-to-unlock)</li>
16286      *     <li>The device is not in the middle of an ephemeral user session</li>
16287      * </ul>
16288      *
16289      * <p>Publicly-accessible dedicated devices don't have the same privacy model as
16290      * personally-used devices. In particular, user consent popups don't make sense as a barrier to
16291      * accessing persistent data on these devices since the user giving consent and the user whose
16292      * data is on the device are unlikely to be the same. These consent popups prevent the true
16293      * remote management of these devices.
16294      *
16295      * <p>This condition is not sufficient to cover APIs that would access data that only lives for
16296      * the duration of the user's session, since the user has an expectation of privacy in these
16297      * conditions that more closely resembles use of a personal device. In those cases, see {@link
16298      * #isUnattendedManagedKiosk()}.
16299      *
16300      * @hide
16301      */
16302     @SystemApi
16303     @RequiresPermission(anyOf = {
16304             android.Manifest.permission.MANAGE_USERS,
16305             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
16306     })
isManagedKiosk()16307     public boolean isManagedKiosk() {
16308         throwIfParentInstance("isManagedKiosk");
16309         if (mService != null) {
16310             try {
16311                 return mService.isManagedKiosk();
16312             } catch (RemoteException e) {
16313                 throw e.rethrowFromSystemServer();
16314             }
16315         }
16316         return false;
16317     }
16318 
16319     /**
16320      * Returns whether the device is being used as an unattended managed kiosk. These requirements
16321      * are as follows:
16322      * <ul>
16323      *     <li>The device is being used as a managed kiosk, as defined at {@link
16324      *     #isManagedKiosk()}</li>
16325      *     <li>The device has not received user input for at least 30 minutes</li>
16326      * </ul>
16327      *
16328      * <p>See {@link #isManagedKiosk()} for context. This is a stronger requirement that also
16329      * ensures that the device hasn't been interacted with recently, making it an appropriate check
16330      * for privacy-sensitive APIs that wouldn't be appropriate during an active user session.
16331      *
16332      * @hide
16333      */
16334     @SystemApi
16335     @RequiresPermission(anyOf = {
16336             android.Manifest.permission.MANAGE_USERS,
16337             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
16338     })
isUnattendedManagedKiosk()16339     public boolean isUnattendedManagedKiosk() {
16340         throwIfParentInstance("isUnattendedManagedKiosk");
16341         if (mService != null) {
16342             try {
16343                 return mService.isUnattendedManagedKiosk();
16344             } catch (RemoteException e) {
16345                 throw e.rethrowFromSystemServer();
16346             }
16347         }
16348         return false;
16349     }
16350 
16351     /**
16352      * Starts an activity to view calendar events in the managed profile.
16353      *
16354      * @param eventId the id of the event to be viewed
16355      * @param start the start time of the event
16356      * @param end the end time of the event
16357      * @param allDay if the event is an all-day event
16358      * @param flags flags to be set for the intent
16359      * @return {@code true} if the activity is started successfully, {@code false} otherwise
16360      *
16361      * @see CalendarContract#startViewCalendarEventInManagedProfile(Context, String, long, long,
16362      * long, boolean, int)
16363      *
16364      * @hide
16365      */
startViewCalendarEventInManagedProfile(long eventId, long start, long end, boolean allDay, int flags)16366     public boolean startViewCalendarEventInManagedProfile(long eventId, long start, long end,
16367             boolean allDay, int flags) {
16368         throwIfParentInstance("startViewCalendarEventInManagedProfile");
16369         if (mService != null) {
16370             try {
16371                 return mService.startViewCalendarEventInManagedProfile(mContext.getPackageName(),
16372                         eventId, start, end, allDay, flags);
16373             } catch (RemoteException e) {
16374                 throw e.rethrowFromSystemServer();
16375             }
16376         }
16377         return false;
16378     }
16379 
16380     /**
16381      * Service-specific error code used in {@link #setApplicationExemptions(String, Set)} and
16382      * {@link #getApplicationExemptions(String)}.
16383      * @hide
16384      */
16385     public static final int ERROR_PACKAGE_NAME_NOT_FOUND = 1;
16386 
16387     /**
16388      * Called by an application with the
16389      * {@link  android.Manifest.permission#MANAGE_DEVICE_POLICY_APP_EXEMPTIONS} permission, to
16390      * grant platform restriction exemptions to a given application.
16391      *
16392      * @param  packageName The package name of the application to be exempt.
16393      * @param  exemptions The set of exemptions to be applied.
16394      * @throws SecurityException If the caller does not have
16395      *             {@link  android.Manifest.permission#MANAGE_DEVICE_POLICY_APP_EXEMPTIONS}
16396      * @throws NameNotFoundException If either the package is not installed or the package is not
16397      *              visible to the caller.
16398      * @hide
16399      */
16400     @SystemApi
16401     @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_POLICY_APP_EXEMPTIONS)
setApplicationExemptions(@onNull String packageName, @NonNull @ApplicationExemptionConstants Set<Integer> exemptions)16402     public void setApplicationExemptions(@NonNull String packageName,
16403             @NonNull @ApplicationExemptionConstants Set<Integer> exemptions)
16404             throws NameNotFoundException {
16405         throwIfParentInstance("setApplicationExemptions");
16406         if (mService != null) {
16407             try {
16408                 mService.setApplicationExemptions(mContext.getPackageName(), packageName,
16409                         ArrayUtils.convertToIntArray(new ArraySet<>(exemptions)));
16410             } catch (ServiceSpecificException e) {
16411                 switch (e.errorCode) {
16412                     case ERROR_PACKAGE_NAME_NOT_FOUND:
16413                         throw new NameNotFoundException(e.getMessage());
16414                     default:
16415                         throw new RuntimeException(
16416                                 "Unknown error setting application exemptions: " + e.errorCode, e);
16417                 }
16418             } catch (RemoteException e) {
16419                 throw e.rethrowFromSystemServer();
16420             }
16421         }
16422     }
16423 
16424     /**
16425      * Returns all the platform restriction exemptions currently applied to an application. Called
16426      * by an application with the
16427      * {@link  android.Manifest.permission#MANAGE_DEVICE_POLICY_APP_EXEMPTIONS} permission.
16428      *
16429      * @param  packageName The package name to check.
16430      * @return A set of platform restrictions an application is exempt from.
16431      * @throws SecurityException If the caller does not have
16432      *             {@link  android.Manifest.permission#MANAGE_DEVICE_POLICY_APP_EXEMPTIONS}
16433      * @throws NameNotFoundException If either the package is not installed or the package is not
16434      *              visible to the caller.
16435      * @hide
16436      */
16437     @NonNull
16438     @SystemApi
16439     @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_POLICY_APP_EXEMPTIONS)
getApplicationExemptions(@onNull String packageName)16440     public Set<Integer> getApplicationExemptions(@NonNull String packageName)
16441             throws NameNotFoundException {
16442         throwIfParentInstance("getApplicationExemptions");
16443         if (mService == null) {
16444             return Collections.emptySet();
16445         }
16446         try {
16447             return intArrayToSet(mService.getApplicationExemptions(packageName));
16448         } catch (ServiceSpecificException e) {
16449             switch (e.errorCode) {
16450                 case ERROR_PACKAGE_NAME_NOT_FOUND:
16451                     throw new NameNotFoundException(e.getMessage());
16452                 default:
16453                     throw new RuntimeException(
16454                             "Unknown error getting application exemptions: " + e.errorCode, e);
16455             }
16456         } catch (RemoteException e) {
16457             throw e.rethrowFromSystemServer();
16458         }
16459     }
16460 
intArrayToSet(int[] array)16461     private Set<Integer> intArrayToSet(int[] array) {
16462         Set<Integer> set = new ArraySet<>();
16463         for (int item : array) {
16464             set.add(item);
16465         }
16466         return set;
16467     }
16468 
16469     /**
16470      * Called by a device owner or a profile owner or holder of the permission
16471      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL} to disable user
16472      * control over apps. User will not be able to clear app data or force-stop packages. When
16473      * called by a device owner, applies to all users on the device. Packages with user control
16474      * disabled are exempted from App Standby Buckets.
16475      * <p>
16476      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, after the user control disabled
16477      * packages policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
16478      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
16479      * successfully set or not. This callback will contain:
16480      * <ul>
16481      * <li> The policy identifier
16482      * {@link DevicePolicyIdentifiers#USER_CONTROL_DISABLED_PACKAGES_POLICY}
16483      * <li> The {@link TargetUser} that this policy relates to
16484      * <li> The {@link PolicyUpdateResult}, which will be
16485      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
16486      * reason the policy failed to be set
16487      * (e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
16488      * </ul>
16489      * If there has been a change to the policy,
16490      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
16491      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
16492      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
16493      * will contain the reason why the policy changed.
16494      *
16495      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
16496      *               caller is not a device admin.
16497      * @param packages The package names for the apps.
16498      * @throws SecurityException if {@code admin} is not a device owner or a profile owner or
16499      * holder of the permission
16500      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL}.
16501      */
16502     @RequiresPermission(value = MANAGE_DEVICE_POLICY_APPS_CONTROL, conditional = true)
16503     @SupportsCoexistence
setUserControlDisabledPackages(@ullable ComponentName admin, @NonNull List<String> packages)16504     public void setUserControlDisabledPackages(@Nullable ComponentName admin,
16505             @NonNull List<String> packages) {
16506         throwIfParentInstance("setUserControlDisabledPackages");
16507         if (mService != null) {
16508             try {
16509                 mService.setUserControlDisabledPackages(admin, mContext.getPackageName(), packages);
16510             } catch (RemoteException re) {
16511                 throw re.rethrowFromSystemServer();
16512             }
16513         }
16514     }
16515 
16516     /**
16517      * Returns the list of packages over which user control is disabled by a device or profile
16518      * owner or holders of the permission
16519      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL}.
16520      * <p>
16521      * Starting from {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, the returned policy will be the
16522      * current resolved policy rather than the policy set by the calling admin.
16523      *
16524      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
16525      *               caller is not a device admin.
16526      * @throws SecurityException if {@code admin} is not a device or profile owner or holder of the
16527      * permission {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_APPS_CONTROL}.
16528      */
16529     @RequiresPermission(value = MANAGE_DEVICE_POLICY_APPS_CONTROL, conditional = true)
16530     @NonNull
getUserControlDisabledPackages(@ullable ComponentName admin)16531     public List<String> getUserControlDisabledPackages(@Nullable ComponentName admin) {
16532         throwIfParentInstance("getUserControlDisabledPackages");
16533         if (mService != null) {
16534             try {
16535                 return mService.getUserControlDisabledPackages(admin, mContext.getPackageName());
16536             } catch (RemoteException re) {
16537                 throw re.rethrowFromSystemServer();
16538             }
16539         }
16540         return Collections.emptyList();
16541     }
16542 
16543     /**
16544      * Called by device owner or profile owner of an organization-owned managed profile to toggle
16545      * Common Criteria mode for the device. When the device is in Common Criteria mode,
16546      * certain device functionalities are tuned to meet the higher
16547      * security level required by Common Criteria certification. For example:
16548      * <ul>
16549      * <li> Bluetooth long term key material is additionally integrity-protected with AES-GCM. </li>
16550      * <li> WiFi configuration store is additionally integrity-protected with AES-GCM. </li>
16551      * </ul>
16552      * Common Criteria mode is disabled by default.
16553      *
16554      * <p><em>Note:</em> if Common Critera mode is turned off after being enabled previously,
16555      * all existing WiFi configurations will be lost.
16556      *
16557      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
16558      *              caller is not a device admin.
16559      * @param enabled whether Common Criteria mode should be enabled or not.
16560      */
16561     @RequiresPermission(value = MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE, conditional = true)
setCommonCriteriaModeEnabled(@ullable ComponentName admin, boolean enabled)16562     public void setCommonCriteriaModeEnabled(@Nullable ComponentName admin, boolean enabled) {
16563         throwIfParentInstance("setCommonCriteriaModeEnabled");
16564         if (mService != null) {
16565             try {
16566                 mService.setCommonCriteriaModeEnabled(admin, mContext.getPackageName(), enabled);
16567             } catch (RemoteException e) {
16568                 throw e.rethrowFromSystemServer();
16569             }
16570         }
16571     }
16572 
16573     /**
16574      * Returns whether Common Criteria mode is currently enabled. Device owner and profile owner of
16575      * an organization-owned managed profile can query its own Common Criteria mode setting by
16576      * calling this method with its admin {@link ComponentName}. Any caller can obtain the
16577      * aggregated device-wide Common Criteria mode state by passing {@code null} as the
16578      * {@code admin} argument.
16579      *
16580      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Null if the
16581      *              caller is not a device admin.
16582      * @return {@code true} if Common Criteria mode is enabled, {@code false} otherwise.
16583      */
isCommonCriteriaModeEnabled(@ullable ComponentName admin)16584     public boolean isCommonCriteriaModeEnabled(@Nullable ComponentName admin) {
16585         throwIfParentInstance("isCommonCriteriaModeEnabled");
16586         if (mService != null) {
16587             try {
16588                 return mService.isCommonCriteriaModeEnabled(admin);
16589             } catch (RemoteException e) {
16590                 throw e.rethrowFromSystemServer();
16591             }
16592         }
16593         return false;
16594     }
16595 
16596     /**
16597      * Called by profile owner of an organization-owned managed profile to check whether
16598      * personal apps are suspended.
16599      *
16600      * @return a bitmask of reasons for personal apps suspension or
16601      *     {@link #PERSONAL_APPS_NOT_SUSPENDED} if apps are not suspended.
16602      * @see #setPersonalAppsSuspended
16603      */
getPersonalAppsSuspendedReasons( @onNull ComponentName admin)16604     public @PersonalAppsSuspensionReason int getPersonalAppsSuspendedReasons(
16605             @NonNull ComponentName admin) {
16606         throwIfParentInstance("getPersonalAppsSuspendedReasons");
16607         if (mService != null) {
16608             try {
16609                 return mService.getPersonalAppsSuspendedReasons(admin);
16610             } catch (RemoteException re) {
16611                 throw re.rethrowFromSystemServer();
16612             }
16613         }
16614         return 0;
16615     }
16616 
16617     /**
16618      * Called by a profile owner of an organization-owned managed profile to suspend personal
16619      * apps on the device. When personal apps are suspended the device can only be used for calls.
16620      *
16621      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
16622      * @param suspended Whether personal apps should be suspended.
16623      * @throws IllegalStateException if the profile owner doesn't have an activity that handles
16624      *        {@link #ACTION_CHECK_POLICY_COMPLIANCE}
16625      */
setPersonalAppsSuspended(@onNull ComponentName admin, boolean suspended)16626     public void setPersonalAppsSuspended(@NonNull ComponentName admin, boolean suspended) {
16627         throwIfParentInstance("setPersonalAppsSuspended");
16628         if (mService != null) {
16629             try {
16630                 mService.setPersonalAppsSuspended(admin, suspended);
16631             } catch (RemoteException re) {
16632                 throw re.rethrowFromSystemServer();
16633             }
16634         }
16635     }
16636 
16637     /**
16638      * Called by a profile owner of an organization-owned managed profile to set maximum time
16639      * the profile is allowed to be turned off. If the profile is turned off for longer, personal
16640      * apps are suspended on the device.
16641      *
16642      * <p>When personal apps are suspended, an ongoing notification about that is shown to the user.
16643      * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE}
16644      * in the profile owner package. Profile owner implementation that uses personal apps suspension
16645      * must handle this intent.
16646      *
16647      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
16648      * @param timeoutMillis Maximum time the profile is allowed to be off in milliseconds or 0 if
16649      *        not limited. The minimum non-zero value corresponds to 72 hours. If an admin sets a
16650      *        smaller non-zero vaulue, 72 hours will be set instead.
16651      * @throws IllegalStateException if the profile owner doesn't have an activity that handles
16652      *        {@link #ACTION_CHECK_POLICY_COMPLIANCE}
16653      * @see #setPersonalAppsSuspended
16654      */
setManagedProfileMaximumTimeOff(@onNull ComponentName admin, long timeoutMillis)16655     public void setManagedProfileMaximumTimeOff(@NonNull ComponentName admin, long timeoutMillis) {
16656         throwIfParentInstance("setManagedProfileMaximumTimeOff");
16657         if (mService != null) {
16658             try {
16659                 mService.setManagedProfileMaximumTimeOff(admin, timeoutMillis);
16660             } catch (RemoteException re) {
16661                 throw re.rethrowFromSystemServer();
16662             }
16663         }
16664     }
16665 
16666      /**
16667      * Called by a profile owner of an organization-owned managed profile to get maximum time
16668      * the profile is allowed to be turned off.
16669      *
16670      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
16671      * @return Maximum time the profile is allowed to be off in milliseconds or 0 if not limited.
16672      * @see #setPersonalAppsSuspended
16673      */
getManagedProfileMaximumTimeOff(@onNull ComponentName admin)16674     public long getManagedProfileMaximumTimeOff(@NonNull ComponentName admin) {
16675         throwIfParentInstance("getManagedProfileMaximumTimeOff");
16676         if (mService != null) {
16677             try {
16678                 return mService.getManagedProfileMaximumTimeOff(admin);
16679             } catch (RemoteException re) {
16680                 throw re.rethrowFromSystemServer();
16681             }
16682         }
16683         return 0;
16684     }
16685 
16686     /**
16687      * Called by a profile owner of an organization-owned managed profile to acknowledge that the
16688      * device is compliant and the user can turn the profile off if needed according to the maximum
16689      * time off policy.
16690      *
16691      * This method should be called when the device is deemed compliant after getting
16692      * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)} callback in
16693      * case it is overridden. Before this method is called the user is still free to turn the
16694      * profile off, but the timer won't be reset, so personal apps will be suspended sooner.
16695      *
16696      * DPCs only need acknowledging device compliance if they override
16697      * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)}, otherwise
16698      * compliance is acknowledged automatically.
16699      *
16700      * @throws IllegalStateException if the user isn't unlocked
16701      * @see #isComplianceAcknowledgementRequired()
16702      * @see #setManagedProfileMaximumTimeOff(ComponentName, long)
16703      * @see DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)
16704      */
acknowledgeDeviceCompliant()16705     public void acknowledgeDeviceCompliant() {
16706         throwIfParentInstance("acknowledgeDeviceCompliant");
16707         if (mService != null) {
16708             try {
16709                 mService.acknowledgeDeviceCompliant();
16710             } catch (RemoteException re) {
16711                 throw re.rethrowFromSystemServer();
16712             }
16713         }
16714     }
16715 
16716     /**
16717      * Called by a profile owner of an organization-owned managed profile to query whether it needs
16718      * to acknowledge device compliance to allow the user to turn the profile off if needed
16719      * according to the maximum profile time off policy.
16720      *
16721      * Normally when acknowledgement is needed the DPC gets a
16722      * {@link DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)} callback.
16723      * But if the callback was not delivered or handled for some reason, this method can be used to
16724      * verify if acknowledgement is needed.
16725      *
16726      * @throws IllegalStateException if the user isn't unlocked
16727      * @see #acknowledgeDeviceCompliant()
16728      * @see #setManagedProfileMaximumTimeOff(ComponentName, long)
16729      * @see DeviceAdminReceiver#onComplianceAcknowledgementRequired(Context, Intent)
16730      */
isComplianceAcknowledgementRequired()16731     public boolean isComplianceAcknowledgementRequired() {
16732         throwIfParentInstance("isComplianceAcknowledgementRequired");
16733         if (mService != null) {
16734             try {
16735                 return mService.isComplianceAcknowledgementRequired();
16736             } catch (RemoteException re) {
16737                 throw re.rethrowFromSystemServer();
16738             }
16739         }
16740         return false;
16741     }
16742 
16743     /**
16744      * Returns {@code true} when {@code userId} has a profile owner that is capable of resetting
16745      * password in RUNNING_LOCKED state. For that it should have at least one direct boot aware
16746      * component and have an active password reset token. Can only be called by the system.
16747      * @hide
16748      */
canProfileOwnerResetPasswordWhenLocked(int userId)16749     public boolean canProfileOwnerResetPasswordWhenLocked(int userId) {
16750         if (mService != null) {
16751             try {
16752                 return mService.canProfileOwnerResetPasswordWhenLocked(userId);
16753             } catch (RemoteException re) {
16754                 throw re.rethrowFromSystemServer();
16755             }
16756         }
16757         return false;
16758     }
16759 
16760     /**
16761      * Used by CTS to set the result of the next safety operation check.
16762      *
16763      * @hide
16764      */
16765     @TestApi
16766     @RequiresPermission(MANAGE_DEVICE_ADMINS)
setNextOperationSafety(@evicePolicyOperation int operation, @OperationSafetyReason int reason)16767     public void setNextOperationSafety(@DevicePolicyOperation int operation,
16768             @OperationSafetyReason int reason) {
16769         if (mService != null) {
16770             try {
16771                 mService.setNextOperationSafety(operation, reason);
16772             } catch (RemoteException re) {
16773                 throw re.rethrowFromSystemServer();
16774             }
16775         }
16776     }
16777 
16778     /**
16779      * Returns an enrollment-specific identifier of this device, which is guaranteed to be the same
16780      * value for the same device, enrolled into the same organization by the same managing app.
16781      * This identifier is high-entropy, useful for uniquely identifying individual devices within
16782      * the same organisation.
16783      * It is available both in a work profile and on a fully-managed device.
16784      * The identifier would be consistent even if the work profile is removed and enrolled again
16785      * (to the same organization), or the device is factory reset and re-enrolled.
16786      *
16787      * Can only be called by the Profile Owner and Device Owner, and starting from Android
16788      * {@link android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM}, holders of the permission
16789      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES}.
16790      * If {@link #setOrganizationId(String)} was not called, then the returned value will be an
16791      * empty string.
16792      *
16793      * <p>Note about access to device identifiers: a device owner, a profile owner of an
16794      * organization-owned device or the delegated certificate installer (holding the
16795      * {@link #DELEGATION_CERT_INSTALL} delegation) on such a device can still obtain hardware
16796      * identifiers by calling e.g. {@link android.os.Build#getSerial()}, in addition to using
16797      * this method. However, a profile owner on a personal (non organization-owned) device, or the
16798      * delegated certificate installer on such a device, cannot obtain hardware identifiers anymore
16799      * and must switch to using this method.
16800      *
16801      * @return A stable, enrollment-specific identifier.
16802      * @throws SecurityException if the caller is not a profile owner, device owner or holding the
16803      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission
16804      */
16805     @RequiresPermission(value = MANAGE_DEVICE_POLICY_CERTIFICATES, conditional = true)
16806     @SuppressLint("RequiresPermission")
getEnrollmentSpecificId()16807     @NonNull public String getEnrollmentSpecificId() {
16808         throwIfParentInstance("getEnrollmentSpecificId");
16809         if (mService == null) {
16810             return "";
16811         }
16812 
16813         try {
16814             return mService.getEnrollmentSpecificId(mContext.getPackageName());
16815         } catch (RemoteException re) {
16816             throw re.rethrowFromSystemServer();
16817         }
16818     }
16819 
16820     /**
16821      * Sets the Enterprise ID for the work profile or managed device. This is a requirement for
16822      * generating an enrollment-specific ID for the device, see {@link #getEnrollmentSpecificId()}.
16823      *
16824      * It is recommended that the Enterprise ID is at least 6 characters long, and no more than
16825      * 64 characters.
16826      *
16827      * @param enterpriseId An identifier of the organization this work profile or device is
16828      *                     enrolled into.
16829      */
setOrganizationId(@onNull String enterpriseId)16830     public void setOrganizationId(@NonNull String enterpriseId) {
16831         throwIfParentInstance("setOrganizationId");
16832         setOrganizationIdForUser(mContext.getPackageName(), enterpriseId, myUserId());
16833     }
16834 
16835     /**
16836      * Sets the Enterprise ID for the work profile or managed device. This is a requirement for
16837      * generating an enrollment-specific ID for the device, see
16838      * {@link #getEnrollmentSpecificId()}.
16839      *
16840      * @hide
16841      */
setOrganizationIdForUser(@onNull String packageName, @NonNull String enterpriseId, @UserIdInt int userId)16842     public void setOrganizationIdForUser(@NonNull String packageName,
16843             @NonNull String enterpriseId, @UserIdInt int userId) {
16844         if (mService == null) {
16845             return;
16846         }
16847         try {
16848             mService.setOrganizationIdForUser(packageName, enterpriseId, userId);
16849         } catch (RemoteException re) {
16850             throw re.rethrowFromSystemServer();
16851         }
16852     }
16853 
16854     /**
16855      * Clears organization ID set by the DPC and resets the precomputed enrollment specific ID.
16856      * @hide
16857      */
16858     @TestApi
16859     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
clearOrganizationId()16860     public void clearOrganizationId() {
16861         if (mService == null) {
16862             return;
16863         }
16864         try {
16865             mService.clearOrganizationIdForUser(myUserId());
16866         } catch (RemoteException re) {
16867             throw re.rethrowFromSystemServer();
16868         }
16869     }
16870 
16871     /**
16872      * Creates and provisions a managed profile and sets the
16873      * {@link ManagedProfileProvisioningParams#getProfileAdminComponentName()} as the profile
16874      * owner.
16875      *
16876      * <p>The method {@link #checkProvisioningPrecondition} must be returning {@link #STATUS_OK}
16877      * before calling this method.
16878      *
16879      * @param provisioningParams Params required to provision a managed profile,
16880      * see {@link ManagedProfileProvisioningParams}.
16881      * @return The {@link UserHandle} of the created profile or {@code null} if the service is
16882      * not available.
16883      * @throws SecurityException if the caller does not hold
16884      * {@link android.Manifest.permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
16885      * @throws ProvisioningException if an error occurred during provisioning.
16886      * @hide
16887      */
16888     @Nullable
16889     @SystemApi
16890     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
createAndProvisionManagedProfile( @onNull ManagedProfileProvisioningParams provisioningParams)16891     public UserHandle createAndProvisionManagedProfile(
16892             @NonNull ManagedProfileProvisioningParams provisioningParams)
16893             throws ProvisioningException {
16894         if (mService == null) {
16895             return null;
16896         }
16897         try {
16898             return mService.createAndProvisionManagedProfile(
16899                     provisioningParams, mContext.getPackageName());
16900         } catch (ServiceSpecificException e) {
16901             throw new ProvisioningException(e, e.errorCode, getErrorMessage(e));
16902         } catch (RemoteException e) {
16903             throw e.rethrowFromSystemServer();
16904         }
16905     }
16906 
16907     /**
16908      * Called when a managed profile has been provisioned.
16909      *
16910      * @throws SecurityException if the caller does not hold
16911      * {@link android.Manifest.permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
16912      * @hide
16913      */
16914     @SystemApi
16915     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
finalizeWorkProfileProvisioning( @onNull UserHandle managedProfileUser, @Nullable Account migratedAccount)16916     public void finalizeWorkProfileProvisioning(
16917             @NonNull UserHandle managedProfileUser, @Nullable Account migratedAccount) {
16918         Objects.requireNonNull(managedProfileUser, "managedProfileUser can't be null");
16919         if (mService == null) {
16920             throw new IllegalStateException("Could not find DevicePolicyManagerService");
16921         }
16922         try {
16923             mService.finalizeWorkProfileProvisioning(managedProfileUser, migratedAccount);
16924         } catch (RemoteException e) {
16925             throw e.rethrowFromSystemServer();
16926         }
16927     }
16928 
16929     /**
16930      * The localized error message to show to the end-user. If {@code null}, a generic error
16931      * message will be shown.
16932      */
getErrorMessage(ServiceSpecificException e)16933     private String getErrorMessage(ServiceSpecificException e) {
16934         return null;
16935     }
16936 
16937 
16938     /**
16939      * Provisions a managed device and sets the {@code deviceAdminComponentName} as the device
16940      * owner.
16941      *
16942      * <p>The method {@link #checkProvisioningPrecondition} must be returning {@link #STATUS_OK}
16943      * before calling this method.
16944      *
16945      * <p>Holders of {@link android.Manifest.permission#PROVISION_DEMO_DEVICE} can call this API
16946      * only if {@link FullyManagedDeviceProvisioningParams#isDemoDevice()} is {@code true}.
16947      *
16948      * <p>If headless device is in {@link DeviceAdminInfo#HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER}
16949      * mode then it sets the device owner on the first secondary user.</p>
16950      *
16951      * @param provisioningParams Params required to provision a fully managed device,
16952      * see {@link FullyManagedDeviceProvisioningParams}.
16953      *
16954      * @throws ProvisioningException if an error occurred during provisioning.
16955      *
16956      * @hide
16957      */
16958     @SystemApi
16959     @RequiresPermission(anyOf = {
16960             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
16961             android.Manifest.permission.PROVISION_DEMO_DEVICE})
provisionFullyManagedDevice( @onNull FullyManagedDeviceProvisioningParams provisioningParams)16962     public void provisionFullyManagedDevice(
16963             @NonNull FullyManagedDeviceProvisioningParams provisioningParams)
16964             throws ProvisioningException {
16965         if (mService != null) {
16966             try {
16967                 mService.provisionFullyManagedDevice(provisioningParams, mContext.getPackageName());
16968             } catch (ServiceSpecificException e) {
16969                 throw new ProvisioningException(e, e.errorCode, getErrorMessage(e));
16970             } catch (RemoteException re) {
16971                 throw re.rethrowFromSystemServer();
16972             }
16973         }
16974     }
16975 
16976     /**
16977      * Resets the default cross profile intent filters that were set during
16978      * {@link #createAndProvisionManagedProfile} between {@code userId} and all it's managed
16979      * profiles if any.
16980      *
16981      * @hide
16982      */
16983     @TestApi
16984     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
resetDefaultCrossProfileIntentFilters(@serIdInt int userId)16985     public void resetDefaultCrossProfileIntentFilters(@UserIdInt int userId) {
16986         if (mService != null) {
16987             try {
16988                 mService.resetDefaultCrossProfileIntentFilters(userId);
16989             } catch (RemoteException re) {
16990                 throw re.rethrowFromSystemServer();
16991             }
16992         }
16993     }
16994 
16995     /**
16996      * Returns true if the caller is running on a device where an admin can grant
16997      * permissions related to device sensors.
16998      * This is a signal that the device is a fully-managed device where personal usage is
16999      * discouraged.
17000      * The list of permissions is listed in
17001      * {@link #setPermissionGrantState(ComponentName, String, String, int)}.
17002      *
17003      * May be called by any app.
17004      * @return true if an admin can grant device sensors-related permissions, false otherwise.
17005      */
canAdminGrantSensorsPermissions()17006     public boolean canAdminGrantSensorsPermissions() {
17007         throwIfParentInstance("canAdminGrantSensorsPermissions");
17008         if (mService == null) {
17009             return false;
17010         }
17011         try {
17012             return mService.canAdminGrantSensorsPermissions();
17013         } catch (RemoteException re) {
17014             throw re.rethrowFromSystemServer();
17015         }
17016     }
17017 
17018     /**
17019      * Sets the device owner type for a managed device (e.g. financed device).
17020      *
17021      * @param admin The {@link DeviceAdminReceiver} that is the device owner.
17022      * @param deviceOwnerType The device owner type is set to. Use
17023      * {@link #DEVICE_OWNER_TYPE_DEFAULT} for the default device owner type. Use
17024      * {@link #DEVICE_OWNER_TYPE_FINANCED} for the financed device owner type.
17025      *
17026      * @throws IllegalStateException When admin is not the device owner, or there is no device
17027      *     owner, or attempting to set the device owner type again for the same admin.
17028      * @throws SecurityException If the caller does not have the permission
17029      *     {@link permission#MANAGE_PROFILE_AND_DEVICE_OWNERS}.
17030      *
17031      * @hide
17032      */
17033     @TestApi
setDeviceOwnerType(@onNull ComponentName admin, @DeviceOwnerType int deviceOwnerType)17034     public void setDeviceOwnerType(@NonNull ComponentName admin,
17035             @DeviceOwnerType int deviceOwnerType) {
17036         throwIfParentInstance("setDeviceOwnerType");
17037         if (mService != null) {
17038             try {
17039                 mService.setDeviceOwnerType(admin, deviceOwnerType);
17040             } catch (RemoteException re) {
17041                 throw re.rethrowFromSystemServer();
17042             }
17043         }
17044     }
17045 
17046     /**
17047      * Returns the device owner type for the admin used in
17048      * {@link #setDeviceOwnerType(ComponentName, int)}. {@link #DEVICE_OWNER_TYPE_DEFAULT}
17049      * would be returned when the device owner type is not set for the device owner admin.
17050      *
17051      * @param admin The {@link DeviceAdminReceiver} that is the device owner.
17052      *
17053      * @throws IllegalStateException When admin is not the device owner or there is no device owner.
17054      *
17055      * @deprecated Use type-specific APIs (e.g. {@link #isFinancedDevice}).
17056      * @hide
17057      */
17058     @TestApi
17059     @DeviceOwnerType
17060     @Deprecated
17061     // TODO(b/259908270): remove
getDeviceOwnerType(@onNull ComponentName admin)17062     public int getDeviceOwnerType(@NonNull ComponentName admin) {
17063         throwIfParentInstance("getDeviceOwnerType");
17064         if (mService != null) {
17065             try {
17066                 return mService.getDeviceOwnerType(admin);
17067             } catch (RemoteException re) {
17068                 throw re.rethrowFromSystemServer();
17069             }
17070         }
17071         return DEVICE_OWNER_TYPE_DEFAULT;
17072     }
17073 
17074     /**
17075      * {@code true} if this device is financed.
17076      * @hide
17077      */
17078     @RequiresPermission(anyOf = {
17079             android.Manifest.permission.MANAGE_USERS,
17080             android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS
17081     })
isFinancedDevice()17082     public boolean isFinancedDevice() {
17083         return isDeviceManaged()
17084                 && getDeviceOwnerType(getDeviceOwnerComponentOnAnyUser())
17085                 == DEVICE_OWNER_TYPE_FINANCED;
17086     }
17087 
17088     // TODO(b/315298076): revert ag/25574027 and update the doc
17089     /**
17090      * Called by a device owner or profile owner of an organization-owned managed profile to enable
17091      * or disable USB data signaling for the device. When disabled, USB data connections
17092      * (except from charging functions) are prohibited.
17093      *
17094      * <p> This API is not supported on all devices, the caller should call
17095      * {@link #canUsbDataSignalingBeDisabled()} to check whether enabling or disabling USB data
17096      * signaling is supported on the device.
17097      *
17098      * Starting from Android 15, after the USB data signaling
17099      * policy has been set, {@link PolicyUpdateReceiver#onPolicySetResult(Context, String,
17100      * Bundle, TargetUser, PolicyUpdateResult)} will notify the admin on whether the policy was
17101      * successfully set or not. This callback will contain:
17102      * <ul>
17103      * <li> The {@link TargetUser} that this policy relates to
17104      * <li> The {@link PolicyUpdateResult}, which will be
17105      * {@link PolicyUpdateResult#RESULT_POLICY_SET} if the policy was successfully set or the
17106      * reason the policy failed to be set
17107      * e.g. {@link PolicyUpdateResult#RESULT_FAILURE_CONFLICTING_ADMIN_POLICY})
17108      * </ul>
17109      * If there has been a change to the policy,
17110      * {@link PolicyUpdateReceiver#onPolicyChanged(Context, String, Bundle, TargetUser,
17111      * PolicyUpdateResult)} will notify the admin of this change. This callback will contain the
17112      * same parameters as PolicyUpdateReceiver#onPolicySetResult and the {@link PolicyUpdateResult}
17113      * will contain the reason why the policy changed.
17114      *
17115      * @param enabled whether USB data signaling should be enabled or not.
17116      * @throws SecurityException if the caller is not permitted to set this policy
17117      * @throws IllegalStateException if disabling USB data signaling is not supported or
17118      * if USB data signaling fails to be enabled/disabled.
17119      */
17120     @RequiresPermission(value = MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING, conditional = true)
setUsbDataSignalingEnabled(boolean enabled)17121     public void setUsbDataSignalingEnabled(boolean enabled) {
17122         throwIfParentInstance("setUsbDataSignalingEnabled");
17123         if (mService != null) {
17124             try {
17125                 mService.setUsbDataSignalingEnabled(mContext.getPackageName(), enabled);
17126             } catch (RemoteException e) {
17127                 throw e.rethrowFromSystemServer();
17128             }
17129         }
17130     }
17131 
17132     /**
17133      * Returns whether USB data signaling is currently enabled.
17134      *
17135      * <p> When called by a device owner or profile owner of an organization-owned managed profile,
17136      * this API returns whether USB data signaling is currently enabled by that admin. When called
17137      * by any other app, returns whether USB data signaling is currently enabled on the device.
17138      *
17139      * @return {@code true} if USB data signaling is enabled, {@code false} otherwise.
17140      */
isUsbDataSignalingEnabled()17141     public boolean isUsbDataSignalingEnabled() {
17142         throwIfParentInstance("isUsbDataSignalingEnabled");
17143         if (mService != null) {
17144             try {
17145                 return mService.isUsbDataSignalingEnabled(mContext.getPackageName());
17146             } catch (RemoteException e) {
17147                 throw e.rethrowFromSystemServer();
17148             }
17149         }
17150         return true;
17151     }
17152 
17153     /**
17154      * Returns whether enabling or disabling USB data signaling is supported on the device.
17155      *
17156      * @return {@code true} if the device supports enabling and disabling USB data signaling.
17157      */
canUsbDataSignalingBeDisabled()17158     public boolean canUsbDataSignalingBeDisabled() {
17159         throwIfParentInstance("canUsbDataSignalingBeDisabled");
17160         if (mService != null) {
17161             try {
17162                 return mService.canUsbDataSignalingBeDisabled();
17163             } catch (RemoteException re) {
17164                 throw re.rethrowFromSystemServer();
17165             }
17166         }
17167         return false;
17168     }
17169 
17170     /**
17171      * Gets the list of {@link #isAffiliatedUser() affiliated} users running on foreground.
17172      *
17173      * @return list of {@link #isAffiliatedUser() affiliated} users running on foreground.
17174      *
17175      * @throws SecurityException if the calling application is not a device owner
17176      */
17177     @NonNull
listForegroundAffiliatedUsers()17178     public List<UserHandle> listForegroundAffiliatedUsers() {
17179         if (mService == null) return Collections.emptyList();
17180 
17181         try {
17182             return mService.listForegroundAffiliatedUsers();
17183         } catch (RemoteException re) {
17184             throw re.rethrowFromSystemServer();
17185         }
17186     }
17187 
17188     /**
17189      * Lists apps that are exempt from policies (such as
17190      * {@link #setPackagesSuspended(ComponentName, String[], boolean)}).
17191      *
17192      * @hide
17193      */
17194     @TestApi
17195     @RequiresPermission(value = MANAGE_DEVICE_ADMINS)
getPolicyExemptApps()17196     public @NonNull Set<String> getPolicyExemptApps() {
17197         if (mService == null) return Collections.emptySet();
17198 
17199         try {
17200             return new HashSet<>(mService.listPolicyExemptApps());
17201         } catch (RemoteException e) {
17202             throw e.rethrowFromSystemServer();
17203         }
17204     }
17205 
17206     /**
17207      * Creates a {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent
17208      * from the provided {@code nfcIntent}.
17209      *
17210      * <p>Prerequisites to create the provisioning intent:
17211      *
17212      * <ul>
17213      * <li>{@code nfcIntent}'s action is {@link NfcAdapter#ACTION_NDEF_DISCOVERED}</li>
17214      * <li>{@code nfcIntent}'s NFC properties contain either
17215      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} or
17216      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} </li>
17217      * </ul>
17218      *
17219      * This method returns {@code null} if the prerequisites are not met or if an error occurs
17220      * when reading the NFC properties.
17221      *
17222      * @param nfcIntent the nfc intent generated from scanning a NFC tag
17223      * @return a {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE} intent with
17224      * intent extras as read by {@code nfcIntent}'s NFC properties or {@code null} if the
17225      * prerequisites are not met or if an error occurs when reading the NFC properties.
17226      *
17227      * @hide
17228      */
17229     @Nullable
17230     @SystemApi
createProvisioningIntentFromNfcIntent(@onNull Intent nfcIntent)17231     public Intent createProvisioningIntentFromNfcIntent(@NonNull Intent nfcIntent) {
17232         return ProvisioningIntentHelper.createProvisioningIntentFromNfcIntent(nfcIntent);
17233     }
17234 
17235     /**
17236      * Called by device owner or profile owner of an organization-owned managed profile to
17237      * specify the minimum security level required for Wi-Fi networks.
17238      * The device may not connect to networks that do not meet the minimum security level.
17239      * If the current network does not meet the minimum security level set, it will be disconnected.
17240      *
17241      * The following shows the Wi-Fi security levels from the lowest to the highest security level:
17242      * {@link #WIFI_SECURITY_OPEN}
17243      * {@link #WIFI_SECURITY_PERSONAL}
17244      * {@link #WIFI_SECURITY_ENTERPRISE_EAP}
17245      * {@link #WIFI_SECURITY_ENTERPRISE_192}
17246      *
17247      * @param level minimum security level
17248      * @throws SecurityException if the caller is not permitted to set this policy
17249      */
17250     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true)
setMinimumRequiredWifiSecurityLevel(@ifiSecurity int level)17251     public void setMinimumRequiredWifiSecurityLevel(@WifiSecurity int level) {
17252         throwIfParentInstance("setMinimumRequiredWifiSecurityLevel");
17253         if (mService != null) {
17254             try {
17255                 mService.setMinimumRequiredWifiSecurityLevel(mContext.getPackageName(), level);
17256             } catch (RemoteException e) {
17257                 throw e.rethrowFromSystemServer();
17258             }
17259         }
17260     }
17261 
17262     /**
17263      * Returns the current Wi-Fi minimum security level.
17264      *
17265      * @see #setMinimumRequiredWifiSecurityLevel(int)
17266      */
getMinimumRequiredWifiSecurityLevel()17267     public @WifiSecurity int getMinimumRequiredWifiSecurityLevel() {
17268         throwIfParentInstance("getMinimumRequiredWifiSecurityLevel");
17269         if (mService == null) {
17270             return WIFI_SECURITY_OPEN;
17271         }
17272         try {
17273             return mService.getMinimumRequiredWifiSecurityLevel();
17274         } catch (RemoteException e) {
17275             throw e.rethrowFromSystemServer();
17276         }
17277     }
17278 
17279     /**
17280      * Called by device owner or profile owner of an organization-owned managed profile to
17281      * specify the Wi-Fi SSID policy ({@link WifiSsidPolicy}).
17282      * Wi-Fi SSID policy specifies the SSID restriction the network must satisfy
17283      * in order to be eligible for a connection. Providing a null policy results in the
17284      * deactivation of the SSID restriction
17285      *
17286      * @param policy Wi-Fi SSID policy
17287      * @throws SecurityException if the caller is not permitted to manage wifi policy
17288      */
17289     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true)
setWifiSsidPolicy(@ullable WifiSsidPolicy policy)17290     public void setWifiSsidPolicy(@Nullable WifiSsidPolicy policy) {
17291         throwIfParentInstance("setWifiSsidPolicy");
17292         if (mService == null) {
17293             return;
17294         }
17295         try {
17296             mService.setWifiSsidPolicy(mContext.getPackageName(), policy);
17297         } catch (RemoteException e) {
17298             throw e.rethrowFromSystemServer();
17299         }
17300 
17301     }
17302 
17303     /**
17304      * Returns the current Wi-Fi SSID policy.
17305      * If the policy has not been set, it will return NULL.
17306      *
17307      * @see #setWifiSsidPolicy(WifiSsidPolicy)
17308      * @throws SecurityException if the caller is not a device owner or a profile owner on
17309      * an organization-owned managed profile.
17310      */
17311     @RequiresPermission(value = MANAGE_DEVICE_POLICY_WIFI, conditional = true)
17312     @Nullable
getWifiSsidPolicy()17313     public WifiSsidPolicy getWifiSsidPolicy() {
17314         throwIfParentInstance("getWifiSsidPolicy");
17315         if (mService == null) {
17316             return null;
17317         }
17318         try {
17319             return mService.getWifiSsidPolicy(mContext.getPackageName());
17320         } catch (RemoteException e) {
17321             throw e.rethrowFromSystemServer();
17322         }
17323     }
17324 
17325     /**
17326      *
17327      * Returns whether the device considers itself to be potentially stolen.
17328      * @hide
17329      */
17330     @SystemApi
17331     @RequiresPermission(value = QUERY_DEVICE_STOLEN_STATE)
17332     @FlaggedApi(FLAG_DEVICE_THEFT_API_ENABLED)
isDevicePotentiallyStolen()17333     public boolean isDevicePotentiallyStolen() {
17334         throwIfParentInstance("isDevicePotentiallyStolen");
17335         if (mService == null) {
17336             return false;
17337         }
17338         try {
17339             return mService.isDevicePotentiallyStolen(mContext.getPackageName());
17340         } catch (RemoteException e) {
17341             throw e.rethrowFromSystemServer();
17342         }
17343     }
17344 
17345     /**
17346      * Returns a {@link DevicePolicyResourcesManager} containing the required APIs to set, reset,
17347      * and get device policy related resources.
17348      */
17349     @NonNull
getResources()17350     public DevicePolicyResourcesManager getResources() {
17351         return mResourcesManager;
17352     }
17353 
17354     /**
17355      * Returns a boolean for whether the DPC
17356      * (Device Policy Controller, the agent responsible for enforcing policy)
17357      * has been downloaded during provisioning.
17358      *
17359      * <p>If true is returned, then any attempts to begin setup again should result in factory reset
17360      *
17361      * @hide
17362      */
17363     @SystemApi
17364     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
isDpcDownloaded()17365     public boolean isDpcDownloaded() {
17366         throwIfParentInstance("isDpcDownloaded");
17367         if (mService != null) {
17368             try {
17369                 return mService.isDpcDownloaded();
17370             } catch (RemoteException e) {
17371                 throw e.rethrowFromSystemServer();
17372             }
17373         }
17374         return false;
17375     }
17376 
17377     /**
17378      * Indicates that the DPC (Device Policy Controller, the agent responsible for enforcing policy)
17379      * has or has not been downloaded during provisioning.
17380      *
17381      * @param downloaded {@code true} if the dpc has been downloaded during provisioning.
17382      *                               {@code false} otherwise.
17383      *
17384      * @hide
17385      */
17386     @SystemApi
17387     @RequiresPermission(android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
setDpcDownloaded(boolean downloaded)17388     public void setDpcDownloaded(boolean downloaded) {
17389         throwIfParentInstance("setDpcDownloaded");
17390         if (mService != null) {
17391             try {
17392                 mService.setDpcDownloaded(downloaded);
17393             } catch (RemoteException e) {
17394                 throw e.rethrowFromSystemServer();
17395             }
17396         }
17397     }
17398 
17399     /**
17400      * Returns the package name of the device policy management role holder.
17401      *
17402      * <p>If the device policy management role holder is not configured for this device, returns
17403      * {@code null}.
17404      */
17405     @Nullable
getDevicePolicyManagementRoleHolderPackage()17406     public String getDevicePolicyManagementRoleHolderPackage() {
17407         String devicePolicyManagementConfig = mContext.getString(
17408                 com.android.internal.R.string.config_devicePolicyManagement);
17409         return extractPackageNameFromDeviceManagerConfig(devicePolicyManagementConfig);
17410     }
17411 
17412     /**
17413      * Returns the package name of the device policy management role holder updater.
17414      *
17415      * <p>If the device policy management role holder updater is not configured for this device,
17416      * returns {@code null}.
17417      *
17418      * @hide
17419      */
17420     @Nullable
17421     @TestApi
getDevicePolicyManagementRoleHolderUpdaterPackage()17422     public String getDevicePolicyManagementRoleHolderUpdaterPackage() {
17423         String devicePolicyManagementUpdaterConfig = mContext.getString(
17424                 com.android.internal.R.string.config_devicePolicyManagementUpdater);
17425         if (TextUtils.isEmpty(devicePolicyManagementUpdaterConfig)) {
17426             return null;
17427         }
17428         return devicePolicyManagementUpdaterConfig;
17429     }
17430 
17431     /**
17432      * Returns a {@link List} of managed profiles managed by some profile owner within the profile
17433      * group of the given user, or an empty {@link List} if there is not one.
17434      *
17435      * @param user the user whose profile group to look within to return managed profiles
17436      *
17437      * @hide
17438      */
17439     @SystemApi
17440     @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
17441     @NonNull
getPolicyManagedProfiles(@onNull UserHandle user)17442     public List<UserHandle> getPolicyManagedProfiles(@NonNull UserHandle user) {
17443         Objects.requireNonNull(user);
17444         if (mService != null) {
17445             try {
17446                 return mService.getPolicyManagedProfiles(user);
17447             } catch (RemoteException e) {
17448                 throw e.rethrowFromSystemServer();
17449             }
17450         }
17451         return Collections.emptyList();
17452     }
17453 
17454     /**
17455      * Retrieves the package name for a given {@code deviceManagerConfig}.
17456      *
17457      * <p>Valid configs look like:
17458      * <ul>
17459      *     <li>{@code com.package.name}</li>
17460      *     <li>{@code com.package.name:<SHA256 checksum>}</li>
17461      * </ul>
17462      *
17463      * <p>If the supplied {@code deviceManagerConfig} is {@code null} or empty, returns
17464      * {@code null}.
17465      */
17466     @Nullable
extractPackageNameFromDeviceManagerConfig( @ullable String deviceManagerConfig)17467     private String extractPackageNameFromDeviceManagerConfig(
17468             @Nullable String deviceManagerConfig) {
17469         if (TextUtils.isEmpty(deviceManagerConfig)) {
17470             return null;
17471         }
17472         if (deviceManagerConfig.contains(":")) {
17473             return deviceManagerConfig.split(":")[0];
17474         }
17475         return deviceManagerConfig;
17476     }
17477 
17478     /**
17479      * Reset cache for {@link #shouldAllowBypassingDevicePolicyManagementRoleQualification}.
17480      *
17481      * @hide
17482      */
17483     @TestApi
17484     @RequiresPermission(android.Manifest.permission.MANAGE_ROLE_HOLDERS)
resetShouldAllowBypassingDevicePolicyManagementRoleQualificationState()17485     public void resetShouldAllowBypassingDevicePolicyManagementRoleQualificationState() {
17486         if (mService != null) {
17487             try {
17488                 mService.resetShouldAllowBypassingDevicePolicyManagementRoleQualificationState();
17489             } catch (RemoteException e) {
17490                 throw e.rethrowFromSystemServer();
17491             }
17492         }
17493     }
17494 
17495     /**
17496      * Recalculate the incompatible accounts cache.
17497      *
17498      * @hide
17499      */
17500     @TestApi
17501     @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
calculateHasIncompatibleAccounts()17502     public void calculateHasIncompatibleAccounts() {
17503         if (mService != null) {
17504             try {
17505                 mService.calculateHasIncompatibleAccounts();
17506             } catch (RemoteException e) {
17507                 throw e.rethrowFromSystemServer();
17508             }
17509         }
17510     }
17511 
17512     /**
17513      * @return {@code true} if bypassing the device policy management role qualification is allowed
17514      * with the current state of the device.
17515      *
17516      * @hide
17517      */
17518     @SystemApi
17519     @RequiresPermission(android.Manifest.permission.MANAGE_ROLE_HOLDERS)
shouldAllowBypassingDevicePolicyManagementRoleQualification()17520     public boolean shouldAllowBypassingDevicePolicyManagementRoleQualification() {
17521         if (mService != null) {
17522             try {
17523                 return mService.shouldAllowBypassingDevicePolicyManagementRoleQualification();
17524             } catch (RemoteException e) {
17525                 throw e.rethrowFromSystemServer();
17526             }
17527         }
17528         return false;
17529     }
17530 
17531     /**
17532      * Returns a {@link DevicePolicyState} object containing information about the current state
17533      * of device policies (e.g. values set by different admins, info about the enforcing admins,
17534      * resolved policy, etc).
17535      *
17536      * @hide
17537      */
17538     @SystemApi
17539     @NonNull
17540     @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
getDevicePolicyState()17541     public DevicePolicyState getDevicePolicyState() {
17542         if (mService != null) {
17543             try {
17544                 return mService.getDevicePolicyState();
17545             } catch (RemoteException e) {
17546                 throw e.rethrowFromSystemServer();
17547             }
17548         }
17549         return null;
17550     }
17551 
17552     /**
17553      * Triggers the data migration of device policies for existing DPCs to the Device Policy Engine.
17554      * If {@code forceMigration} is set to {@code true} it skips the prerequisite checks before
17555      * triggering the migration.
17556      *
17557      * <p>Returns {@code true} if migration was completed successfully, {@code false} otherwise.
17558      *
17559      * @hide
17560      */
17561     @TestApi
17562     @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
triggerDevicePolicyEngineMigration(boolean forceMigration)17563     public boolean triggerDevicePolicyEngineMigration(boolean forceMigration) {
17564         if (mService != null) {
17565             try {
17566                 return mService.triggerDevicePolicyEngineMigration(forceMigration);
17567             } catch (RemoteException e) {
17568                 throw e.rethrowFromSystemServer();
17569             }
17570         }
17571         return false;
17572     }
17573 
17574     /**
17575      * Returns {@code true} if this device is marked as a financed device.
17576      *
17577      * <p>A financed device can be entered into lock task mode (see {@link #setLockTaskPackages})
17578      * by the holder of the role {@code android.app.role.RoleManager#ROLE_FINANCED_DEVICE_KIOSK}.
17579      * If this occurs, Device Owners and Profile Owners that have set lock task packages or
17580      * features, or that attempt to set lock task packages or features, will receive a callback
17581      * indicating that it could not be set. See {@link PolicyUpdateReceiver#onPolicyChanged} and
17582      * {@link PolicyUpdateReceiver#onPolicySetResult}.
17583      *
17584      * <p>To be informed of changes to this status you can subscribe to the broadcast
17585      * {@link #ACTION_DEVICE_FINANCING_STATE_CHANGED}.
17586      *
17587      * @throws SecurityException if the caller is not a device owner, profile owner of an
17588      * organization-owned managed profile, profile owner on the primary user or holder of one of the
17589      * following roles: {@code android.app.role.RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT},
17590      * {@code android.app.role.RoleManager.ROLE_SYSTEM_SUPERVISION}.
17591      */
isDeviceFinanced()17592     public boolean isDeviceFinanced() {
17593         throwIfParentInstance("isDeviceFinanced");
17594         if (mService != null) {
17595             try {
17596                 return mService.isDeviceFinanced(mContext.getPackageName());
17597             } catch (RemoteException e) {
17598                 throw e.rethrowFromSystemServer();
17599             }
17600         }
17601         return false;
17602     }
17603 
17604     /**
17605      * Returns the package name of the application holding the role:
17606      * {@link android.app.role.RoleManager#ROLE_FINANCED_DEVICE_KIOSK}.
17607      *
17608      * @return the package name of the application holding the role or {@code null} if the role is
17609      * not held by any applications.
17610      * @hide
17611      */
17612     @SystemApi
17613     @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
17614     @Nullable
getFinancedDeviceKioskRoleHolder()17615     public String getFinancedDeviceKioskRoleHolder() {
17616         if (mService != null) {
17617             try {
17618                 return mService.getFinancedDeviceKioskRoleHolder(mContext.getPackageName());
17619             } catch (RemoteException e) {
17620                 throw e.rethrowFromSystemServer();
17621             }
17622         }
17623         return null;
17624     }
17625 
17626     // TODO(b/308755220): Remove once the build is finalised.
17627     /**
17628      * Returns true if the flag for the onboarding bugreport V2 is enabled.
17629      *
17630      * @hide
17631      */
17632     @UnsupportedAppUsage
isOnboardingBugreportV2FlagEnabled()17633     public boolean isOnboardingBugreportV2FlagEnabled() {
17634         return onboardingBugreportV2Enabled();
17635     }
17636 
17637     // TODO(b/308755220): Remove once the build is finalised.
17638     /**
17639      * Returns true if the flag for consentless bugreports is enabled.
17640      *
17641      * @hide
17642      */
17643     @UnsupportedAppUsage
isOnboardingConsentlessBugreportFlagEnabled()17644     public boolean isOnboardingConsentlessBugreportFlagEnabled() {
17645         return onboardingConsentlessBugreports();
17646     }
17647 
17648     /**
17649      * Returns the subscription ids of all subscriptions which were downloaded by the calling
17650      * admin.
17651      *
17652      * <p> This returns only the subscriptions which were downloaded by the calling admin via
17653      *      {@link android.telephony.euicc.EuiccManager#downloadSubscription}.
17654      *      If a subscription is returned by this method then in it subject to management controls
17655      *      and cannot be removed by users.
17656      *
17657      * <p> Callable by device owners and profile owners.
17658      *
17659      * @throws SecurityException if the caller is not authorized to call this method.
17660      * @return ids of all managed subscriptions currently downloaded by an admin on the device.
17661      */
17662     @FlaggedApi(FLAG_ESIM_MANAGEMENT_ENABLED)
17663     @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_POLICY_MANAGED_SUBSCRIPTIONS)
17664     @NonNull
getSubscriptionIds()17665     public Set<Integer> getSubscriptionIds() {
17666         throwIfParentInstance("getSubscriptionIds");
17667         if (mService != null) {
17668             try {
17669                 return intArrayToSet(mService.getSubscriptionIds(mContext.getPackageName()));
17670             } catch (RemoteException e) {
17671                 throw e.rethrowFromSystemServer();
17672             }
17673         }
17674         return new HashSet<>();
17675     }
17676 
17677     /**
17678      * Controls the maximum storage size allowed for policies associated with an admin.
17679      * Setting a limit of -1 effectively removes any storage restrictions.
17680      *
17681      * @param storageLimit Maximum storage allowed in bytes. Use -1 to disable limits.
17682      *
17683      * @hide
17684      */
17685     @SystemApi
17686     @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
17687     @FlaggedApi(FLAG_DEVICE_POLICY_SIZE_TRACKING_ENABLED)
setMaxPolicyStorageLimit(int storageLimit)17688     public void setMaxPolicyStorageLimit(int storageLimit) {
17689         if (mService != null) {
17690             try {
17691                 mService.setMaxPolicyStorageLimit(mContext.getPackageName(), storageLimit);
17692             } catch (RemoteException e) {
17693                 throw e.rethrowFromSystemServer();
17694             }
17695         }
17696     }
17697 
17698     /**
17699      * Retrieves the current maximum storage limit for policies associated with an admin.
17700      *
17701      * @return The maximum storage limit in bytes, or -1 if no limit is enforced.
17702      *
17703      * @hide
17704      */
17705     @SystemApi
17706     @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
17707     @FlaggedApi(FLAG_DEVICE_POLICY_SIZE_TRACKING_ENABLED)
getMaxPolicyStorageLimit()17708     public int getMaxPolicyStorageLimit() {
17709         if (mService != null) {
17710             try {
17711                 return mService.getMaxPolicyStorageLimit(mContext.getPackageName());
17712             } catch (RemoteException e) {
17713                 throw e.rethrowFromSystemServer();
17714             }
17715         }
17716         return -1;
17717     }
17718 
17719     /**
17720      * Force sets the maximum storage size allowed for policies associated with an admin regardless
17721      * of the default value set in the system, unlike {@link #setMaxPolicyStorageLimit} which can
17722      * only set it to a value higher than the default value set by the system.Setting a limit of -1
17723      * effectively removes any storage restrictions.
17724      *
17725      * @param storageLimit Maximum storage allowed in bytes. Use -1 to disable limits.
17726      *
17727      * @hide
17728      */
17729     @TestApi
17730     @RequiresPermission(permission.MANAGE_DEVICE_POLICY_STORAGE_LIMIT)
17731     @FlaggedApi(FLAG_DEVICE_POLICY_SIZE_TRACKING_INTERNAL_BUG_FIX_ENABLED)
forceSetMaxPolicyStorageLimit(int storageLimit)17732     public void forceSetMaxPolicyStorageLimit(int storageLimit) {
17733         if (mService != null) {
17734             try {
17735                 mService.forceSetMaxPolicyStorageLimit(mContext.getPackageName(), storageLimit);
17736             } catch (RemoteException e) {
17737                 throw e.rethrowFromSystemServer();
17738             }
17739         }
17740     }
17741 
17742     /**
17743      * Retrieves the size of the current policies set by the {@code admin}.
17744      *
17745      * @hide
17746      */
17747     @TestApi
17748     @RequiresPermission(permission.MANAGE_DEVICE_POLICY_STORAGE_LIMIT)
17749     @FlaggedApi(FLAG_DEVICE_POLICY_SIZE_TRACKING_INTERNAL_BUG_FIX_ENABLED)
getPolicySizeForAdmin(@onNull EnforcingAdmin admin)17750     public int getPolicySizeForAdmin(@NonNull EnforcingAdmin admin) {
17751         if (mService != null) {
17752             try {
17753                 return mService.getPolicySizeForAdmin(mContext.getPackageName(), admin);
17754             } catch (RemoteException e) {
17755                 throw e.rethrowFromSystemServer();
17756             }
17757         }
17758         return -1;
17759     }
17760 
17761     /**
17762      * @return The headless device owner mode for the current set DO, returns
17763      * {@link DeviceAdminInfo#HEADLESS_DEVICE_OWNER_MODE_UNSUPPORTED} if no DO is set.
17764      *
17765      * @hide
17766      */
17767     @TestApi
17768     @FlaggedApi(FLAG_HEADLESS_DEVICE_OWNER_PROVISIONING_FIX_ENABLED)
17769     @RequiresPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS)
17770     @DeviceAdminInfo.HeadlessDeviceOwnerMode
getHeadlessDeviceOwnerMode()17771     public int getHeadlessDeviceOwnerMode() {
17772         if (!Flags.headlessDeviceOwnerProvisioningFixEnabled()) {
17773             return HEADLESS_DEVICE_OWNER_MODE_UNSUPPORTED;
17774         }
17775         if (mService != null) {
17776             try {
17777                 return mService.getHeadlessDeviceOwnerMode(mContext.getPackageName());
17778             } catch (RemoteException e) {
17779                 throw e.rethrowFromSystemServer();
17780             }
17781         }
17782         return HEADLESS_DEVICE_OWNER_MODE_UNSUPPORTED;
17783     }
17784 }