1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.app.admin;
18 
19 import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
20 
21 import android.Manifest.permission;
22 import android.annotation.CallbackExecutor;
23 import android.annotation.ColorInt;
24 import android.annotation.IntDef;
25 import android.annotation.NonNull;
26 import android.annotation.Nullable;
27 import android.annotation.RequiresFeature;
28 import android.annotation.RequiresPermission;
29 import android.annotation.SdkConstant;
30 import android.annotation.SdkConstant.SdkConstantType;
31 import android.annotation.StringDef;
32 import android.annotation.SuppressLint;
33 import android.annotation.SystemApi;
34 import android.annotation.SystemService;
35 import android.annotation.TestApi;
36 import android.annotation.UserHandleAware;
37 import android.annotation.UserIdInt;
38 import android.annotation.WorkerThread;
39 import android.app.Activity;
40 import android.app.IServiceConnection;
41 import android.app.KeyguardManager;
42 import android.app.admin.SecurityLog.SecurityEvent;
43 import android.compat.annotation.UnsupportedAppUsage;
44 import android.content.ComponentName;
45 import android.content.Context;
46 import android.content.Intent;
47 import android.content.IntentFilter;
48 import android.content.ServiceConnection;
49 import android.content.pm.ApplicationInfo;
50 import android.content.pm.IPackageDataObserver;
51 import android.content.pm.PackageManager;
52 import android.content.pm.PackageManager.NameNotFoundException;
53 import android.content.pm.ParceledListSlice;
54 import android.content.pm.UserInfo;
55 import android.graphics.Bitmap;
56 import android.net.NetworkUtils;
57 import android.net.PrivateDnsConnectivityChecker;
58 import android.net.ProxyInfo;
59 import android.net.Uri;
60 import android.os.Build;
61 import android.os.Bundle;
62 import android.os.ParcelFileDescriptor;
63 import android.os.Parcelable;
64 import android.os.PersistableBundle;
65 import android.os.Process;
66 import android.os.RemoteCallback;
67 import android.os.RemoteException;
68 import android.os.ServiceSpecificException;
69 import android.os.UserHandle;
70 import android.os.UserManager;
71 import android.os.UserManager.UserOperationException;
72 import android.os.UserManager.UserOperationResult;
73 import android.provider.CalendarContract;
74 import android.provider.ContactsContract.Directory;
75 import android.provider.Settings;
76 import android.security.AttestedKeyPair;
77 import android.security.Credentials;
78 import android.security.KeyChain;
79 import android.security.KeyChainException;
80 import android.security.keymaster.KeymasterCertificateChain;
81 import android.security.keystore.AttestationUtils;
82 import android.security.keystore.KeyAttestationException;
83 import android.security.keystore.KeyGenParameterSpec;
84 import android.security.keystore.ParcelableKeyGenParameterSpec;
85 import android.security.keystore.StrongBoxUnavailableException;
86 import android.service.restrictions.RestrictionsReceiver;
87 import android.telephony.TelephonyManager;
88 import android.telephony.data.ApnSetting;
89 import android.util.ArraySet;
90 import android.util.Log;
91 
92 import com.android.internal.annotations.VisibleForTesting;
93 import com.android.internal.os.BackgroundThread;
94 import com.android.internal.util.Preconditions;
95 import com.android.org.conscrypt.TrustedCertificateStore;
96 
97 import java.io.ByteArrayInputStream;
98 import java.io.FileNotFoundException;
99 import java.io.IOException;
100 import java.lang.annotation.Retention;
101 import java.lang.annotation.RetentionPolicy;
102 import java.net.InetSocketAddress;
103 import java.net.Proxy;
104 import java.security.KeyFactory;
105 import java.security.KeyPair;
106 import java.security.NoSuchAlgorithmException;
107 import java.security.PrivateKey;
108 import java.security.cert.Certificate;
109 import java.security.cert.CertificateException;
110 import java.security.cert.CertificateFactory;
111 import java.security.cert.X509Certificate;
112 import java.security.spec.InvalidKeySpecException;
113 import java.security.spec.PKCS8EncodedKeySpec;
114 import java.util.ArrayList;
115 import java.util.Arrays;
116 import java.util.Collections;
117 import java.util.HashSet;
118 import java.util.List;
119 import java.util.Objects;
120 import java.util.Set;
121 import java.util.concurrent.CompletableFuture;
122 import java.util.concurrent.ExecutionException;
123 import java.util.concurrent.Executor;
124 
125 /**
126  * Public interface for managing policies enforced on a device. Most clients of this class must be
127  * registered with the system as a <a href="{@docRoot}guide/topics/admin/device-admin.html">device
128  * administrator</a>. Additionally, a device administrator may be registered as either a profile or
129  * device owner. A given method is accessible to all device administrators unless the documentation
130  * for that method specifies that it is restricted to either device or profile owners. Any
131  * application calling an api may only pass as an argument a device administrator component it
132  * owns. Otherwise, a {@link SecurityException} will be thrown.
133  * <div class="special reference">
134  * <h3>Developer Guides</h3>
135  * <p>
136  * For more information about managing policies for device administration, read the <a href=
137  * "{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a> developer
138  * guide. </div>
139  */
140 @SystemService(Context.DEVICE_POLICY_SERVICE)
141 @RequiresFeature(PackageManager.FEATURE_DEVICE_ADMIN)
142 public class DevicePolicyManager {
143 
144     private static String TAG = "DevicePolicyManager";
145 
146     private final Context mContext;
147     private final IDevicePolicyManager mService;
148     private final boolean mParentInstance;
149 
150     /** @hide */
DevicePolicyManager(Context context, IDevicePolicyManager service)151     public DevicePolicyManager(Context context, IDevicePolicyManager service) {
152         this(context, service, false);
153     }
154 
155     /** @hide */
156     @VisibleForTesting
DevicePolicyManager(Context context, IDevicePolicyManager service, boolean parentInstance)157     protected DevicePolicyManager(Context context, IDevicePolicyManager service,
158             boolean parentInstance) {
159         mContext = context;
160         mService = service;
161         mParentInstance = parentInstance;
162     }
163 
164     /** @hide test will override it. */
165     @VisibleForTesting
myUserId()166     protected int myUserId() {
167         return mContext.getUserId();
168     }
169 
170     /**
171      * Activity action: Starts the provisioning flow which sets up a managed profile.
172      *
173      * <p>A managed profile allows data separation for example for the usage of a
174      * device as a personal and corporate device. The user which provisioning is started from and
175      * the managed profile share a launcher.
176      *
177      * <p>This intent will typically be sent by a mobile device management application (MDM).
178      * Provisioning adds a managed profile and sets the MDM as the profile owner who has full
179      * control over the profile.
180      *
181      * <p>It is possible to check if provisioning is allowed or not by querying the method
182      * {@link #isProvisioningAllowed(String)}.
183      *
184      * <p>In version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this intent must contain the
185      * extra {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}.
186      * As of {@link android.os.Build.VERSION_CODES#M}, it should contain the extra
187      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead, although specifying only
188      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported.
189      *
190      * <p>The intent may also contain the following extras:
191      * <ul>
192      * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, optional </li>
193      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional, supported from
194      * {@link android.os.Build.VERSION_CODES#N}</li>
195      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
196      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
197      * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
198      * <li>{@link #EXTRA_PROVISIONING_SKIP_USER_CONSENT}, optional</li>
199      * <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION}, optional</li>
200      * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
201      * </ul>
202      *
203      * <p>When managed provisioning has completed, broadcasts are sent to the application specified
204      * in the provisioning intent. The
205      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the
206      * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in
207      * the primary profile.
208      *
209      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when managed provisioning has
210      * completed, along with the above broadcast, activity intent
211      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the profile owner.
212      *
213      * <p>If provisioning fails, the managedProfile is removed so the device returns to its
214      * previous state.
215      *
216      * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
217      * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
218      * the provisioning flow was successful, although this doesn't guarantee the full flow will
219      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
220      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
221      */
222     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
223     public static final String ACTION_PROVISION_MANAGED_PROFILE
224         = "android.app.action.PROVISION_MANAGED_PROFILE";
225 
226     /**
227      * Activity action: Starts the provisioning flow which sets up a managed user.
228      *
229      * <p>This intent will typically be sent by a mobile device management application (MDM).
230      * Provisioning configures the user as managed user and sets the MDM as the profile
231      * owner who has full control over the user. Provisioning can only happen before user setup has
232      * been completed. Use {@link #isProvisioningAllowed(String)} to check if provisioning is
233      * allowed.
234      *
235      * <p>The intent contains the following extras:
236      * <ul>
237      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
238      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
239      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
240      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
241      * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
242      * </ul>
243      *
244      * <p>If provisioning fails, the device returns to its previous state.
245      *
246      * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
247      * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
248      * the provisioning flow was successful, although this doesn't guarantee the full flow will
249      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
250      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
251      *
252      * @hide
253      */
254     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
255     public static final String ACTION_PROVISION_MANAGED_USER
256         = "android.app.action.PROVISION_MANAGED_USER";
257 
258     /**
259      * Activity action: Starts the provisioning flow which sets up a managed device.
260      * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
261      *
262      * <p> During device owner provisioning a device admin app is set as the owner of the device.
263      * A device owner has full control over the device. The device owner can not be modified by the
264      * user.
265      *
266      * <p> A typical use case would be a device that is owned by a company, but used by either an
267      * employee or client.
268      *
269      * <p> An intent with this action can be sent only on an unprovisioned device.
270      * It is possible to check if provisioning is allowed or not by querying the method
271      * {@link #isProvisioningAllowed(String)}.
272      *
273      * <p>The intent contains the following extras:
274      * <ul>
275      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
276      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
277      * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
278      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
279      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
280      * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
281      * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
282      * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional</li>
283      * </ul>
284      *
285      * <p>When device owner provisioning has completed, an intent of the type
286      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
287      * device owner.
288      *
289      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
290      * completed, along with the above broadcast, activity intent
291      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
292      *
293      * <p>If provisioning fails, the device is factory reset.
294      *
295      * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
296      * of the provisioning flow was successful, although this doesn't guarantee the full flow will
297      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
298      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
299      */
300     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
301     public static final String ACTION_PROVISION_MANAGED_DEVICE
302         = "android.app.action.PROVISION_MANAGED_DEVICE";
303 
304     /**
305      * Activity action: launch when user provisioning completed, i.e.
306      * {@link #getUserProvisioningState()} returns one of the complete state.
307      *
308      * <p> Please note that the API behavior is not necessarily consistent across various releases,
309      * and devices, as it's contract between SetupWizard and ManagedProvisioning. The default
310      * implementation is that ManagedProvisioning launches SetupWizard in NFC provisioning only.
311      *
312      * <p> The activity must be protected by permission
313      * {@link android.Manifest.permission#BIND_DEVICE_ADMIN}, and the process must hold
314      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE} to be launched.
315      * Only one {@link ComponentName} in the entire system should be enabled, and the rest of the
316      * components are not started by this intent.
317      * @hide
318      */
319     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
320     @SystemApi
321     public static final String ACTION_STATE_USER_SETUP_COMPLETE =
322             "android.app.action.STATE_USER_SETUP_COMPLETE";
323 
324     /**
325      * Activity action: Starts the provisioning flow which sets up a managed device.
326      *
327      * <p>During device owner provisioning, a device admin app is downloaded and set as the owner of
328      * the device. A device owner has full control over the device. The device owner can not be
329      * modified by the user and the only way of resetting the device is via factory reset.
330      *
331      * <p>From version {@link android.os.Build.VERSION_CODES#Q}, the admin app can choose
332      * whether to set up a fully managed device or a managed profile. For the admin app to support
333      * this, it must have an activity with intent filter {@link #ACTION_GET_PROVISIONING_MODE} and
334      * another one with intent filter {@link #ACTION_ADMIN_POLICY_COMPLIANCE}. For example:
335      * <pre>
336      * &lt;activity
337      *     android:name=".GetProvisioningModeActivity"
338      *     android:label="@string/app_name"
339      *     android:permission="android.permission.BIND_DEVICE_ADMIN"&gt;
340      *     &lt;intent-filter&gt;
341      *         &lt;action
342      *             android:name="android.app.action.GET_PROVISIONING_MODE" /&gt;
343      *         &lt;category android:name="android.intent.category.DEFAULT" /&gt;
344      *     &lt;/intent-filter&gt;
345      * &lt;/activity&gt;
346      *
347      * &lt;activity
348      *     android:name=".PolicyComplianceActivity"
349      *     android:label="@string/app_name"
350      *     android:permission="android.permission.BIND_DEVICE_ADMIN"&gt;
351      *     &lt;intent-filter&gt;
352      *         &lt;action
353      *             android:name="android.app.action.ADMIN_POLICY_COMPLIANCE" /&gt;
354      *         &lt;category android:name="android.intent.category.DEFAULT" /&gt;
355      *     &lt;/intent-filter&gt;
356      * &lt;/activity&gt;</pre>
357      *
358      * <p>A typical use case would be a device that is owned by a company, but used by either an
359      * employee or client.
360      *
361      * <p>The provisioning message should be sent to an unprovisioned device.
362      *
363      * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
364      * by a privileged app with the permission
365      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
366      *
367      * <p>The provisioning intent contains the following properties:
368      * <ul>
369      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
370      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
371      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
372      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
373      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL}, optional</li>
374      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI}, optional</li>
375      * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
376      * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
377      * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
378      * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
379      * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
380      * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
381      * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
382      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
383      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
384      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
385      * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
386      * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
387      * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
388      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
389      * <li>{@link #EXTRA_PROVISIONING_USE_MOBILE_DATA}, optional </li>
390      * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional - when not used for
391      * cloud enrollment, NFC or QR provisioning</li>
392      * </ul>
393      *
394      * @hide
395      */
396     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
397     @SystemApi
398     public static final String ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
399             "android.app.action.PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
400 
401     /**
402      * Activity action: Starts the provisioning flow which sets up a financed device.
403      *
404      * <p>During financed device provisioning, a device admin app is downloaded and set as the owner
405      * of the device. A device owner has full control over the device. The device owner can not be
406      * modified by the user.
407      *
408      * <p>A typical use case would be a device that is bought from the reseller through financing
409      * program.
410      *
411      * <p>An intent with this action can be sent only on an unprovisioned device.
412      *
413      * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
414      * by a privileged app with the permission
415      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
416      *
417      * <p>The provisioning intent contains the following properties:
418      * <ul>
419      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
420      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
421      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
422      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
423      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL}, optional</li>
424      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI}, optional</li>
425      * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
426      * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
427      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
428      * </ul>
429      *
430      * @hide
431      */
432     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
433     @SystemApi
434     public static final String ACTION_PROVISION_FINANCED_DEVICE =
435             "android.app.action.PROVISION_FINANCED_DEVICE";
436 
437     /**
438      * Activity action: Starts the provisioning flow which sets up a managed device.
439      * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
440      *
441      * <p>NOTE: This is only supported on split system user devices, and puts the device into a
442      * management state that is distinct from that reached by
443      * {@link #ACTION_PROVISION_MANAGED_DEVICE} - specifically the device owner runs on the system
444      * user, and only has control over device-wide policies, not individual users and their data.
445      * The primary benefit is that multiple non-system users are supported when provisioning using
446      * this form of device management.
447      *
448      * <p>During device owner provisioning a device admin app is set as the owner of the device.
449      * A device owner has full control over the device. The device owner can not be modified by the
450      * user.
451      *
452      * <p>A typical use case would be a device that is owned by a company, but used by either an
453      * employee or client.
454      *
455      * <p>An intent with this action can be sent only on an unprovisioned device.
456      * It is possible to check if provisioning is allowed or not by querying the method
457      * {@link #isProvisioningAllowed(String)}.
458      *
459      * <p>The intent contains the following extras:
460      * <ul>
461      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
462      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
463      * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
464      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
465      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
466      * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
467      * </ul>
468      *
469      * <p>When device owner provisioning has completed, an intent of the type
470      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
471      * device owner.
472      *
473      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
474      * completed, along with the above broadcast, activity intent
475      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
476      *
477      * <p>If provisioning fails, the device is factory reset.
478      *
479      * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
480      * of the provisioning flow was successful, although this doesn't guarantee the full flow will
481      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
482      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
483      *
484      * @hide
485      */
486     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
487     public static final String ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE
488         = "android.app.action.PROVISION_MANAGED_SHAREABLE_DEVICE";
489 
490     /**
491      * Activity action: Finalizes management provisioning, should be used after user-setup
492      * has been completed and {@link #getUserProvisioningState()} returns one of:
493      * <ul>
494      * <li>{@link #STATE_USER_SETUP_INCOMPLETE}</li>
495      * <li>{@link #STATE_USER_SETUP_COMPLETE}</li>
496      * <li>{@link #STATE_USER_PROFILE_COMPLETE}</li>
497      * </ul>
498      *
499      * @hide
500      */
501     @SystemApi
502     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
503     public static final String ACTION_PROVISION_FINALIZATION
504             = "android.app.action.PROVISION_FINALIZATION";
505 
506     /**
507      * Action: Bugreport sharing with device owner has been accepted by the user.
508      *
509      * @hide
510      */
511     public static final String ACTION_BUGREPORT_SHARING_ACCEPTED =
512             "com.android.server.action.REMOTE_BUGREPORT_SHARING_ACCEPTED";
513 
514     /**
515      * Action: Bugreport sharing with device owner has been declined by the user.
516      *
517      * @hide
518      */
519     public static final String ACTION_BUGREPORT_SHARING_DECLINED =
520             "com.android.server.action.REMOTE_BUGREPORT_SHARING_DECLINED";
521 
522     /**
523      * Action: Bugreport has been collected and is dispatched to {@code DevicePolicyManagerService}.
524      *
525      * @hide
526      */
527     public static final String ACTION_REMOTE_BUGREPORT_DISPATCH =
528             "android.intent.action.REMOTE_BUGREPORT_DISPATCH";
529 
530     /**
531      * Extra for shared bugreport's SHA-256 hash.
532      *
533      * @hide
534      */
535     public static final String EXTRA_REMOTE_BUGREPORT_HASH =
536             "android.intent.extra.REMOTE_BUGREPORT_HASH";
537 
538     /**
539      * Extra for remote bugreport notification shown type.
540      *
541      * @hide
542      */
543     public static final String EXTRA_BUGREPORT_NOTIFICATION_TYPE =
544             "android.app.extra.bugreport_notification_type";
545 
546     /**
547      * Notification type for a started remote bugreport flow.
548      *
549      * @hide
550      */
551     public static final int NOTIFICATION_BUGREPORT_STARTED = 1;
552 
553     /**
554      * Notification type for a bugreport that has already been accepted to be shared, but is still
555      * being taken.
556      *
557      * @hide
558      */
559     public static final int NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED = 2;
560 
561     /**
562      * Notification type for a bugreport that has been taken and can be shared or declined.
563      *
564      * @hide
565      */
566     public static final int NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED = 3;
567 
568     /**
569      * Default and maximum timeout in milliseconds after which unlocking with weak auth times out,
570      * i.e. the user has to use a strong authentication method like password, PIN or pattern.
571      *
572      * @hide
573      */
574     public static final long DEFAULT_STRONG_AUTH_TIMEOUT_MS = 72 * 60 * 60 * 1000; // 72h
575 
576     /**
577      * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that
578      * allows a mobile device management application or NFC programmer application which starts
579      * managed provisioning to pass data to the management application instance after provisioning.
580      * <p>
581      * If used with {@link #ACTION_PROVISION_MANAGED_PROFILE} it can be used by the application that
582      * sends the intent to pass data to itself on the newly created profile.
583      * If used with {@link #ACTION_PROVISION_MANAGED_DEVICE} it allows passing data to the same
584      * instance of the app on the primary user.
585      * Starting from {@link android.os.Build.VERSION_CODES#M}, if used with
586      * {@link #MIME_TYPE_PROVISIONING_NFC} as part of NFC managed device provisioning, the NFC
587      * message should contain a stringified {@link java.util.Properties} instance, whose string
588      * properties will be converted into a {@link android.os.PersistableBundle} and passed to the
589      * management application after provisioning.
590      *
591      * <p>
592      * In both cases the application receives the data in
593      * {@link DeviceAdminReceiver#onProfileProvisioningComplete} via an intent with the action
594      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}. The bundle is not changed
595      * during the managed provisioning.
596      */
597     public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE =
598             "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE";
599 
600     /**
601      * A String extra holding the package name of the mobile device management application that
602      * will be set as the profile owner or device owner.
603      *
604      * <p>If an application starts provisioning directly via an intent with action
605      * {@link #ACTION_PROVISION_MANAGED_PROFILE} this package has to match the package name of the
606      * application that started provisioning. The package will be set as profile owner in that case.
607      *
608      * <p>This package is set as device owner when device owner provisioning is started by an NFC
609      * message containing an NFC record with MIME type {@link #MIME_TYPE_PROVISIONING_NFC}.
610      *
611      * <p> When this extra is set, the application must have exactly one device admin receiver.
612      * This receiver will be set as the profile or device owner and active admin.
613      *
614      * @see DeviceAdminReceiver
615      * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}. This extra is still
616      * supported, but only if there is only one device admin receiver in the package that requires
617      * the permission {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
618      */
619     @Deprecated
620     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME
621         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME";
622 
623     /**
624      * A ComponentName extra indicating the device admin receiver of the mobile device management
625      * application that will be set as the profile owner or device owner and active admin.
626      *
627      * <p>If an application starts provisioning directly via an intent with action
628      * {@link #ACTION_PROVISION_MANAGED_PROFILE} or
629      * {@link #ACTION_PROVISION_MANAGED_DEVICE} the package name of this
630      * component has to match the package name of the application that started provisioning.
631      *
632      * <p>This component is set as device owner and active admin when device owner provisioning is
633      * started by an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or by an NFC
634      * message containing an NFC record with MIME type
635      * {@link #MIME_TYPE_PROVISIONING_NFC}. For the NFC record, the component name must be
636      * flattened to a string, via {@link ComponentName#flattenToShortString()}.
637      *
638      * @see DeviceAdminReceiver
639      */
640     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME
641         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME";
642 
643     /**
644      * An {@link android.accounts.Account} extra holding the account to migrate during managed
645      * profile provisioning. If the account supplied is present in the primary user, it will be
646      * copied, along with its credentials to the managed profile and removed from the primary user.
647      *
648      * Use with {@link #ACTION_PROVISION_MANAGED_PROFILE}.
649      */
650 
651     public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
652         = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE";
653 
654     /**
655      * Boolean extra to indicate that the migrated account should be kept. This is used in
656      * conjunction with {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}. If it's set to {@code true},
657      * the account will not be removed from the primary user after it is migrated to the newly
658      * created user or profile.
659      *
660      * <p> Defaults to {@code false}
661      *
662      * <p> Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} and
663      * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}
664      */
665     public static final String EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION
666             = "android.app.extra.PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION";
667 
668     /**
669      * @deprecated From {@link android.os.Build.VERSION_CODES#O}, never used while provisioning the
670      * device.
671      */
672     @Deprecated
673     public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
674         = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
675 
676     /**
677      * A integer extra indicating the predominant color to show during the provisioning.
678      * Refer to {@link android.graphics.Color} for how the color is represented.
679      *
680      * <p>Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or
681      * {@link #ACTION_PROVISION_MANAGED_DEVICE}.
682      */
683     public static final String EXTRA_PROVISIONING_MAIN_COLOR =
684              "android.app.extra.PROVISIONING_MAIN_COLOR";
685 
686     /**
687      * A Boolean extra that can be used by the mobile device management application to skip the
688      * disabling of system apps during provisioning when set to {@code true}.
689      *
690      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
691      * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
692      */
693     public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED =
694             "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED";
695 
696     /**
697      * A String extra holding the time zone {@link android.app.AlarmManager} that the device
698      * will be set to.
699      *
700      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
701      * provisioning via an NFC bump.
702      */
703     public static final String EXTRA_PROVISIONING_TIME_ZONE
704         = "android.app.extra.PROVISIONING_TIME_ZONE";
705 
706     /**
707      * A Long extra holding the wall clock time (in milliseconds) to be set on the device's
708      * {@link android.app.AlarmManager}.
709      *
710      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
711      * provisioning via an NFC bump.
712      */
713     public static final String EXTRA_PROVISIONING_LOCAL_TIME
714         = "android.app.extra.PROVISIONING_LOCAL_TIME";
715 
716     /**
717      * A String extra holding the {@link java.util.Locale} that the device will be set to.
718      * Format: xx_yy, where xx is the language code, and yy the country code.
719      *
720      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
721      * provisioning via an NFC bump.
722      */
723     public static final String EXTRA_PROVISIONING_LOCALE
724         = "android.app.extra.PROVISIONING_LOCALE";
725 
726     /**
727      * A String extra holding the ssid of the wifi network that should be used during nfc device
728      * owner provisioning for downloading the mobile device management application.
729      *
730      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
731      * provisioning via an NFC bump.
732      */
733     public static final String EXTRA_PROVISIONING_WIFI_SSID
734         = "android.app.extra.PROVISIONING_WIFI_SSID";
735 
736     /**
737      * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
738      * is hidden or not.
739      *
740      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
741      * provisioning via an NFC bump.
742      */
743     public static final String EXTRA_PROVISIONING_WIFI_HIDDEN
744         = "android.app.extra.PROVISIONING_WIFI_HIDDEN";
745 
746     /**
747      * A String extra indicating the security type of the wifi network in
748      * {@link #EXTRA_PROVISIONING_WIFI_SSID} and could be one of {@code NONE}, {@code WPA},
749      * {@code WEP} or {@code EAP}.
750      *
751      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
752      * provisioning via an NFC bump.
753      */
754     public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE
755         = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE";
756 
757     /**
758      * A String extra holding the password of the wifi network in
759      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
760      *
761      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
762      * provisioning via an NFC bump.
763      */
764     public static final String EXTRA_PROVISIONING_WIFI_PASSWORD =
765             "android.app.extra.PROVISIONING_WIFI_PASSWORD";
766 
767     /**
768      * The EAP method of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
769      * and could be one of {@code PEAP}, {@code TLS}, {@code TTLS}, {@code PWD}, {@code SIM},
770      * {@code AKA} or {@code AKA_PRIME}. This is only used if the
771      * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
772      *
773      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
774      * provisioning via an NFC bump. It can also be used for QR code provisioning.
775      */
776     public static final String EXTRA_PROVISIONING_WIFI_EAP_METHOD =
777             "android.app.extra.PROVISIONING_WIFI_EAP_METHOD";
778 
779     /**
780      * The phase 2 authentication of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
781      * and could be one of {@code NONE}, {@code PAP}, {@code MSCHAP}, {@code MSCHAPV2}, {@code GTC},
782      * {@code SIM}, {@code AKA} or {@code AKA_PRIME}. This is only used if the
783      * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
784      *
785      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
786      * provisioning via an NFC bump. It can also be used for QR code provisioning.
787      */
788     public static final String EXTRA_PROVISIONING_WIFI_PHASE2_AUTH =
789             "android.app.extra.PROVISIONING_WIFI_PHASE2_AUTH";
790 
791     /**
792      * The CA certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This should
793      * be an X.509 certificate Base64 encoded DER format, ie. PEM representation of a certificate
794      * without header, footer and line breaks. <a href=
795      * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only
796      * used if the {@link
797      * #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
798      *
799      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
800      * provisioning via an NFC bump. It can also be used for QR code provisioning.
801      */
802     public static final String EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE =
803             "android.app.extra.PROVISIONING_WIFI_CA_CERTIFICATE";
804 
805     /**
806      * The user certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This
807      * should be an X.509 certificate and private key Base64 encoded DER format, ie. PEM
808      * representation of a certificate and key without header, footer and line breaks. <a href=
809      * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only
810      * used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
811      *
812      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
813      * provisioning via an NFC bump. It can also be used for QR code provisioning.
814      */
815     public static final String EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE =
816             "android.app.extra.PROVISIONING_WIFI_USER_CERTIFICATE";
817 
818     /**
819      * The identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used
820      * if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
821      *
822      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
823      * provisioning via an NFC bump. It can also be used for QR code provisioning.
824      */
825     public static final String EXTRA_PROVISIONING_WIFI_IDENTITY =
826             "android.app.extra.PROVISIONING_WIFI_IDENTITY";
827 
828     /**
829      * The anonymous identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is
830      * only used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
831      *
832      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
833      * provisioning via an NFC bump. It can also be used for QR code provisioning.
834      */
835 
836     public static final String EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY =
837             "android.app.extra.PROVISIONING_WIFI_ANONYMOUS_IDENTITY";
838     /**
839      * The domain of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used if
840      * the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
841      *
842      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
843      * provisioning via an NFC bump. It can also be used for QR code provisioning.
844      */
845     public static final String EXTRA_PROVISIONING_WIFI_DOMAIN =
846             "android.app.extra.PROVISIONING_WIFI_DOMAIN";
847 
848     /**
849      * A String extra holding the proxy host for the wifi network in
850      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
851      *
852      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
853      * provisioning via an NFC bump.
854      */
855     public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST
856         = "android.app.extra.PROVISIONING_WIFI_PROXY_HOST";
857 
858     /**
859      * An int extra holding the proxy port for the wifi network in
860      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
861      *
862      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
863      * provisioning via an NFC bump.
864      */
865     public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT
866         = "android.app.extra.PROVISIONING_WIFI_PROXY_PORT";
867 
868     /**
869      * A String extra holding the proxy bypass for the wifi network in
870      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
871      *
872      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
873      * provisioning via an NFC bump.
874      */
875     public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS
876         = "android.app.extra.PROVISIONING_WIFI_PROXY_BYPASS";
877 
878     /**
879      * A String extra holding the proxy auto-config (PAC) URL for the wifi network in
880      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
881      *
882      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
883      * provisioning via an NFC bump.
884      */
885     public static final String EXTRA_PROVISIONING_WIFI_PAC_URL
886         = "android.app.extra.PROVISIONING_WIFI_PAC_URL";
887 
888     /**
889      * A String extra holding a url that specifies the download location of the device admin
890      * package. When not provided it is assumed that the device admin package is already installed.
891      *
892      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
893      * provisioning via an NFC bump.
894      */
895     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION
896         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION";
897 
898     /**
899      * A String extra holding the localized name of the organization under management.
900      *
901      * The name is displayed only during provisioning.
902      *
903      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
904      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
905      *
906      * @hide
907      */
908     @SystemApi
909     public static final String EXTRA_PROVISIONING_ORGANIZATION_NAME =
910             "android.app.extra.PROVISIONING_ORGANIZATION_NAME";
911 
912     /**
913      * A String extra holding a url to the website of the device provider so the user can open it
914      * during provisioning. If the url is not HTTPS, an error will be shown.
915      *
916      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
917      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
918      *
919      * @hide
920      */
921     @SystemApi
922     public static final String EXTRA_PROVISIONING_SUPPORT_URL =
923             "android.app.extra.PROVISIONING_SUPPORT_URL";
924 
925     /**
926      * A String extra holding the localized name of the device admin package. It should be the same
927      * as the app label of the package.
928      *
929      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
930      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
931      *
932      * @hide
933      */
934     @SystemApi
935     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL =
936             "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL";
937 
938     /**
939      * A {@link Uri} extra pointing to the app icon of device admin package. This image will be
940      * shown during the provisioning.
941      * <h5>The following URI schemes are accepted:</h5>
942      * <ul>
943      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
944      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
945      * </ul>
946      *
947      * <p> It is the responsibility of the caller to provide an image with a reasonable
948      * pixel density for the device.
949      *
950      * <p> If a content: URI is passed, the intent should have the flag
951      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
952      * {@link android.content.ClipData} of the intent too.
953      *
954      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
955      * or {@link #ACTION_PROVISION_FINANCED_DEVICE}
956      *
957      * @hide
958      */
959     @SystemApi
960     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI =
961             "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI";
962 
963     /**
964      * An int extra holding a minimum required version code for the device admin package. If the
965      * device admin is already installed on the device, it will only be re-downloaded from
966      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION} if the version of the
967      * installed package is less than this version code.
968      *
969      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
970      * provisioning via an NFC bump.
971      */
972     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE
973         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE";
974 
975     /**
976      * A String extra holding a http cookie header which should be used in the http request to the
977      * url specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
978      *
979      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
980      * provisioning via an NFC bump.
981      */
982     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER
983         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER";
984 
985     /**
986      * A String extra holding the URL-safe base64 encoded SHA-256 hash of the file at download
987      * location specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
988      *
989      * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM} must be
990      * present. The provided checksum must match the checksum of the file at the download
991      * location. If the checksum doesn't match an error will be shown to the user and the user will
992      * be asked to factory reset the device.
993      *
994      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
995      * provisioning via an NFC bump.
996      *
997      * <p><strong>Note:</strong> for devices running {@link android.os.Build.VERSION_CODES#LOLLIPOP}
998      * and {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} only SHA-1 hash is supported.
999      * Starting from {@link android.os.Build.VERSION_CODES#M}, this parameter accepts SHA-256 in
1000      * addition to SHA-1. From {@link android.os.Build.VERSION_CODES#Q}, only SHA-256 hash is
1001      * supported.
1002      */
1003     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM
1004         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM";
1005 
1006     /**
1007      * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
1008      * android package archive at the download location specified in {@link
1009      * #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
1010      *
1011      * <p>The signatures of an android package archive can be obtained using
1012      * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
1013      * {@link android.content.pm.PackageManager#GET_SIGNATURES}.
1014      *
1015      * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM} must be
1016      * present. The provided checksum must match the checksum of any signature of the file at
1017      * the download location. If the checksum does not match an error will be shown to the user and
1018      * the user will be asked to factory reset the device.
1019      *
1020      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1021      * provisioning via an NFC bump.
1022      */
1023     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM
1024         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM";
1025 
1026     /**
1027      * Broadcast Action: This broadcast is sent to indicate that provisioning of a managed profile
1028      * has completed successfully.
1029      *
1030      * <p>The broadcast is limited to the primary profile, to the app specified in the provisioning
1031      * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
1032      *
1033      * <p>This intent will contain the following extras
1034      * <ul>
1035      * <li>{@link Intent#EXTRA_USER}, corresponds to the {@link UserHandle} of the managed
1036      * profile.</li>
1037      * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, corresponds to the account requested to
1038      * be migrated at provisioning time, if any.</li>
1039      * </ul>
1040      */
1041     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1042     public static final String ACTION_MANAGED_PROFILE_PROVISIONED
1043         = "android.app.action.MANAGED_PROFILE_PROVISIONED";
1044 
1045     /**
1046      * Activity action: This activity action is sent to indicate that provisioning of a managed
1047      * profile or managed device has completed successfully. It'll be sent at the same time as
1048      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast but this will be
1049      * delivered faster as it's an activity intent.
1050      *
1051      * <p>The intent is only sent to the new device or profile owner.
1052      *
1053      * @see #ACTION_PROVISION_MANAGED_PROFILE
1054      * @see #ACTION_PROVISION_MANAGED_DEVICE
1055      */
1056     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1057     public static final String ACTION_PROVISIONING_SUCCESSFUL =
1058             "android.app.action.PROVISIONING_SUCCESSFUL";
1059 
1060     /**
1061      * A boolean extra indicating whether device encryption can be skipped as part of device owner
1062      * or managed profile provisioning.
1063      *
1064      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
1065      * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
1066      *
1067      * <p>From {@link android.os.Build.VERSION_CODES#N} onwards, this is also supported for an
1068      * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
1069      */
1070     public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION =
1071              "android.app.extra.PROVISIONING_SKIP_ENCRYPTION";
1072 
1073     /**
1074      * A {@link Uri} extra pointing to a logo image. This image will be shown during the
1075      * provisioning. If this extra is not passed, a default image will be shown.
1076      * <h5>The following URI schemes are accepted:</h5>
1077      * <ul>
1078      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1079      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1080      * </ul>
1081      *
1082      * <p> It is the responsibility of the caller to provide an image with a reasonable
1083      * pixel density for the device.
1084      *
1085      * <p> If a content: URI is passed, the intent should have the flag
1086      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1087      * {@link android.content.ClipData} of the intent too.
1088      *
1089      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1090      * {@link #ACTION_PROVISION_MANAGED_DEVICE}
1091      */
1092     public static final String EXTRA_PROVISIONING_LOGO_URI =
1093             "android.app.extra.PROVISIONING_LOGO_URI";
1094 
1095     /**
1096      * A {@link Bundle}[] extra consisting of list of disclaimer headers and disclaimer contents.
1097      * Each {@link Bundle} must have both {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}
1098      * as disclaimer header, and {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} as disclaimer
1099      * content.
1100      *
1101      * <p> The extra typically contains one disclaimer from the company of mobile device
1102      * management application (MDM), and one disclaimer from the organization.
1103      *
1104      * <p> Call {@link Bundle#putParcelableArray(String, Parcelable[])} to put the {@link Bundle}[]
1105      *
1106      * <p> Maximum 3 key-value pairs can be specified. The rest will be ignored.
1107      *
1108      * <p> Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1109      * {@link #ACTION_PROVISION_MANAGED_DEVICE}
1110      */
1111     public static final String EXTRA_PROVISIONING_DISCLAIMERS =
1112             "android.app.extra.PROVISIONING_DISCLAIMERS";
1113 
1114     /**
1115      * A String extra of localized disclaimer header.
1116      *
1117      * <p> The extra is typically the company name of mobile device management application (MDM)
1118      * or the organization name.
1119      *
1120      * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
1121      *
1122      * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
1123      * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
1124      * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT}. Here is the example:
1125      *
1126      * <pre>
1127      *  &lt;meta-data
1128      *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_HEADER"
1129      *      android:resource="@string/disclaimer_header"
1130      * /&gt;</pre>
1131      */
1132     public static final String EXTRA_PROVISIONING_DISCLAIMER_HEADER =
1133             "android.app.extra.PROVISIONING_DISCLAIMER_HEADER";
1134 
1135     /**
1136      * A {@link Uri} extra pointing to disclaimer content.
1137      *
1138      * <h5>The following URI schemes are accepted:</h5>
1139      * <ul>
1140      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1141      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1142      * </ul>
1143      *
1144      * <p> Styled text is supported in the disclaimer content. The content is parsed by
1145      * {@link android.text.Html#fromHtml(String)} and displayed in a
1146      * {@link android.widget.TextView}.
1147      *
1148      * <p> If a <code>content:</code> URI is passed, URI is passed, the intent should have the flag
1149      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1150      * {@link android.content.ClipData} of the intent too.
1151      *
1152      * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
1153      *
1154      * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
1155      * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
1156      * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}. Here is the example:
1157      *
1158      * <pre>
1159      *  &lt;meta-data
1160      *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_CONTENT"
1161      *      android:resource="@string/disclaimer_content"
1162      * /&gt;</pre>
1163      */
1164     public static final String EXTRA_PROVISIONING_DISCLAIMER_CONTENT =
1165             "android.app.extra.PROVISIONING_DISCLAIMER_CONTENT";
1166 
1167     /**
1168      * A boolean extra indicating if user setup should be skipped, for when provisioning is started
1169      * during setup-wizard.
1170      *
1171      * <p>If unspecified, defaults to {@code true} to match the behavior in
1172      * {@link android.os.Build.VERSION_CODES#M} and earlier.
1173      *
1174      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or
1175      * {@link #ACTION_PROVISION_MANAGED_USER}.
1176      *
1177      * @hide
1178      */
1179     public static final String EXTRA_PROVISIONING_SKIP_USER_SETUP =
1180             "android.app.extra.PROVISIONING_SKIP_USER_SETUP";
1181 
1182     /**
1183      * A boolean extra indicating if the user consent steps from the provisioning flow should be
1184      * skipped. If unspecified, defaults to {@code false}.
1185      *
1186      * It can only be used by an existing device owner trying to create a managed profile via
1187      * {@link #ACTION_PROVISION_MANAGED_PROFILE}. Otherwise it is ignored.
1188      */
1189     public static final String EXTRA_PROVISIONING_SKIP_USER_CONSENT =
1190             "android.app.extra.PROVISIONING_SKIP_USER_CONSENT";
1191 
1192     /**
1193      * A boolean extra indicating if the education screens from the provisioning flow should be
1194      * skipped. If unspecified, defaults to {@code false}.
1195      *
1196      * <p>This extra can be set in the following ways:
1197      * <ul>
1198      * <li>By the admin app when performing the admin-integrated
1199      * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity</li>
1200      * <li>With intent action {@link #ACTION_PROVISION_MANAGED_DEVICE}</li>
1201      * </ul>
1202      *
1203      * <p>If the education screens are skipped, it is the admin application's responsibility
1204      * to display its own user education screens.
1205      */
1206     public static final String EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS =
1207             "android.app.extra.PROVISIONING_SKIP_EDUCATION_SCREENS";
1208 
1209     /**
1210      * A boolean extra indicating if mobile data should be used during NFC device owner provisioning
1211      * for downloading the mobile device management application. If {@link
1212      * #EXTRA_PROVISIONING_WIFI_SSID} is also specified, wifi network will be used instead.
1213      *
1214      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1215      * provisioning via an NFC bump.
1216      *
1217      * @hide
1218      */
1219     public static final String EXTRA_PROVISIONING_USE_MOBILE_DATA =
1220             "android.app.extra.PROVISIONING_USE_MOBILE_DATA";
1221 
1222     /**
1223      * A String extra holding the provisioning trigger. It could be one of
1224      * {@link #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT}, {@link #PROVISIONING_TRIGGER_QR_CODE},
1225      * {@link #PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER} or {@link
1226      * #PROVISIONING_TRIGGER_UNSPECIFIED}.
1227      *
1228      * <p>Use in an intent with action {@link
1229      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}.
1230      * @hide
1231      */
1232     @SystemApi
1233     public static final String EXTRA_PROVISIONING_TRIGGER =
1234             "android.app.extra.PROVISIONING_TRIGGER";
1235 
1236     /**
1237      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1238      * trigger has not been specified.
1239      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1240      * @see #PROVISIONING_TRIGGER_QR_CODE
1241      * @see #PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER
1242      * @hide
1243      */
1244     @SystemApi
1245     public static final int PROVISIONING_TRIGGER_UNSPECIFIED = 0;
1246 
1247     /**
1248      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1249      * trigger is cloud enrollment.
1250      * @see #PROVISIONING_TRIGGER_QR_CODE
1251      * @see #PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER
1252      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1253      * @hide
1254      */
1255     @SystemApi
1256     public static final int PROVISIONING_TRIGGER_CLOUD_ENROLLMENT = 1;
1257 
1258     /**
1259      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1260      * trigger is the QR code scanner.
1261      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1262      * @see #PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER
1263      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1264      * @hide
1265      */
1266     @SystemApi
1267     public static final int PROVISIONING_TRIGGER_QR_CODE = 2;
1268 
1269     /**
1270      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1271      * trigger is persistent device owner enrollment.
1272      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1273      * @see #PROVISIONING_TRIGGER_QR_CODE
1274      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1275      * @hide
1276      */
1277     @SystemApi
1278     public static final int PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER = 3;
1279 
1280     /**
1281      * This MIME type is used for starting the device owner provisioning.
1282      *
1283      * <p>During device owner provisioning a device admin app is set as the owner of the device.
1284      * A device owner has full control over the device. The device owner can not be modified by the
1285      * user and the only way of resetting the device is if the device owner app calls a factory
1286      * reset.
1287      *
1288      * <p> A typical use case would be a device that is owned by a company, but used by either an
1289      * employee or client.
1290      *
1291      * <p> The NFC message must be sent to an unprovisioned device.
1292      *
1293      * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
1294      * contains the following properties:
1295      * <ul>
1296      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
1297      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
1298      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
1299      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
1300      * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
1301      * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
1302      * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
1303      * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
1304      * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
1305      * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
1306      * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
1307      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
1308      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
1309      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
1310      * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
1311      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional, supported from {@link
1312      * android.os.Build.VERSION_CODES#M} </li>
1313      * <li>{@link #EXTRA_PROVISIONING_WIFI_EAP_METHOD}, optional, supported from {@link
1314      * android.os.Build.VERSION_CODES#Q}</li>
1315      * <li>{@link #EXTRA_PROVISIONING_WIFI_PHASE2_AUTH}, optional, supported from {@link
1316      * android.os.Build.VERSION_CODES#Q}</li>
1317      * <li>{@link #EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE}, optional, supported from {@link
1318      * android.os.Build.VERSION_CODES#Q}</li>
1319      * <li>{@link #EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE}, optional, supported from {@link
1320      * android.os.Build.VERSION_CODES#Q}</li>
1321      * <li>{@link #EXTRA_PROVISIONING_WIFI_IDENTITY}, optional, supported from {@link
1322      * android.os.Build.VERSION_CODES#Q}</li>
1323      * <li>{@link #EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY}, optional, supported from {@link
1324      * android.os.Build.VERSION_CODES#Q}</li>
1325      * <li>{@link #EXTRA_PROVISIONING_WIFI_DOMAIN}, optional, supported from {@link
1326      * android.os.Build.VERSION_CODES#Q}</li></ul>
1327      *
1328      * <p>
1329      * As of {@link android.os.Build.VERSION_CODES#M}, the properties should contain
1330      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of
1331      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only
1332      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported).
1333      */
1334     public static final String MIME_TYPE_PROVISIONING_NFC
1335         = "application/com.android.managedprovisioning";
1336 
1337     /**
1338      * Activity action: ask the user to add a new device administrator to the system.
1339      * The desired policy is the ComponentName of the policy in the
1340      * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
1341      * bring the user through adding the device administrator to the system (or
1342      * allowing them to reject it).
1343      *
1344      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1345      * field to provide the user with additional explanation (in addition
1346      * to your component's description) about what is being added.
1347      *
1348      * <p>If your administrator is already active, this will ordinarily return immediately (without
1349      * user intervention).  However, if your administrator has been updated and is requesting
1350      * additional uses-policy flags, the user will be presented with the new list.  New policies
1351      * will not be available to the updated administrator until the user has accepted the new list.
1352      */
1353     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1354     public static final String ACTION_ADD_DEVICE_ADMIN
1355             = "android.app.action.ADD_DEVICE_ADMIN";
1356 
1357     /**
1358      * @hide
1359      * Activity action: ask the user to add a new device administrator as the profile owner
1360      * for this user. Only system apps can launch this intent.
1361      *
1362      * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN}
1363      * extra field. This will invoke a UI to bring the user through adding the profile owner admin
1364      * to remotely control restrictions on the user.
1365      *
1366      * <p>The intent must be invoked via {@link Activity#startActivityForResult} to receive the
1367      * result of whether or not the user approved the action. If approved, the result will
1368      * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well
1369      * as a profile owner.
1370      *
1371      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1372      * field to provide the user with additional explanation (in addition
1373      * to your component's description) about what is being added.
1374      *
1375      * <p>If there is already a profile owner active or the caller is not a system app, the
1376      * operation will return a failure result.
1377      */
1378     @SystemApi
1379     public static final String ACTION_SET_PROFILE_OWNER
1380             = "android.app.action.SET_PROFILE_OWNER";
1381 
1382     /**
1383      * @hide
1384      * Name of the profile owner admin that controls the user.
1385      */
1386     @SystemApi
1387     public static final String EXTRA_PROFILE_OWNER_NAME
1388             = "android.app.extra.PROFILE_OWNER_NAME";
1389 
1390     /**
1391      * Broadcast action: send when any policy admin changes a policy.
1392      * This is generally used to find out when a new policy is in effect.
1393      *
1394      * If the profile owner of an organization-owned managed profile changes some user
1395      * restriction explicitly on the parent user, this broadcast will <em>not</em> be
1396      * sent to the parent user.
1397      * @hide
1398      */
1399     @UnsupportedAppUsage
1400     public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
1401             = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
1402 
1403     /**
1404      * Broadcast action: sent when the device owner is set, changed or cleared.
1405      *
1406      * This broadcast is sent only to the primary user.
1407      * @see #ACTION_PROVISION_MANAGED_DEVICE
1408      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
1409      */
1410     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1411     public static final String ACTION_DEVICE_OWNER_CHANGED
1412             = "android.app.action.DEVICE_OWNER_CHANGED";
1413 
1414     /**
1415      * Broadcast action: sent when the factory reset protection (FRP) policy is changed.
1416      *
1417      * @see #setFactoryResetProtectionPolicy
1418      * @hide
1419      */
1420     @RequiresPermission(android.Manifest.permission.MANAGE_FACTORY_RESET_PROTECTION)
1421     @SystemApi
1422     public static final String ACTION_RESET_PROTECTION_POLICY_CHANGED =
1423             "android.app.action.RESET_PROTECTION_POLICY_CHANGED";
1424 
1425     /**
1426      * The ComponentName of the administrator component.
1427      *
1428      * @see #ACTION_ADD_DEVICE_ADMIN
1429      */
1430     public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
1431 
1432     /**
1433      * An optional CharSequence providing additional explanation for why the
1434      * admin is being added.
1435      *
1436      * @see #ACTION_ADD_DEVICE_ADMIN
1437      */
1438     public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
1439 
1440     /**
1441      * Constant to indicate the feature of disabling the camera. Used as argument to
1442      * {@link #createAdminSupportIntent(String)}.
1443      * @see #setCameraDisabled(ComponentName, boolean)
1444      */
1445     public static final String POLICY_DISABLE_CAMERA = "policy_disable_camera";
1446 
1447     /**
1448      * Constant to indicate the feature of disabling screen captures. Used as argument to
1449      * {@link #createAdminSupportIntent(String)}.
1450      * @see #setScreenCaptureDisabled(ComponentName, boolean)
1451      */
1452     public static final String POLICY_DISABLE_SCREEN_CAPTURE = "policy_disable_screen_capture";
1453 
1454     /**
1455      * Constant to indicate the feature of suspending app. Use it as the value of
1456      * {@link #EXTRA_RESTRICTION}.
1457      * @hide
1458      */
1459     public static final String POLICY_SUSPEND_PACKAGES = "policy_suspend_packages";
1460 
1461     /**
1462      * A String indicating a specific restricted feature. Can be a user restriction from the
1463      * {@link UserManager}, e.g. {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the values
1464      * {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
1465      * @see #createAdminSupportIntent(String)
1466      * @hide
1467      */
1468     @TestApi @SystemApi
1469     public static final String EXTRA_RESTRICTION = "android.app.extra.RESTRICTION";
1470 
1471     /**
1472      * Activity action: have the user enter a new password.
1473      *
1474      * <p>For admin apps, this activity should be launched after using {@link
1475      * #setPasswordQuality(ComponentName, int)}, or {@link
1476      * #setPasswordMinimumLength(ComponentName, int)} to have the user enter a new password that
1477      * meets the current requirements. You can use {@link #isActivePasswordSufficient()} to
1478      * determine whether you need to have the user select a new password in order to meet the
1479      * current constraints. Upon being resumed from this activity, you can check the new
1480      * password characteristics to see if they are sufficient.
1481      *
1482      * <p>Non-admin apps can use {@link #getPasswordComplexity()} to check the current screen lock
1483      * complexity, and use this activity with extra {@link #EXTRA_PASSWORD_COMPLEXITY} to suggest
1484      * to users how complex the app wants the new screen lock to be. Note that both {@link
1485      * #getPasswordComplexity()} and the extra {@link #EXTRA_PASSWORD_COMPLEXITY} require the
1486      * calling app to have the permission {@link permission#REQUEST_PASSWORD_COMPLEXITY}.
1487      *
1488      * <p>If the intent is launched from within a managed profile with a profile
1489      * owner built against {@link android.os.Build.VERSION_CODES#M} or before,
1490      * this will trigger entering a new password for the parent of the profile.
1491      * For all other cases it will trigger entering a new password for the user
1492      * or profile it is launched from.
1493      *
1494      * @see #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1495      */
1496     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1497     public static final String ACTION_SET_NEW_PASSWORD
1498             = "android.app.action.SET_NEW_PASSWORD";
1499 
1500     /**
1501      * An integer indicating the complexity level of the new password an app would like the user to
1502      * set when launching the action {@link #ACTION_SET_NEW_PASSWORD}.
1503      *
1504      * <p>Must be one of
1505      * <ul>
1506      *     <li>{@link #PASSWORD_COMPLEXITY_HIGH}
1507      *     <li>{@link #PASSWORD_COMPLEXITY_MEDIUM}
1508      *     <li>{@link #PASSWORD_COMPLEXITY_LOW}
1509      *     <li>{@link #PASSWORD_COMPLEXITY_NONE}
1510      * </ul>
1511      *
1512      * <p>If an invalid value is used, it will be treated as {@link #PASSWORD_COMPLEXITY_NONE}.
1513      */
1514     @RequiresPermission(android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY)
1515     public static final String EXTRA_PASSWORD_COMPLEXITY =
1516             "android.app.extra.PASSWORD_COMPLEXITY";
1517 
1518     /**
1519      * Constant for {@link #getPasswordComplexity()}: no password.
1520      *
1521      * <p>Note that these complexity constants are ordered so that higher values are more complex.
1522      */
1523     public static final int PASSWORD_COMPLEXITY_NONE = 0;
1524 
1525     /**
1526      * Constant for {@link #getPasswordComplexity()}: password satisfies one of the following:
1527      * <ul>
1528      * <li>pattern
1529      * <li>PIN with repeating (4444) or ordered (1234, 4321, 2468) sequences
1530      * </ul>
1531      *
1532      * <p>Note that these complexity constants are ordered so that higher values are more complex.
1533      *
1534      * @see #PASSWORD_QUALITY_SOMETHING
1535      * @see #PASSWORD_QUALITY_NUMERIC
1536      */
1537     public static final int PASSWORD_COMPLEXITY_LOW = 0x10000;
1538 
1539     /**
1540      * Constant for {@link #getPasswordComplexity()}: password satisfies one of the following:
1541      * <ul>
1542      * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
1543      * least 4
1544      * <li>alphabetic, length at least 4
1545      * <li>alphanumeric, length at least 4
1546      * </ul>
1547      *
1548      * <p>Note that these complexity constants are ordered so that higher values are more complex.
1549      *
1550      * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX
1551      * @see #PASSWORD_QUALITY_ALPHABETIC
1552      * @see #PASSWORD_QUALITY_ALPHANUMERIC
1553      */
1554     public static final int PASSWORD_COMPLEXITY_MEDIUM = 0x30000;
1555 
1556     /**
1557      * Constant for {@link #getPasswordComplexity()}: password satisfies one of the following:
1558      * <ul>
1559      * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
1560      * least 8
1561      * <li>alphabetic, length at least 6
1562      * <li>alphanumeric, length at least 6
1563      * </ul>
1564      *
1565      * <p>Note that these complexity constants are ordered so that higher values are more complex.
1566      *
1567      * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX
1568      * @see #PASSWORD_QUALITY_ALPHABETIC
1569      * @see #PASSWORD_QUALITY_ALPHANUMERIC
1570      */
1571     public static final int PASSWORD_COMPLEXITY_HIGH = 0x50000;
1572 
1573     /**
1574      * @hide
1575      */
1576     @Retention(RetentionPolicy.SOURCE)
1577     @IntDef(prefix = {"PASSWORD_COMPLEXITY_"}, value = {
1578             PASSWORD_COMPLEXITY_NONE,
1579             PASSWORD_COMPLEXITY_LOW,
1580             PASSWORD_COMPLEXITY_MEDIUM,
1581             PASSWORD_COMPLEXITY_HIGH,
1582     })
1583     public @interface PasswordComplexity {}
1584 
1585     /**
1586      * Activity action: have the user enter a new password for the parent profile.
1587      * If the intent is launched from within a managed profile, this will trigger
1588      * entering a new password for the parent of the profile. In all other cases
1589      * the behaviour is identical to {@link #ACTION_SET_NEW_PASSWORD}.
1590      */
1591     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1592     public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1593             = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD";
1594 
1595     /**
1596      * Broadcast action: Tell the status bar to open the device monitoring dialog, e.g. when
1597      * Network logging was enabled and the user tapped the notification.
1598      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1599      * @hide
1600      */
1601     public static final String ACTION_SHOW_DEVICE_MONITORING_DIALOG
1602             = "android.app.action.SHOW_DEVICE_MONITORING_DIALOG";
1603 
1604     /**
1605      * Broadcast Action: Sent after application delegation scopes are changed. The new delegation
1606      * scopes will be sent in an {@code ArrayList<String>} extra identified by the
1607      * {@link #EXTRA_DELEGATION_SCOPES} key.
1608      *
1609      * <p class="note"><b>Note:</b> This is a protected intent that can only be sent by the
1610      * system.</p>
1611      */
1612     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1613     public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED =
1614             "android.app.action.APPLICATION_DELEGATION_SCOPES_CHANGED";
1615 
1616     /**
1617      * An {@code ArrayList<String>} corresponding to the delegation scopes given to an app in the
1618      * {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} broadcast.
1619      */
1620     public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES";
1621 
1622     /**
1623      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1624      * the parent profile to access intents sent from the managed profile.
1625      * That is, when an app in the managed profile calls
1626      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1627      * matching activity in the parent profile.
1628      */
1629     public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
1630 
1631     /**
1632      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1633      * the managed profile to access intents sent from the parent profile.
1634      * That is, when an app in the parent profile calls
1635      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1636      * matching activity in the managed profile.
1637      */
1638     public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
1639 
1640     /**
1641      * Broadcast action: notify that a new local system update policy has been set by the device
1642      * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
1643      */
1644     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1645     public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
1646             = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
1647 
1648     /**
1649      * Broadcast action to notify ManagedProvisioning that
1650      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has changed.
1651      * @hide
1652      */
1653     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1654     public static final String ACTION_DATA_SHARING_RESTRICTION_CHANGED =
1655             "android.app.action.DATA_SHARING_RESTRICTION_CHANGED";
1656 
1657     /**
1658      * Broadcast action from ManagedProvisioning to notify that the latest change to
1659      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has been successfully
1660      * applied (cross profile intent filters updated). Only usesd for CTS tests.
1661      * @hide
1662      */
1663     @TestApi
1664     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1665     public static final String ACTION_DATA_SHARING_RESTRICTION_APPLIED =
1666             "android.app.action.DATA_SHARING_RESTRICTION_APPLIED";
1667 
1668     /**
1669      * Permission policy to prompt user for new permission requests for runtime permissions.
1670      * Already granted or denied permissions are not affected by this.
1671      */
1672     public static final int PERMISSION_POLICY_PROMPT = 0;
1673 
1674     /**
1675      * Permission policy to always grant new permission requests for runtime permissions.
1676      * Already granted or denied permissions are not affected by this.
1677      */
1678     public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
1679 
1680     /**
1681      * Permission policy to always deny new permission requests for runtime permissions.
1682      * Already granted or denied permissions are not affected by this.
1683      */
1684     public static final int PERMISSION_POLICY_AUTO_DENY = 2;
1685 
1686     /**
1687      * Possible policy values for permissions.
1688      *
1689      * @hide
1690      */
1691     @IntDef(prefix = { "PERMISSION_GRANT_STATE_" }, value = {
1692             PERMISSION_GRANT_STATE_DEFAULT,
1693             PERMISSION_GRANT_STATE_GRANTED,
1694             PERMISSION_GRANT_STATE_DENIED
1695     })
1696     @Retention(RetentionPolicy.SOURCE)
1697     public @interface PermissionGrantState {}
1698 
1699     /**
1700      * Runtime permission state: The user can manage the permission
1701      * through the UI.
1702      */
1703     public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
1704 
1705     /**
1706      * Runtime permission state: The permission is granted to the app
1707      * and the user cannot manage the permission through the UI.
1708      */
1709     public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
1710 
1711     /**
1712      * Runtime permission state: The permission is denied to the app
1713      * and the user cannot manage the permission through the UI.
1714      */
1715     public static final int PERMISSION_GRANT_STATE_DENIED = 2;
1716 
1717     /**
1718      * Delegation of certificate installation and management. This scope grants access to the
1719      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
1720      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair} APIs.
1721      */
1722     public static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
1723 
1724     /**
1725      * Delegation of application restrictions management. This scope grants access to the
1726      * {@link #setApplicationRestrictions} and {@link #getApplicationRestrictions} APIs.
1727      */
1728     public static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions";
1729 
1730     /**
1731      * Delegation of application uninstall block. This scope grants access to the
1732      * {@link #setUninstallBlocked} API.
1733      */
1734     public static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall";
1735 
1736     /**
1737      * Delegation of permission policy and permission grant state. This scope grants access to the
1738      * {@link #setPermissionPolicy}, {@link #getPermissionGrantState},
1739      * and {@link #setPermissionGrantState} APIs.
1740      */
1741     public static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant";
1742 
1743     /**
1744      * Delegation of package access state. This scope grants access to the
1745      * {@link #isApplicationHidden}, {@link #setApplicationHidden}, {@link #isPackageSuspended}, and
1746      * {@link #setPackagesSuspended} APIs.
1747      */
1748     public static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
1749 
1750     /**
1751      * Delegation for enabling system apps. This scope grants access to the {@link #enableSystemApp}
1752      * API.
1753      */
1754     public static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app";
1755 
1756     /**
1757      * Delegation for installing existing packages. This scope grants access to the
1758      * {@link #installExistingPackage} API.
1759      */
1760     public static final String DELEGATION_INSTALL_EXISTING_PACKAGE =
1761             "delegation-install-existing-package";
1762 
1763     /**
1764      * Delegation of management of uninstalled packages. This scope grants access to the
1765      * {@link #setKeepUninstalledPackages} and {@link #getKeepUninstalledPackages} APIs.
1766      */
1767     public static final String DELEGATION_KEEP_UNINSTALLED_PACKAGES =
1768             "delegation-keep-uninstalled-packages";
1769 
1770     /**
1771      * Grants access to {@link #setNetworkLoggingEnabled}, {@link #isNetworkLoggingEnabled} and
1772      * {@link #retrieveNetworkLogs}. Once granted the delegated app will start receiving
1773      * DelegatedAdminReceiver.onNetworkLogsAvailable() callback, and Device owner will no longer
1774      * receive the DeviceAdminReceiver.onNetworkLogsAvailable() callback.
1775      * There can be at most one app that has this delegation.
1776      * If another app already had delegated network logging access,
1777      * it will lose the delegation when a new app is delegated.
1778      *
1779      * <p> Can only be granted by Device Owner.
1780      */
1781     public static final String DELEGATION_NETWORK_LOGGING = "delegation-network-logging";
1782 
1783     /**
1784      * Grants access to selection of KeyChain certificates on behalf of requesting apps.
1785      * Once granted the app will start receiving
1786      * {@link DelegatedAdminReceiver#onChoosePrivateKeyAlias}. The caller (PO/DO) will
1787      * no longer receive {@link DeviceAdminReceiver#onChoosePrivateKeyAlias}.
1788      * There can be at most one app that has this delegation.
1789      * If another app already had delegated certificate selection access,
1790      * it will lose the delegation when a new app is delegated.
1791      * <p> The delegaetd app can also call {@link #grantKeyPairToApp} and
1792      * {@link #revokeKeyPairFromApp} to directly grant KeyCain keys to other apps.
1793      * <p> Can be granted by Device Owner or Profile Owner.
1794      */
1795     public static final String DELEGATION_CERT_SELECTION = "delegation-cert-selection";
1796 
1797     /**
1798      * No management for current user in-effect. This is the default.
1799      * @hide
1800      */
1801     @SystemApi
1802     public static final int STATE_USER_UNMANAGED = 0;
1803 
1804     /**
1805      * Management partially setup, user setup needs to be completed.
1806      * @hide
1807      */
1808     @SystemApi
1809     public static final int STATE_USER_SETUP_INCOMPLETE = 1;
1810 
1811     /**
1812      * Management partially setup, user setup completed.
1813      * @hide
1814      */
1815     @SystemApi
1816     public static final int STATE_USER_SETUP_COMPLETE = 2;
1817 
1818     /**
1819      * Management setup and active on current user.
1820      * @hide
1821      */
1822     @SystemApi
1823     public static final int STATE_USER_SETUP_FINALIZED = 3;
1824 
1825     /**
1826      * Management partially setup on a managed profile.
1827      * @hide
1828      */
1829     @SystemApi
1830     public static final int STATE_USER_PROFILE_COMPLETE = 4;
1831 
1832     /**
1833      * @hide
1834      */
1835     @IntDef(prefix = { "STATE_USER_" }, value = {
1836             STATE_USER_UNMANAGED,
1837             STATE_USER_SETUP_INCOMPLETE,
1838             STATE_USER_SETUP_COMPLETE,
1839             STATE_USER_SETUP_FINALIZED,
1840             STATE_USER_PROFILE_COMPLETE
1841     })
1842     @Retention(RetentionPolicy.SOURCE)
1843     public @interface UserProvisioningState {}
1844 
1845     /**
1846      * Result code for {@link #checkProvisioningPreCondition}.
1847      *
1848      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1849      * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1850      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when provisioning is allowed.
1851      *
1852      * @hide
1853      */
1854     public static final int CODE_OK = 0;
1855 
1856     /**
1857      * Result code for {@link #checkProvisioningPreCondition}.
1858      *
1859      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1860      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the device already has a device
1861      * owner.
1862      *
1863      * @hide
1864      */
1865     public static final int CODE_HAS_DEVICE_OWNER = 1;
1866 
1867     /**
1868      * Result code for {@link #checkProvisioningPreCondition}.
1869      *
1870      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1871      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user has a profile owner and for
1872      * {@link #ACTION_PROVISION_MANAGED_PROFILE} when the profile owner is already set.
1873      *
1874      * @hide
1875      */
1876     public static final int CODE_USER_HAS_PROFILE_OWNER = 2;
1877 
1878     /**
1879      * Result code for {@link #checkProvisioningPreCondition}.
1880      *
1881      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1882      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user isn't running.
1883      *
1884      * @hide
1885      */
1886     public static final int CODE_USER_NOT_RUNNING = 3;
1887 
1888     /**
1889      * Result code for {@link #checkProvisioningPreCondition}.
1890      *
1891      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1892      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the device has already been setup and
1893      * for {@link #ACTION_PROVISION_MANAGED_USER} if the user has already been setup.
1894      *
1895      * @hide
1896      */
1897     public static final int CODE_USER_SETUP_COMPLETED = 4;
1898 
1899     /**
1900      * Code used to indicate that the device also has a user other than the system user.
1901      *
1902      * @hide
1903      */
1904     public static final int CODE_NONSYSTEM_USER_EXISTS = 5;
1905 
1906     /**
1907      * Code used to indicate that device has an account that prevents provisioning.
1908      *
1909      * @hide
1910      */
1911     public static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
1912 
1913     /**
1914      * Result code for {@link #checkProvisioningPreCondition}.
1915      *
1916      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1917      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the user is not a system user.
1918      *
1919      * @hide
1920      */
1921     public static final int CODE_NOT_SYSTEM_USER = 7;
1922 
1923     /**
1924      * Result code for {@link #checkProvisioningPreCondition}.
1925      *
1926      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1927      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} and {@link #ACTION_PROVISION_MANAGED_USER}
1928      * when the device is a watch and is already paired.
1929      *
1930      * @hide
1931      */
1932     public static final int CODE_HAS_PAIRED = 8;
1933 
1934     /**
1935      * Result code for {@link #checkProvisioningPreCondition}.
1936      *
1937      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} and
1938      * {@link #ACTION_PROVISION_MANAGED_USER} on devices which do not support managed users.
1939      *
1940      * @see {@link PackageManager#FEATURE_MANAGED_USERS}
1941      * @hide
1942      */
1943     public static final int CODE_MANAGED_USERS_NOT_SUPPORTED = 9;
1944 
1945     /**
1946      * Result code for {@link #checkProvisioningPreCondition}.
1947      *
1948      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} if the user is a system user.
1949      *
1950      * @hide
1951      */
1952     public static final int CODE_SYSTEM_USER = 10;
1953 
1954     /**
1955      * Result code for {@link #checkProvisioningPreCondition}.
1956      *
1957      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the user cannot have more
1958      * managed profiles.
1959      *
1960      * @hide
1961      */
1962     public static final int CODE_CANNOT_ADD_MANAGED_PROFILE = 11;
1963 
1964     /**
1965      * Result code for {@link #checkProvisioningPreCondition}.
1966      *
1967      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} and
1968      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices not running with split system
1969      * user.
1970      *
1971      * @hide
1972      */
1973     public static final int CODE_NOT_SYSTEM_USER_SPLIT = 12;
1974 
1975     /**
1976      * Result code for {@link #checkProvisioningPreCondition}.
1977      *
1978      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1979      * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1980      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices which do no support device
1981      * admins.
1982      *
1983      * @hide
1984      */
1985     public static final int CODE_DEVICE_ADMIN_NOT_SUPPORTED = 13;
1986 
1987     /**
1988      * Result code for {@link #checkProvisioningPreCondition}.
1989      *
1990      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the device the user is a
1991      * system user on a split system user device.
1992      *
1993      * @hide
1994      */
1995     public static final int CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER = 14;
1996 
1997     /**
1998      * Result codes for {@link #checkProvisioningPreCondition} indicating all the provisioning pre
1999      * conditions.
2000      *
2001      * @hide
2002      */
2003     @Retention(RetentionPolicy.SOURCE)
2004     @IntDef(prefix = { "CODE_" }, value = {
2005             CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
2006             CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER, CODE_HAS_PAIRED,
2007             CODE_MANAGED_USERS_NOT_SUPPORTED, CODE_SYSTEM_USER, CODE_CANNOT_ADD_MANAGED_PROFILE,
2008             CODE_NOT_SYSTEM_USER_SPLIT, CODE_DEVICE_ADMIN_NOT_SUPPORTED,
2009             CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER
2010     })
2011     public @interface ProvisioningPreCondition {}
2012 
2013     /**
2014      * Disable all configurable SystemUI features during LockTask mode. This includes,
2015      * <ul>
2016      *     <li>system info area in the status bar (connectivity icons, clock, etc.)
2017      *     <li>notifications (including alerts, icons, and the notification shade)
2018      *     <li>Home button
2019      *     <li>Recents button and UI
2020      *     <li>global actions menu (i.e. power button menu)
2021      *     <li>keyguard
2022      * </ul>
2023      *
2024      * @see #setLockTaskFeatures(ComponentName, int)
2025      */
2026     public static final int LOCK_TASK_FEATURE_NONE = 0;
2027 
2028     /**
2029      * Enable the system info area in the status bar during LockTask mode. The system info area
2030      * usually occupies the right side of the status bar (although this can differ across OEMs). It
2031      * includes all system information indicators, such as date and time, connectivity, battery,
2032      * vibration mode, etc.
2033      *
2034      * @see #setLockTaskFeatures(ComponentName, int)
2035      */
2036     public static final int LOCK_TASK_FEATURE_SYSTEM_INFO = 1;
2037 
2038     /**
2039      * Enable notifications during LockTask mode. This includes notification icons on the status
2040      * bar, heads-up notifications, and the expandable notification shade. Note that the Quick
2041      * Settings panel remains disabled. This feature flag can only be used in combination with
2042      * {@link #LOCK_TASK_FEATURE_HOME}. {@link #setLockTaskFeatures(ComponentName, int)}
2043      * throws an {@link IllegalArgumentException} if this feature flag is defined without
2044      * {@link #LOCK_TASK_FEATURE_HOME}.
2045      *
2046      * @see #setLockTaskFeatures(ComponentName, int)
2047      */
2048     public static final int LOCK_TASK_FEATURE_NOTIFICATIONS = 1 << 1;
2049 
2050     /**
2051      * Enable the Home button during LockTask mode. Note that if a custom launcher is used, it has
2052      * to be registered as the default launcher with
2053      * {@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}, and its
2054      * package needs to be whitelisted for LockTask with
2055      * {@link #setLockTaskPackages(ComponentName, String[])}.
2056      *
2057      * @see #setLockTaskFeatures(ComponentName, int)
2058      */
2059     public static final int LOCK_TASK_FEATURE_HOME = 1 << 2;
2060 
2061     /**
2062      * Enable the Overview button and the Overview screen during LockTask mode. This feature flag
2063      * can only be used in combination with {@link #LOCK_TASK_FEATURE_HOME}, and
2064      * {@link #setLockTaskFeatures(ComponentName, int)} will throw an
2065      * {@link IllegalArgumentException} if this feature flag is defined without
2066      * {@link #LOCK_TASK_FEATURE_HOME}.
2067      *
2068      * @see #setLockTaskFeatures(ComponentName, int)
2069      */
2070     public static final int LOCK_TASK_FEATURE_OVERVIEW = 1 << 3;
2071 
2072     /**
2073      * Enable the global actions dialog during LockTask mode. This is the dialog that shows up when
2074      * the user long-presses the power button, for example. Note that the user may not be able to
2075      * power off the device if this flag is not set.
2076      *
2077      * <p>This flag is enabled by default until {@link #setLockTaskFeatures(ComponentName, int)} is
2078      * called for the first time.
2079      *
2080      * @see #setLockTaskFeatures(ComponentName, int)
2081      */
2082     public static final int LOCK_TASK_FEATURE_GLOBAL_ACTIONS = 1 << 4;
2083 
2084     /**
2085      * Enable the keyguard during LockTask mode. Note that if the keyguard is already disabled with
2086      * {@link #setKeyguardDisabled(ComponentName, boolean)}, setting this flag will have no effect.
2087      * If this flag is not set, the keyguard will not be shown even if the user has a lock screen
2088      * credential.
2089      *
2090      * @see #setLockTaskFeatures(ComponentName, int)
2091      */
2092     public static final int LOCK_TASK_FEATURE_KEYGUARD = 1 << 5;
2093 
2094     /**
2095      * Enable blocking of non-whitelisted activities from being started into a locked task.
2096      *
2097      * @see #setLockTaskFeatures(ComponentName, int)
2098      */
2099     public static final int LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK = 1 << 6;
2100 
2101     /**
2102      * Flags supplied to {@link #setLockTaskFeatures(ComponentName, int)}.
2103      *
2104      * @hide
2105      */
2106     @Retention(RetentionPolicy.SOURCE)
2107     @IntDef(flag = true, prefix = { "LOCK_TASK_FEATURE_" }, value = {
2108             LOCK_TASK_FEATURE_NONE,
2109             LOCK_TASK_FEATURE_SYSTEM_INFO,
2110             LOCK_TASK_FEATURE_NOTIFICATIONS,
2111             LOCK_TASK_FEATURE_HOME,
2112             LOCK_TASK_FEATURE_OVERVIEW,
2113             LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
2114             LOCK_TASK_FEATURE_KEYGUARD,
2115             LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK
2116     })
2117     public @interface LockTaskFeature {}
2118 
2119     /**
2120      * Service action: Action for a service that device owner and profile owner can optionally
2121      * own.  If a device owner or a profile owner has such a service, the system tries to keep
2122      * a bound connection to it, in order to keep their process always running.
2123      * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN}
2124      * permission.
2125      */
2126     @SdkConstant(SdkConstantType.SERVICE_ACTION)
2127     public static final String ACTION_DEVICE_ADMIN_SERVICE
2128             = "android.app.action.DEVICE_ADMIN_SERVICE";
2129 
2130     /** @hide */
2131     @Retention(RetentionPolicy.SOURCE)
2132     @IntDef(flag = true, prefix = {"ID_TYPE_"}, value = {
2133         ID_TYPE_BASE_INFO,
2134         ID_TYPE_SERIAL,
2135         ID_TYPE_IMEI,
2136         ID_TYPE_MEID,
2137         ID_TYPE_INDIVIDUAL_ATTESTATION
2138     })
2139     public @interface AttestationIdType {}
2140 
2141     /**
2142      * Specifies that the device should attest its manufacturer details. For use with
2143      * {@link #generateKeyPair}.
2144      *
2145      * @see #generateKeyPair
2146      */
2147     public static final int ID_TYPE_BASE_INFO = 1;
2148 
2149     /**
2150      * Specifies that the device should attest its serial number. For use with
2151      * {@link #generateKeyPair}.
2152      *
2153      * @see #generateKeyPair
2154      */
2155     public static final int ID_TYPE_SERIAL = 2;
2156 
2157     /**
2158      * Specifies that the device should attest its IMEI. For use with {@link #generateKeyPair}.
2159      *
2160      * @see #generateKeyPair
2161      */
2162     public static final int ID_TYPE_IMEI = 4;
2163 
2164     /**
2165      * Specifies that the device should attest its MEID. For use with {@link #generateKeyPair}.
2166      *
2167      * @see #generateKeyPair
2168      */
2169     public static final int ID_TYPE_MEID = 8;
2170 
2171     /**
2172      * Specifies that the device should attest using an individual attestation certificate.
2173      * For use with {@link #generateKeyPair}.
2174      *
2175      * @see #generateKeyPair
2176      */
2177     public static final int ID_TYPE_INDIVIDUAL_ATTESTATION = 16;
2178 
2179     /**
2180      * Service-specific error code for {@link #generateKeyPair}:
2181      * Indicates the call has failed due to StrongBox unavailability.
2182      * @hide
2183      */
2184     public static final int KEY_GEN_STRONGBOX_UNAVAILABLE = 1;
2185 
2186     /**
2187      * Specifies that the calling app should be granted access to the installed credentials
2188      * immediately. Otherwise, access to the credentials will be gated by user approval.
2189      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
2190      *
2191      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
2192      */
2193     public static final int INSTALLKEY_REQUEST_CREDENTIALS_ACCESS = 1;
2194 
2195     /**
2196      * Specifies that a user can select the key via the Certificate Selection prompt.
2197      * If this flag is not set when calling {@link #installKeyPair}, the key can only be granted
2198      * access by implementing {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
2199      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
2200      *
2201      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
2202      */
2203     public static final int INSTALLKEY_SET_USER_SELECTABLE = 2;
2204 
2205     /**
2206      * Broadcast action: sent when the profile owner is set, changed or cleared.
2207      *
2208      * This broadcast is sent only to the user managed by the new profile owner.
2209      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
2210      */
2211     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2212     public static final String ACTION_PROFILE_OWNER_CHANGED =
2213             "android.app.action.PROFILE_OWNER_CHANGED";
2214 
2215     /** @hide */
2216     @Retention(RetentionPolicy.SOURCE)
2217     @IntDef(flag = true, prefix = {"PRIVATE_DNS_MODE_"}, value = {
2218             PRIVATE_DNS_MODE_UNKNOWN,
2219             PRIVATE_DNS_MODE_OFF,
2220             PRIVATE_DNS_MODE_OPPORTUNISTIC,
2221             PRIVATE_DNS_MODE_PROVIDER_HOSTNAME
2222     })
2223     public @interface PrivateDnsMode {}
2224 
2225     /**
2226      * Specifies that the Private DNS setting is in an unknown state.
2227      */
2228     public static final int PRIVATE_DNS_MODE_UNKNOWN = 0;
2229 
2230     /**
2231      * Specifies that Private DNS was turned off completely.
2232      */
2233     public static final int PRIVATE_DNS_MODE_OFF = 1;
2234 
2235     /**
2236      * Specifies that the device owner requested opportunistic DNS over TLS
2237      */
2238     public static final int PRIVATE_DNS_MODE_OPPORTUNISTIC = 2;
2239 
2240     /**
2241      * Specifies that the device owner configured a specific host to use for Private DNS.
2242      */
2243     public static final int PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = 3;
2244 
2245     /**
2246      * Callback used in {@link #installSystemUpdate} to indicate that there was an error while
2247      * trying to install an update.
2248      */
2249     public abstract static class InstallSystemUpdateCallback {
2250         /** Represents an unknown error while trying to install an update. */
2251         public static final int UPDATE_ERROR_UNKNOWN = 1;
2252 
2253         /** Represents the update file being intended for different OS version. */
2254         public static final int UPDATE_ERROR_INCORRECT_OS_VERSION = 2;
2255 
2256         /**
2257          * Represents the update file being wrong; e.g. payloads are mismatched, or the wrong
2258          * compression method is used.
2259          */
2260         public static final int UPDATE_ERROR_UPDATE_FILE_INVALID = 3;
2261 
2262         /** Represents that the file could not be found. */
2263         public static final int UPDATE_ERROR_FILE_NOT_FOUND = 4;
2264 
2265         /** Represents the battery being too low to apply an update. */
2266         public static final int UPDATE_ERROR_BATTERY_LOW = 5;
2267 
2268         /**
2269          * Method invoked when there was an error while installing an update.
2270          *
2271          * <p>The given error message is not intended to be user-facing. It is intended to be
2272          * reported back to the IT admin to be read.
2273          */
onInstallUpdateError( @nstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage)2274         public void onInstallUpdateError(
2275                 @InstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage) {
2276         }
2277     }
2278 
2279     /**
2280      * @hide
2281      */
2282     @IntDef(prefix = { "UPDATE_ERROR_" }, value = {
2283             InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN,
2284             InstallSystemUpdateCallback.UPDATE_ERROR_INCORRECT_OS_VERSION,
2285             InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
2286             InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
2287             InstallSystemUpdateCallback.UPDATE_ERROR_BATTERY_LOW
2288     })
2289     @Retention(RetentionPolicy.SOURCE)
2290     public @interface InstallUpdateCallbackErrorConstants {}
2291 
2292     /**
2293      * The selected mode has been set successfully. If the mode is
2294      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} then it implies the supplied host is valid
2295      * and reachable.
2296      */
2297     public static final int PRIVATE_DNS_SET_NO_ERROR = 0;
2298 
2299     /**
2300      * If the {@code privateDnsHost} provided was of a valid hostname but that host was found
2301      * to not support DNS-over-TLS.
2302      */
2303     public static final int PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING = 1;
2304 
2305     /**
2306      * General failure to set the Private DNS mode, not due to one of the reasons listed above.
2307      */
2308     public static final int PRIVATE_DNS_SET_ERROR_FAILURE_SETTING = 2;
2309 
2310     /**
2311      * @hide
2312      */
2313     @IntDef(prefix = {"PRIVATE_DNS_SET_"}, value = {
2314             PRIVATE_DNS_SET_NO_ERROR,
2315             PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING,
2316             PRIVATE_DNS_SET_ERROR_FAILURE_SETTING
2317     })
2318     @Retention(RetentionPolicy.SOURCE)
2319     public @interface PrivateDnsModeErrorCodes {}
2320 
2321     /**
2322      * Activity action: Starts the administrator to get the mode for the provisioning.
2323      * This intent may contain the following extras:
2324      * <ul>
2325      *     <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}</li>
2326      *     <li>{@link #EXTRA_PROVISIONING_IMEI}</li>
2327      *     <li>{@link #EXTRA_PROVISIONING_SERIAL_NUMBER}</li>
2328      * </ul>
2329      *
2330      * <p>The target activity should return one of the following values in
2331      * {@link #EXTRA_PROVISIONING_MODE} as result:
2332      * <ul>
2333      *     <li>{@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}</li>
2334      *     <li>{@link #PROVISIONING_MODE_MANAGED_PROFILE}</li>
2335      * </ul>
2336      *
2337      * <p>If performing fully-managed device provisioning and the admin app desires to show its
2338      * own education screens, the target activity can additionally return
2339      * {@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS} set to <code>true</code>.
2340      *
2341      * <p>The target activity may also return the account that needs to be migrated from primary
2342      * user to managed profile in case of a profile owner provisioning in
2343      * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE} as result.
2344      */
2345     public static final String ACTION_GET_PROVISIONING_MODE =
2346             "android.app.action.GET_PROVISIONING_MODE";
2347 
2348     /**
2349      * A string extra holding the IMEI (International Mobile Equipment Identity) of the device.
2350      */
2351     public static final String EXTRA_PROVISIONING_IMEI = "android.app.extra.PROVISIONING_IMEI";
2352 
2353     /**
2354      * A string extra holding the serial number of the device.
2355      */
2356     public static final String EXTRA_PROVISIONING_SERIAL_NUMBER =
2357             "android.app.extra.PROVISIONING_SERIAL_NUMBER";
2358 
2359     /**
2360      * An intent extra holding the provisioning mode returned by the administrator.
2361      * The value for this extra should be one of the following:
2362      * <ul>
2363      *     <li>{@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}</li>
2364      *     <li>{@link #PROVISIONING_MODE_MANAGED_PROFILE}</li>
2365      * </ul>
2366      */
2367     public static final String EXTRA_PROVISIONING_MODE =
2368             "android.app.extra.PROVISIONING_MODE";
2369 
2370     /**
2371      * The provisioning mode for fully managed device.
2372      */
2373     public static final int PROVISIONING_MODE_FULLY_MANAGED_DEVICE = 1;
2374 
2375     /**
2376      * The provisioning mode for managed profile.
2377      */
2378     public static final int PROVISIONING_MODE_MANAGED_PROFILE = 2;
2379 
2380     /**
2381      * Activity action: Starts the administrator to show policy compliance for the provisioning.
2382      * This action is used any time that the administrator has an opportunity to show policy
2383      * compliance before the end of setup wizard. This could happen as part of the admin-integrated
2384      * provisioning flow (in which case this gets sent after {@link #ACTION_GET_PROVISIONING_MODE}),
2385      * or it could happen during provisioning finalization if the administrator supports
2386      * finalization during setup wizard.
2387      */
2388     public static final String ACTION_ADMIN_POLICY_COMPLIANCE =
2389             "android.app.action.ADMIN_POLICY_COMPLIANCE";
2390 
2391     /**
2392      * Maximum supported password length. Kind-of arbitrary.
2393      * @hide
2394      */
2395     public static final int MAX_PASSWORD_LENGTH = 16;
2396 
2397     /**
2398      * Service Action: Service implemented by a device owner or profile owner supervision app to
2399      * provide a secondary lockscreen.
2400      * @hide
2401      */
2402     @SystemApi
2403     public static final String ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE =
2404             "android.app.action.BIND_SECONDARY_LOCKSCREEN_SERVICE";
2405 
2406     /**
2407      * Return value for {@link #getPersonalAppsSuspendedReasons} when personal apps are not
2408      * suspended.
2409      */
2410     public static final int PERSONAL_APPS_NOT_SUSPENDED = 0;
2411 
2412     /**
2413      * Flag for {@link #getPersonalAppsSuspendedReasons} return value. Set when personal
2414      * apps are suspended by an admin explicitly via {@link #setPersonalAppsSuspended}.
2415      */
2416     public static final int PERSONAL_APPS_SUSPENDED_EXPLICITLY = 1 << 0;
2417 
2418     /**
2419      * Flag for {@link #getPersonalAppsSuspendedReasons} return value. Set when personal apps are
2420      * suspended by framework because managed profile was off for longer than allowed by policy.
2421      * @see #setManagedProfileMaximumTimeOff
2422      */
2423     public static final int PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT = 1 << 1;
2424 
2425     /**
2426      * @hide
2427      */
2428     @IntDef(flag = true, prefix = { "PERSONAL_APPS_" }, value = {
2429             PERSONAL_APPS_NOT_SUSPENDED,
2430             PERSONAL_APPS_SUSPENDED_EXPLICITLY,
2431             PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT
2432     })
2433     @Retention(RetentionPolicy.SOURCE)
2434     public @interface PersonalAppsSuspensionReason {}
2435 
2436     /**
2437      * Return true if the given administrator component is currently active (enabled) in the system.
2438      *
2439      * @param admin The administrator component to check for.
2440      * @return {@code true} if {@code admin} is currently enabled in the system, {@code false}
2441      *         otherwise
2442      */
isAdminActive(@onNull ComponentName admin)2443     public boolean isAdminActive(@NonNull ComponentName admin) {
2444         throwIfParentInstance("isAdminActive");
2445         return isAdminActiveAsUser(admin, myUserId());
2446     }
2447 
2448     /**
2449      * @see #isAdminActive(ComponentName)
2450      * @hide
2451      */
isAdminActiveAsUser(@onNull ComponentName admin, int userId)2452     public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
2453         if (mService != null) {
2454             try {
2455                 return mService.isAdminActive(admin, userId);
2456             } catch (RemoteException e) {
2457                 throw e.rethrowFromSystemServer();
2458             }
2459         }
2460         return false;
2461     }
2462 
2463     /**
2464      * Return true if the given administrator component is currently being removed
2465      * for the user.
2466      * @hide
2467      */
isRemovingAdmin(@onNull ComponentName admin, int userId)2468     public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
2469         if (mService != null) {
2470             try {
2471                 return mService.isRemovingAdmin(admin, userId);
2472             } catch (RemoteException e) {
2473                 throw e.rethrowFromSystemServer();
2474             }
2475         }
2476         return false;
2477     }
2478 
2479     /**
2480      * Return a list of all currently active device administrators' component
2481      * names.  If there are no administrators {@code null} may be
2482      * returned.
2483      */
getActiveAdmins()2484     public @Nullable List<ComponentName> getActiveAdmins() {
2485         throwIfParentInstance("getActiveAdmins");
2486         return getActiveAdminsAsUser(myUserId());
2487     }
2488 
2489     /**
2490      * @see #getActiveAdmins()
2491      * @hide
2492      */
2493     @UnsupportedAppUsage
getActiveAdminsAsUser(int userId)2494     public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) {
2495         if (mService != null) {
2496             try {
2497                 return mService.getActiveAdmins(userId);
2498             } catch (RemoteException e) {
2499                 throw e.rethrowFromSystemServer();
2500             }
2501         }
2502         return null;
2503     }
2504 
2505     /**
2506      * Used by package administration code to determine if a package can be stopped
2507      * or uninstalled.
2508      * @hide
2509      */
2510     @SystemApi
2511     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
packageHasActiveAdmins(String packageName)2512     public boolean packageHasActiveAdmins(String packageName) {
2513         return packageHasActiveAdmins(packageName, myUserId());
2514     }
2515 
2516     /**
2517      * Used by package administration code to determine if a package can be stopped
2518      * or uninstalled.
2519      * @hide
2520      */
2521     @UnsupportedAppUsage
packageHasActiveAdmins(String packageName, int userId)2522     public boolean packageHasActiveAdmins(String packageName, int userId) {
2523         if (mService != null) {
2524             try {
2525                 return mService.packageHasActiveAdmins(packageName, userId);
2526             } catch (RemoteException e) {
2527                 throw e.rethrowFromSystemServer();
2528             }
2529         }
2530         return false;
2531     }
2532 
2533     /**
2534      * Remove a current administration component.  This can only be called
2535      * by the application that owns the administration component; if you
2536      * try to remove someone else's component, a security exception will be
2537      * thrown.
2538      *
2539      * <p>Note that the operation is not synchronous and the admin might still be active (as
2540      * indicated by {@link #getActiveAdmins()}) by the time this method returns.
2541      *
2542      * @param admin The administration compononent to remove.
2543      * @throws SecurityException if the caller is not in the owner application of {@code admin}.
2544      */
removeActiveAdmin(@onNull ComponentName admin)2545     public void removeActiveAdmin(@NonNull ComponentName admin) {
2546         throwIfParentInstance("removeActiveAdmin");
2547         if (mService != null) {
2548             try {
2549                 mService.removeActiveAdmin(admin, myUserId());
2550             } catch (RemoteException e) {
2551                 throw e.rethrowFromSystemServer();
2552             }
2553         }
2554     }
2555 
2556     /**
2557      * Returns true if an administrator has been granted a particular device policy. This can be
2558      * used to check whether the administrator was activated under an earlier set of policies, but
2559      * requires additional policies after an upgrade.
2560      *
2561      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be an
2562      *            active administrator, or an exception will be thrown.
2563      * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
2564      * @throws SecurityException if {@code admin} is not an active administrator.
2565      */
hasGrantedPolicy(@onNull ComponentName admin, int usesPolicy)2566     public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) {
2567         throwIfParentInstance("hasGrantedPolicy");
2568         if (mService != null) {
2569             try {
2570                 return mService.hasGrantedPolicy(admin, usesPolicy, myUserId());
2571             } catch (RemoteException e) {
2572                 throw e.rethrowFromSystemServer();
2573             }
2574         }
2575         return false;
2576     }
2577 
2578     /**
2579      * Returns true if the Profile Challenge is available to use for the given profile user.
2580      *
2581      * @hide
2582      */
isSeparateProfileChallengeAllowed(int userHandle)2583     public boolean isSeparateProfileChallengeAllowed(int userHandle) {
2584         if (mService != null) {
2585             try {
2586                 return mService.isSeparateProfileChallengeAllowed(userHandle);
2587             } catch (RemoteException e) {
2588                 throw e.rethrowFromSystemServer();
2589             }
2590         }
2591         return false;
2592     }
2593 
2594     /**
2595      * Constant for {@link #setPasswordQuality}: the policy has no requirements
2596      * for the password.  Note that quality constants are ordered so that higher
2597      * values are more restrictive.
2598      */
2599     public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
2600 
2601     /**
2602      * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
2603      * recognition technology.  This implies technologies that can recognize the identity of
2604      * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
2605      * Note that quality constants are ordered so that higher values are more restrictive.
2606      */
2607     public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
2608 
2609     /**
2610      * Constant for {@link #setPasswordQuality}: the policy requires some kind
2611      * of password or pattern, but doesn't care what it is. Note that quality constants
2612      * are ordered so that higher values are more restrictive.
2613      */
2614     public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
2615 
2616     /**
2617      * Constant for {@link #setPasswordQuality}: the user must have entered a
2618      * password containing at least numeric characters.  Note that quality
2619      * constants are ordered so that higher values are more restrictive.
2620      */
2621     public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
2622 
2623     /**
2624      * Constant for {@link #setPasswordQuality}: the user must have entered a
2625      * password containing at least numeric characters with no repeating (4444)
2626      * or ordered (1234, 4321, 2468) sequences.  Note that quality
2627      * constants are ordered so that higher values are more restrictive.
2628      */
2629     public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
2630 
2631     /**
2632      * Constant for {@link #setPasswordQuality}: the user must have entered a
2633      * password containing at least alphabetic (or other symbol) characters.
2634      * Note that quality constants are ordered so that higher values are more
2635      * restrictive.
2636      */
2637     public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
2638 
2639     /**
2640      * Constant for {@link #setPasswordQuality}: the user must have entered a
2641      * password containing at least <em>both></em> numeric <em>and</em>
2642      * alphabetic (or other symbol) characters.  Note that quality constants are
2643      * ordered so that higher values are more restrictive.
2644      */
2645     public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
2646 
2647     /**
2648      * Constant for {@link #setPasswordQuality}: allows the admin to set precisely how many
2649      * characters of various types the password should contain to satisfy the policy. The admin
2650      * should set these requirements via {@link #setPasswordMinimumLetters},
2651      * {@link #setPasswordMinimumNumeric}, {@link #setPasswordMinimumSymbols},
2652      * {@link #setPasswordMinimumUpperCase}, {@link #setPasswordMinimumLowerCase},
2653      * {@link #setPasswordMinimumNonLetter}, and {@link #setPasswordMinimumLength}.
2654      * Note that quality constants are ordered so that higher values are more restrictive.
2655      */
2656     public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
2657 
2658     /**
2659      * Constant for {@link #setPasswordQuality}: the user is not allowed to
2660      * modify password. In case this password quality is set, the password is
2661      * managed by a profile owner. The profile owner can set any password,
2662      * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note
2663      * that quality constants are ordered so that higher values are more
2664      * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is
2665      * the highest.
2666      * @hide
2667      */
2668     public static final int PASSWORD_QUALITY_MANAGED = 0x80000;
2669 
2670     /**
2671      * @hide
2672      *
2673      * adb shell dpm set-{device,profile}-owner will normally not allow installing an owner to
2674      * a user with accounts.  {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED}
2675      * and {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} are the account features
2676      * used by authenticator to exempt their accounts from this:
2677      *
2678      * <ul>
2679      *     <li>Non-test-only DO/PO still can't be installed when there are accounts.
2680      *     <p>In order to make an apk test-only, add android:testOnly="true" to the
2681      *     &lt;application&gt; tag in the manifest.
2682      *
2683      *     <li>Test-only DO/PO can be installed even when there are accounts, as long as all the
2684      *     accounts have the {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} feature.
2685      *     Some authenticators claim to have any features, so to detect it, we also check
2686      *     {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} and disallow installing
2687      *     if any of the accounts have it.
2688      * </ul>
2689      */
2690     @SystemApi
2691     @TestApi
2692     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED =
2693             "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED";
2694 
2695     /** @hide See {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} */
2696     @SystemApi
2697     @TestApi
2698     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED =
2699             "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED";
2700 
2701     /**
2702      * Called by an application that is administering the device to set the password restrictions it
2703      * is imposing. After setting this, the user will not be able to enter a new password that is
2704      * not at least as restrictive as what has been set. Note that the current password will remain
2705      * until the user has set a new one, so the change does not take place immediately. To prompt
2706      * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2707      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after calling this method.
2708      * <p>
2709      * Quality constants are ordered so that higher values are more restrictive; thus the highest
2710      * requested quality constant (between the policy set here, the user's preference, and any other
2711      * considerations) is the one that is in effect.
2712      * <p>
2713      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2714      * password is always treated as empty.
2715      * <p>
2716      * The calling device admin must have requested
2717      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2718      * not, a security exception will be thrown.
2719      * <p>
2720      * This method can be called on the {@link DevicePolicyManager} instance returned by
2721      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2722      * profile.
2723      *
2724      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2725      * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED},
2726      *            {@link #PASSWORD_QUALITY_BIOMETRIC_WEAK},
2727      *            {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC},
2728      *            {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
2729      *            {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
2730      * @throws SecurityException if {@code admin} is not an active administrator or if {@code admin}
2731      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2732      */
setPasswordQuality(@onNull ComponentName admin, int quality)2733     public void setPasswordQuality(@NonNull ComponentName admin, int quality) {
2734         if (mService != null) {
2735             try {
2736                 mService.setPasswordQuality(admin, quality, mParentInstance);
2737             } catch (RemoteException e) {
2738                 throw e.rethrowFromSystemServer();
2739             }
2740         }
2741     }
2742 
2743     /**
2744      * Retrieve the current minimum password quality for a particular admin or all admins that set
2745      * restrictions on this user and its participating profiles. Restrictions on profiles that have
2746      * a separate challenge are not taken into account.
2747      *
2748      * <p>This method can be called on the {@link DevicePolicyManager} instance
2749      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2750      * restrictions on the parent profile.
2751      *
2752      * <p>Note: on devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
2753      * the password is always treated as empty.
2754      *
2755      * @param admin The name of the admin component to check, or {@code null} to aggregate
2756      * all admins.
2757      */
getPasswordQuality(@ullable ComponentName admin)2758     public int getPasswordQuality(@Nullable ComponentName admin) {
2759         return getPasswordQuality(admin, myUserId());
2760     }
2761 
2762     /** @hide per-user version */
2763     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordQuality(@ullable ComponentName admin, int userHandle)2764     public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) {
2765         if (mService != null) {
2766             try {
2767                 return mService.getPasswordQuality(admin, userHandle, mParentInstance);
2768             } catch (RemoteException e) {
2769                 throw e.rethrowFromSystemServer();
2770             }
2771         }
2772         return PASSWORD_QUALITY_UNSPECIFIED;
2773     }
2774 
2775     /**
2776      * Called by an application that is administering the device to set the minimum allowed password
2777      * length. After setting this, the user will not be able to enter a new password that is not at
2778      * least as restrictive as what has been set. Note that the current password will remain until
2779      * the user has set a new one, so the change does not take place immediately. To prompt the user
2780      * for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2781      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2782      * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
2783      * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
2784      * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with
2785      * {@link #setPasswordQuality}. If an app targeting SDK level
2786      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
2787      * password quality to one of these values first, this method will throw
2788      * {@link IllegalStateException}.
2789      * <p>
2790      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2791      * password is always treated as empty.
2792      * <p>
2793      * The calling device admin must have requested
2794      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2795      * not, a security exception will be thrown.
2796      * <p>
2797      * This method can be called on the {@link DevicePolicyManager} instance returned by
2798      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2799      * profile.
2800      *
2801      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2802      * @param length The new desired minimum password length. A value of 0 means there is no
2803      *     restriction.
2804      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2805      *     does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2806      * @throws IllegalStateException if the calling app is targeting SDK level
2807      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
2808      *     quality requirement prior to calling this method.
2809      */
setPasswordMinimumLength(@onNull ComponentName admin, int length)2810     public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
2811         if (mService != null) {
2812             try {
2813                 mService.setPasswordMinimumLength(admin, length, mParentInstance);
2814             } catch (RemoteException e) {
2815                 throw e.rethrowFromSystemServer();
2816             }
2817         }
2818     }
2819 
2820     /**
2821      * Retrieve the current minimum password length for a particular admin or all admins that set
2822      * restrictions on this user and its participating profiles. Restrictions on profiles that have
2823      * a separate challenge are not taken into account.
2824      *
2825      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2826      * password is always treated as empty.
2827      *
2828      * <p>This method can be called on the {@link DevicePolicyManager} instance
2829      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2830      * restrictions on the parent profile.
2831      *
2832      * @param admin The name of the admin component to check, or {@code null} to aggregate
2833      * all admins.
2834      */
getPasswordMinimumLength(@ullable ComponentName admin)2835     public int getPasswordMinimumLength(@Nullable ComponentName admin) {
2836         return getPasswordMinimumLength(admin, myUserId());
2837     }
2838 
2839     /** @hide per-user version */
2840     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLength(@ullable ComponentName admin, int userHandle)2841     public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) {
2842         if (mService != null) {
2843             try {
2844                 return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance);
2845             } catch (RemoteException e) {
2846                 throw e.rethrowFromSystemServer();
2847             }
2848         }
2849         return 0;
2850     }
2851 
2852     /**
2853      * Called by an application that is administering the device to set the minimum number of upper
2854      * case letters required in the password. After setting this, the user will not be able to enter
2855      * a new password that is not at least as restrictive as what has been set. Note that the
2856      * current password will remain until the user has set a new one, so the change does not take
2857      * place immediately. To prompt the user for a new password, use
2858      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2859      * setting this value. This constraint is only imposed if the administrator has also requested
2860      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
2861      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
2862      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
2863      * {@link IllegalStateException}. The default value is 0.
2864      * <p>
2865      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2866      * password is always treated as empty.
2867      * <p>
2868      * The calling device admin must have requested
2869      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2870      * not, a security exception will be thrown.
2871      * <p>
2872      * This method can be called on the {@link DevicePolicyManager} instance returned by
2873      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2874      * profile.
2875      *
2876      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2877      * @param length The new desired minimum number of upper case letters required in the password.
2878      *            A value of 0 means there is no restriction.
2879      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2880      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2881      * @throws IllegalStateException if the calling app is targeting SDK level
2882      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
2883      *     quality requirement prior to calling this method.
2884      */
setPasswordMinimumUpperCase(@onNull ComponentName admin, int length)2885     public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
2886         if (mService != null) {
2887             try {
2888                 mService.setPasswordMinimumUpperCase(admin, length, mParentInstance);
2889             } catch (RemoteException e) {
2890                 throw e.rethrowFromSystemServer();
2891             }
2892         }
2893     }
2894 
2895     /**
2896      * Retrieve the current number of upper case letters required in the password
2897      * for a particular admin or all admins that set restrictions on this user and
2898      * its participating profiles. Restrictions on profiles that have a separate challenge
2899      * are not taken into account.
2900      * This is the same value as set by
2901      * {@link #setPasswordMinimumUpperCase(ComponentName, int)}
2902      * and only applies when the password quality is
2903      * {@link #PASSWORD_QUALITY_COMPLEX}.
2904      *
2905      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2906      * password is always treated as empty.
2907      *
2908      * <p>This method can be called on the {@link DevicePolicyManager} instance
2909      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2910      * restrictions on the parent profile.
2911      *
2912      * @param admin The name of the admin component to check, or {@code null} to
2913      *            aggregate all admins.
2914      * @return The minimum number of upper case letters required in the
2915      *         password.
2916      */
getPasswordMinimumUpperCase(@ullable ComponentName admin)2917     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) {
2918         return getPasswordMinimumUpperCase(admin, myUserId());
2919     }
2920 
2921     /** @hide per-user version */
2922     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumUpperCase(@ullable ComponentName admin, int userHandle)2923     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) {
2924         if (mService != null) {
2925             try {
2926                 return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance);
2927             } catch (RemoteException e) {
2928                 throw e.rethrowFromSystemServer();
2929             }
2930         }
2931         return 0;
2932     }
2933 
2934     /**
2935      * Called by an application that is administering the device to set the minimum number of lower
2936      * case letters required in the password. After setting this, the user will not be able to enter
2937      * a new password that is not at least as restrictive as what has been set. Note that the
2938      * current password will remain until the user has set a new one, so the change does not take
2939      * place immediately. To prompt the user for a new password, use
2940      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2941      * setting this value. This constraint is only imposed if the administrator has also requested
2942      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
2943      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
2944      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
2945      * {@link IllegalStateException}. The default value is 0.
2946      * <p>
2947      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2948      * password is always treated as empty.
2949      * <p>
2950      * The calling device admin must have requested
2951      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2952      * not, a security exception will be thrown.
2953      * <p>
2954      * This method can be called on the {@link DevicePolicyManager} instance returned by
2955      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2956      * profile.
2957      *
2958      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2959      * @param length The new desired minimum number of lower case letters required in the password.
2960      *            A value of 0 means there is no restriction.
2961      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2962      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2963      * @throws IllegalStateException if the calling app is targeting SDK level
2964      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
2965      *     quality requirement prior to calling this method.
2966      */
setPasswordMinimumLowerCase(@onNull ComponentName admin, int length)2967     public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
2968         if (mService != null) {
2969             try {
2970                 mService.setPasswordMinimumLowerCase(admin, length, mParentInstance);
2971             } catch (RemoteException e) {
2972                 throw e.rethrowFromSystemServer();
2973             }
2974         }
2975     }
2976 
2977     /**
2978      * Retrieve the current number of lower case letters required in the password
2979      * for a particular admin or all admins that set restrictions on this user
2980      * and its participating profiles. Restrictions on profiles that have
2981      * a separate challenge are not taken into account.
2982      * This is the same value as set by
2983      * {@link #setPasswordMinimumLowerCase(ComponentName, int)}
2984      * and only applies when the password quality is
2985      * {@link #PASSWORD_QUALITY_COMPLEX}.
2986      *
2987      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2988      * password is always treated as empty.
2989      *
2990      * <p>This method can be called on the {@link DevicePolicyManager} instance
2991      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2992      * restrictions on the parent profile.
2993      *
2994      * @param admin The name of the admin component to check, or {@code null} to
2995      *            aggregate all admins.
2996      * @return The minimum number of lower case letters required in the
2997      *         password.
2998      */
getPasswordMinimumLowerCase(@ullable ComponentName admin)2999     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) {
3000         return getPasswordMinimumLowerCase(admin, myUserId());
3001     }
3002 
3003     /** @hide per-user version */
3004     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLowerCase(@ullable ComponentName admin, int userHandle)3005     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) {
3006         if (mService != null) {
3007             try {
3008                 return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance);
3009             } catch (RemoteException e) {
3010                 throw e.rethrowFromSystemServer();
3011             }
3012         }
3013         return 0;
3014     }
3015 
3016     /**
3017      * Called by an application that is administering the device to set the minimum number of
3018      * letters required in the password. After setting this, the user will not be able to enter a
3019      * new password that is not at least as restrictive as what has been set. Note that the current
3020      * password will remain until the user has set a new one, so the change does not take place
3021      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
3022      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
3023      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
3024      * {@link #setPasswordQuality}. If an app targeting SDK level
3025      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
3026      * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
3027      * {@link IllegalStateException}. The default value is 1.
3028      * <p>
3029      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3030      * password is always treated as empty.
3031      * <p>
3032      * The calling device admin must have requested
3033      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3034      * not, a security exception will be thrown.
3035      * <p>
3036      * This method can be called on the {@link DevicePolicyManager} instance returned by
3037      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3038      * profile.
3039      *
3040      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3041      * @param length The new desired minimum number of letters required in the password. A value of
3042      *            0 means there is no restriction.
3043      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3044      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3045      * @throws IllegalStateException if the calling app is targeting SDK level
3046      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
3047      *     quality requirement prior to calling this method.
3048      */
setPasswordMinimumLetters(@onNull ComponentName admin, int length)3049     public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
3050         if (mService != null) {
3051             try {
3052                 mService.setPasswordMinimumLetters(admin, length, mParentInstance);
3053             } catch (RemoteException e) {
3054                 throw e.rethrowFromSystemServer();
3055             }
3056         }
3057     }
3058 
3059     /**
3060      * Retrieve the current number of letters required in the password
3061      * for a particular admin or all admins that set restrictions on this user
3062      * and its participating profiles. Restrictions on profiles that have
3063      * a separate challenge are not taken into account.
3064      * This is the same value as set by
3065      * {@link #setPasswordMinimumLetters(ComponentName, int)}
3066      * and only applies when the password quality is
3067      * {@link #PASSWORD_QUALITY_COMPLEX}.
3068      *
3069      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3070      * password is always treated as empty.
3071      *
3072      * <p>This method can be called on the {@link DevicePolicyManager} instance
3073      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3074      * restrictions on the parent profile.
3075      *
3076      * @param admin The name of the admin component to check, or {@code null} to
3077      *            aggregate all admins.
3078      * @return The minimum number of letters required in the password.
3079      */
getPasswordMinimumLetters(@ullable ComponentName admin)3080     public int getPasswordMinimumLetters(@Nullable ComponentName admin) {
3081         return getPasswordMinimumLetters(admin, myUserId());
3082     }
3083 
3084     /** @hide per-user version */
3085     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLetters(@ullable ComponentName admin, int userHandle)3086     public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) {
3087         if (mService != null) {
3088             try {
3089                 return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance);
3090             } catch (RemoteException e) {
3091                 throw e.rethrowFromSystemServer();
3092             }
3093         }
3094         return 0;
3095     }
3096 
3097     /**
3098      * Called by an application that is administering the device to set the minimum number of
3099      * numerical digits required in the password. After setting this, the user will not be able to
3100      * enter a new password that is not at least as restrictive as what has been set. Note that the
3101      * current password will remain until the user has set a new one, so the change does not take
3102      * place immediately. To prompt the user for a new password, use
3103      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
3104      * setting this value. This constraint is only imposed if the administrator has also requested
3105      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
3106      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
3107      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
3108      * {@link IllegalStateException}. The default value is 1.
3109      * <p>
3110      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3111      * password is always treated as empty.
3112      * <p>
3113      * The calling device admin must have requested
3114      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3115      * not, a security exception will be thrown.
3116      * <p>
3117      * This method can be called on the {@link DevicePolicyManager} instance returned by
3118      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3119      * profile.
3120      *
3121      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3122      * @param length The new desired minimum number of numerical digits required in the password. A
3123      *            value of 0 means there is no restriction.
3124      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3125      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3126      * @throws IllegalStateException if the calling app is targeting SDK level
3127      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
3128      *     quality requirement prior to calling this method.
3129      */
setPasswordMinimumNumeric(@onNull ComponentName admin, int length)3130     public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
3131         if (mService != null) {
3132             try {
3133                 mService.setPasswordMinimumNumeric(admin, length, mParentInstance);
3134             } catch (RemoteException e) {
3135                 throw e.rethrowFromSystemServer();
3136             }
3137         }
3138     }
3139 
3140     /**
3141      * Retrieve the current number of numerical digits required in the password
3142      * for a particular admin or all admins that set restrictions on this user
3143      * and its participating profiles. Restrictions on profiles that have
3144      * a separate challenge are not taken into account.
3145      * This is the same value as set by
3146      * {@link #setPasswordMinimumNumeric(ComponentName, int)}
3147      * and only applies when the password quality is
3148      * {@link #PASSWORD_QUALITY_COMPLEX}.
3149      *
3150      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3151      * password is always treated as empty.
3152      *
3153      * <p>This method can be called on the {@link DevicePolicyManager} instance
3154      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3155      * restrictions on the parent profile.
3156      *
3157      * @param admin The name of the admin component to check, or {@code null} to
3158      *            aggregate all admins.
3159      * @return The minimum number of numerical digits required in the password.
3160      */
getPasswordMinimumNumeric(@ullable ComponentName admin)3161     public int getPasswordMinimumNumeric(@Nullable ComponentName admin) {
3162         return getPasswordMinimumNumeric(admin, myUserId());
3163     }
3164 
3165     /** @hide per-user version */
3166     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumNumeric(@ullable ComponentName admin, int userHandle)3167     public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) {
3168         if (mService != null) {
3169             try {
3170                 return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance);
3171             } catch (RemoteException e) {
3172                 throw e.rethrowFromSystemServer();
3173             }
3174         }
3175         return 0;
3176     }
3177 
3178     /**
3179      * Called by an application that is administering the device to set the minimum number of
3180      * symbols required in the password. After setting this, the user will not be able to enter a
3181      * new password that is not at least as restrictive as what has been set. Note that the current
3182      * password will remain until the user has set a new one, so the change does not take place
3183      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
3184      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
3185      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
3186      * {@link #setPasswordQuality}. If an app targeting SDK level
3187      * {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without settings
3188      * password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
3189      * {@link IllegalStateException}. The default value is 1.
3190      * <p>
3191      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3192      * password is always treated as empty.
3193      * <p>
3194      * The calling device admin must have requested
3195      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3196      * not, a security exception will be thrown.
3197      * <p>
3198      * This method can be called on the {@link DevicePolicyManager} instance returned by
3199      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3200      * profile.
3201      *
3202      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3203      * @param length The new desired minimum number of symbols required in the password. A value of
3204      *            0 means there is no restriction.
3205      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3206      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3207      * @throws IllegalStateException if the calling app is targeting SDK level
3208      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
3209      *     quality requirement prior to calling this method.
3210      */
setPasswordMinimumSymbols(@onNull ComponentName admin, int length)3211     public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
3212         if (mService != null) {
3213             try {
3214                 mService.setPasswordMinimumSymbols(admin, length, mParentInstance);
3215             } catch (RemoteException e) {
3216                 throw e.rethrowFromSystemServer();
3217             }
3218         }
3219     }
3220 
3221     /**
3222      * Retrieve the current number of symbols required in the password
3223      * for a particular admin or all admins that set restrictions on this user
3224      * and its participating profiles. Restrictions on profiles that have
3225      * a separate challenge are not taken into account. This is the same value as
3226      * set by {@link #setPasswordMinimumSymbols(ComponentName, int)}
3227      * and only applies when the password quality is
3228      * {@link #PASSWORD_QUALITY_COMPLEX}.
3229      *
3230      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3231      * password is always treated as empty.
3232      *
3233      * <p>This method can be called on the {@link DevicePolicyManager} instance
3234      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3235      * restrictions on the parent profile.
3236      *
3237      * @param admin The name of the admin component to check, or {@code null} to
3238      *            aggregate all admins.
3239      * @return The minimum number of symbols required in the password.
3240      */
getPasswordMinimumSymbols(@ullable ComponentName admin)3241     public int getPasswordMinimumSymbols(@Nullable ComponentName admin) {
3242         return getPasswordMinimumSymbols(admin, myUserId());
3243     }
3244 
3245     /** @hide per-user version */
3246     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumSymbols(@ullable ComponentName admin, int userHandle)3247     public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) {
3248         if (mService != null) {
3249             try {
3250                 return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance);
3251             } catch (RemoteException e) {
3252                 throw e.rethrowFromSystemServer();
3253             }
3254         }
3255         return 0;
3256     }
3257 
3258     /**
3259      * Called by an application that is administering the device to set the minimum number of
3260      * non-letter characters (numerical digits or symbols) required in the password. After setting
3261      * this, the user will not be able to enter a new password that is not at least as restrictive
3262      * as what has been set. Note that the current password will remain until the user has set a new
3263      * one, so the change does not take place immediately. To prompt the user for a new password,
3264      * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
3265      * setting this value. This constraint is only imposed if the administrator has also requested
3266      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. If an app targeting
3267      * SDK level {@link android.os.Build.VERSION_CODES#R} and above enforces this constraint without
3268      * settings password quality to {@link #PASSWORD_QUALITY_COMPLEX} first, this method will throw
3269      * {@link IllegalStateException}. The default value is 0.
3270      * <p>
3271      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3272      * password is always treated as empty.
3273      * <p>
3274      * The calling device admin must have requested
3275      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3276      * not, a security exception will be thrown.
3277      * <p>
3278      * This method can be called on the {@link DevicePolicyManager} instance returned by
3279      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3280      * profile.
3281      *
3282      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3283      * @param length The new desired minimum number of letters required in the password. A value of
3284      *            0 means there is no restriction.
3285      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3286      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3287      * @throws IllegalStateException if the calling app is targeting SDK level
3288      *     {@link android.os.Build.VERSION_CODES#R} and above and didn't set a sufficient password
3289      *     quality requirement prior to calling this method.
3290      */
setPasswordMinimumNonLetter(@onNull ComponentName admin, int length)3291     public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
3292         if (mService != null) {
3293             try {
3294                 mService.setPasswordMinimumNonLetter(admin, length, mParentInstance);
3295             } catch (RemoteException e) {
3296                 throw e.rethrowFromSystemServer();
3297             }
3298         }
3299     }
3300 
3301     /**
3302      * Retrieve the current number of non-letter characters required in the password
3303      * for a particular admin or all admins that set restrictions on this user
3304      * and its participating profiles. Restrictions on profiles that have
3305      * a separate challenge are not taken into account.
3306      * This is the same value as set by
3307      * {@link #setPasswordMinimumNonLetter(ComponentName, int)}
3308      * and only applies when the password quality is
3309      * {@link #PASSWORD_QUALITY_COMPLEX}.
3310      *
3311      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3312      * password is always treated as empty.
3313      *
3314      * <p>This method can be called on the {@link DevicePolicyManager} instance
3315      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3316      * restrictions on the parent profile.
3317      *
3318      * @param admin The name of the admin component to check, or {@code null} to
3319      *            aggregate all admins.
3320      * @return The minimum number of letters required in the password.
3321      */
getPasswordMinimumNonLetter(@ullable ComponentName admin)3322     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) {
3323         return getPasswordMinimumNonLetter(admin, myUserId());
3324     }
3325 
3326     /** @hide per-user version */
3327     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumNonLetter(@ullable ComponentName admin, int userHandle)3328     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) {
3329         if (mService != null) {
3330             try {
3331                 return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance);
3332             } catch (RemoteException e) {
3333                 throw e.rethrowFromSystemServer();
3334             }
3335         }
3336         return 0;
3337     }
3338 
3339     /**
3340      * Returns minimum PasswordMetrics that satisfies all admin policies.
3341      *
3342      * @hide
3343      */
getPasswordMinimumMetrics(@serIdInt int userHandle)3344     public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle) {
3345         if (mService != null) {
3346             try {
3347                 return mService.getPasswordMinimumMetrics(userHandle);
3348             } catch (RemoteException e) {
3349                 throw e.rethrowFromSystemServer();
3350             }
3351         }
3352         return null;
3353     }
3354 
3355     /**
3356      * Called by an application that is administering the device to set the length of the password
3357      * history. After setting this, the user will not be able to enter a new password that is the
3358      * same as any password in the history. Note that the current password will remain until the
3359      * user has set a new one, so the change does not take place immediately. To prompt the user for
3360      * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
3361      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value.
3362      * <p>
3363      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3364      * password history length is always 0.
3365      * <p>
3366      * The calling device admin must have requested
3367      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3368      * not, a security exception will be thrown.
3369      * <p>
3370      * This method can be called on the {@link DevicePolicyManager} instance returned by
3371      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3372      * profile.
3373      *
3374      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3375      * @param length The new desired length of password history. A value of 0 means there is no
3376      *            restriction.
3377      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3378      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3379      */
3380     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setPasswordHistoryLength(@onNull ComponentName admin, int length)3381     public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
3382         if (mService != null) {
3383             try {
3384                 mService.setPasswordHistoryLength(admin, length, mParentInstance);
3385             } catch (RemoteException e) {
3386                 throw e.rethrowFromSystemServer();
3387             }
3388         }
3389     }
3390 
3391     /**
3392      * Called by a device admin to set the password expiration timeout. Calling this method will
3393      * restart the countdown for password expiration for the given admin, as will changing the
3394      * device password (for all admins).
3395      * <p>
3396      * The provided timeout is the time delta in ms and will be added to the current time. For
3397      * example, to have the password expire 5 days from now, timeout would be 5 * 86400 * 1000 =
3398      * 432000000 ms for timeout.
3399      * <p>
3400      * To disable password expiration, a value of 0 may be used for timeout.
3401      * <p>
3402      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3403      * password expiration is always disabled.
3404      * <p>
3405      * The calling device admin must have requested
3406      * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this method; if it has
3407      * not, a security exception will be thrown.
3408      * <p>
3409      * Note that setting the password will automatically reset the expiration time for all active
3410      * admins. Active admins do not need to explicitly call this method in that case.
3411      * <p>
3412      * This method can be called on the {@link DevicePolicyManager} instance returned by
3413      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3414      * profile.
3415      *
3416      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3417      * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 means
3418      *            there is no restriction (unlimited).
3419      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3420      *             does not use {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD}
3421      */
3422     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setPasswordExpirationTimeout(@onNull ComponentName admin, long timeout)3423     public void setPasswordExpirationTimeout(@NonNull ComponentName admin, long timeout) {
3424         if (mService != null) {
3425             try {
3426                 mService.setPasswordExpirationTimeout(admin, timeout, mParentInstance);
3427             } catch (RemoteException e) {
3428                 throw e.rethrowFromSystemServer();
3429             }
3430         }
3431     }
3432 
3433     /**
3434      * Get the password expiration timeout for the given admin. The expiration timeout is the
3435      * recurring expiration timeout provided in the call to
3436      * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
3437      * aggregate of all participating policy administrators if {@code admin} is null. Admins that
3438      * have set restrictions on profiles that have a separate challenge are not taken into account.
3439      *
3440      * <p>This method can be called on the {@link DevicePolicyManager} instance
3441      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3442      * restrictions on the parent profile.
3443      *
3444      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3445      * password expiration is always disabled and this method always returns 0.
3446      *
3447      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
3448      * @return The timeout for the given admin or the minimum of all timeouts
3449      */
3450     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordExpirationTimeout(@ullable ComponentName admin)3451     public long getPasswordExpirationTimeout(@Nullable ComponentName admin) {
3452         if (mService != null) {
3453             try {
3454                 return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance);
3455             } catch (RemoteException e) {
3456                 throw e.rethrowFromSystemServer();
3457             }
3458         }
3459         return 0;
3460     }
3461 
3462     /**
3463      * Get the current password expiration time for a particular admin or all admins that set
3464      * restrictions on this user and its participating profiles. Restrictions on profiles that have
3465      * a separate challenge are not taken into account. If admin is {@code null}, then a composite
3466      * of all expiration times is returned - which will be the minimum of all of them.
3467      *
3468      * <p>This method can be called on the {@link DevicePolicyManager} instance
3469      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3470      * the password expiration for the parent profile.
3471      *
3472      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3473      * password expiration is always disabled and this method always returns 0.
3474      *
3475      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
3476      * @return The password expiration time, in milliseconds since epoch.
3477      */
3478     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordExpiration(@ullable ComponentName admin)3479     public long getPasswordExpiration(@Nullable ComponentName admin) {
3480         if (mService != null) {
3481             try {
3482                 return mService.getPasswordExpiration(admin, myUserId(), mParentInstance);
3483             } catch (RemoteException e) {
3484                 throw e.rethrowFromSystemServer();
3485             }
3486         }
3487         return 0;
3488     }
3489 
3490     /**
3491      * Retrieve the current password history length for a particular admin or all admins that
3492      * set restrictions on this user and its participating profiles. Restrictions on profiles that
3493      * have a separate challenge are not taken into account.
3494      *
3495      * <p>This method can be called on the {@link DevicePolicyManager} instance
3496      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3497      * restrictions on the parent profile.
3498      *
3499      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3500      * password history length is always 0.
3501      *
3502      * @param admin The name of the admin component to check, or {@code null} to aggregate
3503      * all admins.
3504      * @return The length of the password history
3505      */
3506     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordHistoryLength(@ullable ComponentName admin)3507     public int getPasswordHistoryLength(@Nullable ComponentName admin) {
3508         return getPasswordHistoryLength(admin, myUserId());
3509     }
3510 
3511     /** @hide per-user version */
3512     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
3513     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordHistoryLength(@ullable ComponentName admin, int userHandle)3514     public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) {
3515         if (mService != null) {
3516             try {
3517                 return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance);
3518             } catch (RemoteException e) {
3519                 throw e.rethrowFromSystemServer();
3520             }
3521         }
3522         return 0;
3523     }
3524 
3525     /**
3526      * Return the maximum password length that the device supports for a
3527      * particular password quality.
3528      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3529      * password is always empty and this method always returns 0.
3530      * @param quality The quality being interrogated.
3531      * @return Returns the maximum length that the user can enter.
3532      */
getPasswordMaximumLength(int quality)3533     public int getPasswordMaximumLength(int quality) {
3534         PackageManager pm = mContext.getPackageManager();
3535         if (!pm.hasSystemFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)) {
3536             return 0;
3537         }
3538         return MAX_PASSWORD_LENGTH;
3539     }
3540 
3541     /**
3542      * Determines whether the calling user's current password meets policy requirements
3543      * (e.g. quality, minimum length). The user must be unlocked to perform this check.
3544      *
3545      * <p>Policy requirements which affect this check can be set by admins of the user, but also
3546      * by the admin of a managed profile associated with the calling user (when the managed profile
3547      * doesn't have a separate work challenge). When a managed profile has a separate work
3548      * challenge, its policy requirements only affect the managed profile.
3549      *
3550      * <p>Depending on the user, this method checks the policy requirement against one of the
3551      * following passwords:
3552      * <ul>
3553      * <li>For the primary user or secondary users: the personal keyguard password.
3554      * <li>For managed profiles: a work challenge if set, otherwise the parent user's personal
3555      *     keyguard password.
3556      * <ul/>
3557      * In other words, it's always checking the requirement against the password that is protecting
3558      * the calling user.
3559      *
3560      * <p>Note that this method considers all policy requirements targeting the password in
3561      * question. For example a profile owner might set a requirement on the parent profile i.e.
3562      * personal keyguard but not on the profile itself. When the device has a weak personal keyguard
3563      * password and no separate work challenge, calling this method will return {@code false}
3564      * despite the profile owner not setting a policy on the profile itself. This is because the
3565      * profile's current password is the personal keyguard password, and it does not meet all policy
3566      * requirements.
3567      *
3568      * <p>Device admins must request {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} before
3569      * calling this method. Note, this policy type is deprecated for device admins in Android 9.0
3570      * (API level 28) or higher.
3571      *
3572      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
3573      * {@link #getParentProfileInstance(ComponentName)} in order to determine if the password set on
3574      * the parent profile is sufficient.
3575      *
3576      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3577      * password is always treated as empty - i.e. this method will always return false on such
3578      * devices, provided any password requirements were set.
3579      *
3580      * @return {@code true} if the password meets the policy requirements, {@code false} otherwise
3581      * @throws SecurityException if the calling application isn't an active admin that uses
3582      *     {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3583      * @throws IllegalStateException if the user isn't unlocked
3584      */
isActivePasswordSufficient()3585     public boolean isActivePasswordSufficient() {
3586         if (mService != null) {
3587             try {
3588                 return mService.isActivePasswordSufficient(myUserId(), mParentInstance);
3589             } catch (RemoteException e) {
3590                 throw e.rethrowFromSystemServer();
3591             }
3592         }
3593         return false;
3594     }
3595 
3596     /**
3597      * Returns how complex the current user's screen lock is.
3598      *
3599      * <p>Note that when called from a profile which uses an unified challenge with its parent, the
3600      * screen lock complexity of the parent will be returned.
3601      *
3602      * <p>This method can be called on the {@link DevicePolicyManager} instance
3603      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3604      * restrictions on the parent profile.
3605      *
3606      * @throws IllegalStateException if the user is not unlocked.
3607      * @throws SecurityException     if the calling application does not have the permission
3608      *                               {@link permission#REQUEST_PASSWORD_COMPLEXITY}
3609      */
3610     @PasswordComplexity
3611     @RequiresPermission(android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY)
getPasswordComplexity()3612     public int getPasswordComplexity() {
3613         if (mService == null) {
3614             return PASSWORD_COMPLEXITY_NONE;
3615         }
3616 
3617         try {
3618             return mService.getPasswordComplexity(mParentInstance);
3619         } catch (RemoteException e) {
3620             throw e.rethrowFromSystemServer();
3621         }
3622     }
3623 
3624     /**
3625      * When called by a profile owner of a managed profile returns true if the profile uses unified
3626      * challenge with its parent user.
3627      *
3628      * <strong>Note</strong>: This method is not concerned with password quality and will return
3629      * false if the profile has empty password as a separate challenge.
3630      *
3631      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3632      * @throws SecurityException if {@code admin} is not a profile owner of a managed profile.
3633      * @see UserManager#DISALLOW_UNIFIED_PASSWORD
3634      */
isUsingUnifiedPassword(@onNull ComponentName admin)3635     public boolean isUsingUnifiedPassword(@NonNull ComponentName admin) {
3636         throwIfParentInstance("isUsingUnifiedPassword");
3637         if (mService != null) {
3638             try {
3639                 return mService.isUsingUnifiedPassword(admin);
3640             } catch (RemoteException e) {
3641                 throw e.rethrowFromSystemServer();
3642             }
3643         }
3644         return true;
3645     }
3646 
3647     /**
3648      * Determine whether the current profile password the user has set is sufficient
3649      * to meet the policy requirements (e.g. quality, minimum length) that have been
3650      * requested by the admins of the parent user and its profiles.
3651      *
3652      * @param userHandle the userId of the profile to check the password for.
3653      * @return Returns true if the password would meet the current requirements, else false.
3654      * @throws SecurityException if {@code userHandle} is not a managed profile.
3655      * @hide
3656      */
isProfileActivePasswordSufficientForParent(int userHandle)3657     public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3658         if (mService != null) {
3659             try {
3660                 return mService.isProfileActivePasswordSufficientForParent(userHandle);
3661             } catch (RemoteException e) {
3662                 throw e.rethrowFromSystemServer();
3663             }
3664         }
3665         return false;
3666     }
3667 
3668     /**
3669      * Returns whether the given user's credential will be sufficient for all password policy
3670      * requirement, once the user's profile has switched to unified challenge.
3671      *
3672      * <p>This is different from {@link #isActivePasswordSufficient()} since once the profile
3673      * switches to unified challenge, policies set explicitly on the profile will start to affect
3674      * the parent user.
3675      * @param userHandle the user whose password requirement will be checked
3676      * @param profileUser the profile user whose lockscreen challenge will be unified.
3677      * @hide
3678      */
isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser)3679     public boolean isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser) {
3680         if (mService != null) {
3681             try {
3682                 return mService.isPasswordSufficientAfterProfileUnification(userHandle,
3683                         profileUser);
3684             } catch (RemoteException e) {
3685                 throw e.rethrowFromSystemServer();
3686             }
3687         }
3688         return false;
3689     }
3690     /**
3691      * Retrieve the number of times the user has failed at entering a password since that last
3692      * successful password entry.
3693      * <p>
3694      * This method can be called on the {@link DevicePolicyManager} instance returned by
3695      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the number of failed
3696      * password attemts for the parent user.
3697      * <p>
3698      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
3699      * to be able to call this method; if it has not, a security exception will be thrown.
3700      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3701      * password is always empty and this method always returns 0.
3702      *
3703      * @return The number of times user has entered an incorrect password since the last correct
3704      *         password entry.
3705      * @throws SecurityException if the calling application does not own an active administrator
3706      *             that uses {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
3707      */
3708     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getCurrentFailedPasswordAttempts()3709     public int getCurrentFailedPasswordAttempts() {
3710         return getCurrentFailedPasswordAttempts(myUserId());
3711     }
3712 
3713     /**
3714      * Retrieve the number of times the given user has failed at entering a
3715      * password since that last successful password entry.
3716      *
3717      * <p>The calling device admin must have requested
3718      * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call this method; if it has
3719      * not and it is not the system uid, a security exception will be thrown.
3720      *
3721      * @hide
3722      */
3723     @UnsupportedAppUsage
getCurrentFailedPasswordAttempts(int userHandle)3724     public int getCurrentFailedPasswordAttempts(int userHandle) {
3725         if (mService != null) {
3726             try {
3727                 return mService.getCurrentFailedPasswordAttempts(userHandle, mParentInstance);
3728             } catch (RemoteException e) {
3729                 throw e.rethrowFromSystemServer();
3730             }
3731         }
3732         return -1;
3733     }
3734 
3735     /**
3736      * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set.
3737      *
3738      * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set.
3739      * @hide
3740      */
getDoNotAskCredentialsOnBoot()3741     public boolean getDoNotAskCredentialsOnBoot() {
3742         if (mService != null) {
3743             try {
3744                 return mService.getDoNotAskCredentialsOnBoot();
3745             } catch (RemoteException e) {
3746                 throw e.rethrowFromSystemServer();
3747             }
3748         }
3749         return false;
3750     }
3751 
3752     /**
3753      * Setting this to a value greater than zero enables a built-in policy that will perform a
3754      * device or profile wipe after too many incorrect device-unlock passwords have been entered.
3755      * This built-in policy combines watching for failed passwords and wiping the device, and
3756      * requires that you request both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
3757      * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
3758      * <p>
3759      * When this policy is set by a device owner, profile owner of an organization-owned device or
3760      * an admin on the primary user, the device will be factory reset after too many incorrect
3761      * password attempts. When set by a profile owner or an admin on a secondary user or a managed
3762      * profile, only the corresponding user or profile will be wiped.
3763      * <p>
3764      * To implement any other policy (e.g. wiping data for a particular application only, erasing or
3765      * revoking credentials, or reporting the failure to a server), you should implement
3766      * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)} instead. Do not
3767      * use this API, because if the maximum count is reached, the device or profile will be wiped
3768      * immediately, and your callback will not be invoked.
3769      * <p>
3770      * This method can be called on the {@link DevicePolicyManager} instance returned by
3771      * {@link #getParentProfileInstance(ComponentName)} in order to set a value on the parent
3772      * profile.
3773      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3774      * password is always empty and this method has no effect - i.e. the policy is not set.
3775      *
3776      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3777      * @param num The number of failed password attempts at which point the device or profile will
3778      *            be wiped.
3779      * @throws SecurityException if {@code admin} is not an active administrator or does not use
3780      *             both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
3781      *             {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}.
3782      */
3783     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setMaximumFailedPasswordsForWipe(@onNull ComponentName admin, int num)3784     public void setMaximumFailedPasswordsForWipe(@NonNull ComponentName admin, int num) {
3785         if (mService != null) {
3786             try {
3787                 mService.setMaximumFailedPasswordsForWipe(admin, num, mParentInstance);
3788             } catch (RemoteException e) {
3789                 throw e.rethrowFromSystemServer();
3790             }
3791         }
3792     }
3793 
3794     /**
3795      * Retrieve the current maximum number of login attempts that are allowed before the device
3796      * or profile is wiped, for a particular admin or all admins that set restrictions on this user
3797      * and its participating profiles. Restrictions on profiles that have a separate challenge are
3798      * not taken into account.
3799      *
3800      * <p>This method can be called on the {@link DevicePolicyManager} instance
3801      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3802      * the value for the parent profile.
3803      *
3804      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3805      * password is always empty and this method returns a default value (0) indicating that the
3806      * policy is not set.
3807      *
3808      * @param admin The name of the admin component to check, or {@code null} to aggregate
3809      * all admins.
3810      */
3811     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin)3812     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) {
3813         return getMaximumFailedPasswordsForWipe(admin, myUserId());
3814     }
3815 
3816     /** @hide per-user version */
3817     @UnsupportedAppUsage
3818     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin, int userHandle)3819     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) {
3820         if (mService != null) {
3821             try {
3822                 return mService.getMaximumFailedPasswordsForWipe(
3823                         admin, userHandle, mParentInstance);
3824             } catch (RemoteException e) {
3825                 throw e.rethrowFromSystemServer();
3826             }
3827         }
3828         return 0;
3829     }
3830 
3831     /**
3832      * Returns the user that will be wiped first when too many failed attempts are made to unlock
3833      * user {@code userHandle}. That user is either the same as {@code userHandle} or belongs to the
3834      * same profile group. When there is no such policy, returns {@code UserHandle.USER_NULL}.
3835      * E.g. managed profile user may be wiped as a result of failed primary profile password
3836      * attempts when using unified challenge. Primary user may be wiped as a result of failed
3837      * password attempts on the managed profile on an organization-owned device.
3838      * @hide Used only by Keyguard
3839      */
3840     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getProfileWithMinimumFailedPasswordsForWipe(int userHandle)3841     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
3842         if (mService != null) {
3843             try {
3844                 return mService.getProfileWithMinimumFailedPasswordsForWipe(
3845                         userHandle, mParentInstance);
3846             } catch (RemoteException e) {
3847                 throw e.rethrowFromSystemServer();
3848             }
3849         }
3850         return UserHandle.USER_NULL;
3851     }
3852 
3853     /**
3854      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't allow other admins
3855      * to change the password again until the user has entered it.
3856      */
3857     public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
3858 
3859     /**
3860      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't ask for user
3861      * credentials on device boot.
3862      * If the flag is set, the device can be booted without asking for user password.
3863      * The absence of this flag does not change the current boot requirements. This flag
3864      * can be set by the device owner only. If the app is not the device owner, the flag
3865      * is ignored. Once the flag is set, it cannot be reverted back without resetting the
3866      * device to factory defaults.
3867      */
3868     public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
3869 
3870     /**
3871      * Force a new password for device unlock (the password needed to access the entire device) or
3872      * the work profile challenge on the current user. This takes effect immediately.
3873      *
3874      * <p> Before {@link android.os.Build.VERSION_CODES#N}, this API is available to device admin,
3875      * profile owner and device owner. Starting from {@link android.os.Build.VERSION_CODES#N},
3876      * legacy device admin (who is not also profile owner or device owner) can only call this
3877      * API to set a new password if there is currently no password set. Profile owner and device
3878      * owner can continue to force change an existing password as long as the target user is
3879      * unlocked, although device owner will not be able to call this API at all if there is also a
3880      * managed profile on the device.
3881      *
3882      * <p> Between {@link android.os.Build.VERSION_CODES#O},
3883      * {@link android.os.Build.VERSION_CODES#P} and {@link android.os.Build.VERSION_CODES#Q},
3884      * profile owner and devices owner targeting SDK level {@link android.os.Build.VERSION_CODES#O}
3885      * or above who attempt to call this API will receive {@link SecurityException}; they are
3886      * encouraged to migrate to the new {@link #resetPasswordWithToken} API instead.
3887      * Profile owner and device owner targeting older SDK levels are not affected: they continue
3888      * to experience the existing behaviour described in the previous paragraph.
3889      *
3890      * <p><em>Starting from {@link android.os.Build.VERSION_CODES#R}, this API is no longer
3891      * supported in most cases.</em> Device owner and profile owner calling
3892      * this API will receive {@link SecurityException} if they target SDK level
3893      * {@link android.os.Build.VERSION_CODES#O} or above, or they will receive a silent failure
3894      * (API returning {@code false}) if they target lower SDK level.
3895      * For legacy device admins, this API throws {@link SecurityException} if they target SDK level
3896      * {@link android.os.Build.VERSION_CODES#N} or above, and returns {@code false} otherwise. Only
3897      * privileged apps holding RESET_PASSWORD permission which are part of
3898      * the system factory image can still call this API to set a new password if there is currently
3899      * no password set. In this case, if the device already has a password, this API will throw
3900      * {@link SecurityException}.
3901      *
3902      * <p>
3903      * The given password must be sufficient for the current password quality and length constraints
3904      * as returned by {@link #getPasswordQuality(ComponentName)} and
3905      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
3906      * it will be rejected and false returned. Note that the password may be a stronger quality
3907      * (containing alphanumeric characters when the requested quality is only numeric), in which
3908      * case the currently active quality will be increased to match.
3909      *
3910      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
3911      * methods does nothing.
3912      * <p>
3913      * The calling device admin must have requested
3914      * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call this method; if it has
3915      * not, a security exception will be thrown.
3916      *
3917      * @param password The new password for the user. Null or empty clears the password.
3918      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
3919      *            {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
3920      * @return Returns true if the password was applied, or false if it is not acceptable for the
3921      *         current constraints.
3922      * @throws SecurityException if the calling application does not own an active administrator
3923      *             that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
3924      * @throws IllegalStateException if the calling user is locked or has a managed profile.
3925      * @deprecated Please use {@link #resetPasswordWithToken} instead.
3926      */
3927     @Deprecated
3928     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
resetPassword(String password, int flags)3929     public boolean resetPassword(String password, int flags) {
3930         throwIfParentInstance("resetPassword");
3931         if (mService != null) {
3932             try {
3933                 return mService.resetPassword(password, flags);
3934             } catch (RemoteException e) {
3935                 throw e.rethrowFromSystemServer();
3936             }
3937         }
3938         return false;
3939     }
3940 
3941     /**
3942      * Called by a profile or device owner to provision a token which can later be used to reset the
3943      * device lockscreen password (if called by device owner), or managed profile challenge (if
3944      * called by profile owner), via {@link #resetPasswordWithToken}.
3945      * <p>
3946      * If the user currently has a lockscreen password, the provisioned token will not be
3947      * immediately usable; it only becomes active after the user performs a confirm credential
3948      * operation, which can be triggered by {@link KeyguardManager#createConfirmDeviceCredentialIntent}.
3949      * If the user has no lockscreen password, the token is activated immediately. In all cases,
3950      * the active state of the current token can be checked by {@link #isResetPasswordTokenActive}.
3951      * For security reasons, un-activated tokens are only stored in memory and will be lost once
3952      * the device reboots. In this case a new token needs to be provisioned again.
3953      * <p>
3954      * Once provisioned and activated, the token will remain effective even if the user changes
3955      * or clears the lockscreen password.
3956      * <p>
3957      * <em>This token is highly sensitive and should be treated at the same level as user
3958      * credentials. In particular, NEVER store this token on device in plaintext. Do not store
3959      * the plaintext token in device-encrypted storage if it will be needed to reset password on
3960      * file-based encryption devices before user unlocks. Consider carefully how any password token
3961      * will be stored on your server and who will need access to them. Tokens may be the subject of
3962      * legal access requests.
3963      * </em>
3964      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3965      * reset token is not set and this method returns false.
3966      *
3967      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3968      * @param token a secure token a least 32-byte long, which must be generated by a
3969      *        cryptographically strong random number generator.
3970      * @return true if the operation is successful, false otherwise.
3971      * @throws SecurityException if admin is not a device or profile owner.
3972      * @throws IllegalArgumentException if the supplied token is invalid.
3973      */
3974     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setResetPasswordToken(ComponentName admin, byte[] token)3975     public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
3976         throwIfParentInstance("setResetPasswordToken");
3977         if (mService != null) {
3978             try {
3979                 return mService.setResetPasswordToken(admin, token);
3980             } catch (RemoteException e) {
3981                 throw e.rethrowFromSystemServer();
3982             }
3983         }
3984         return false;
3985     }
3986 
3987     /**
3988      * Called by a profile or device owner to revoke the current password reset token.
3989      *
3990      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
3991      * method has no effect - the reset token should not have been set in the first place - and
3992      * false is returned.
3993      *
3994      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3995      * @return true if the operation is successful, false otherwise.
3996      * @throws SecurityException if admin is not a device or profile owner.
3997      */
3998     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
clearResetPasswordToken(ComponentName admin)3999     public boolean clearResetPasswordToken(ComponentName admin) {
4000         throwIfParentInstance("clearResetPasswordToken");
4001         if (mService != null) {
4002             try {
4003                 return mService.clearResetPasswordToken(admin);
4004             } catch (RemoteException e) {
4005                 throw e.rethrowFromSystemServer();
4006             }
4007         }
4008         return false;
4009     }
4010 
4011     /**
4012      * Called by a profile or device owner to check if the current reset password token is active.
4013      *
4014      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
4015      * false is always returned.
4016      *
4017      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4018      * @return true if the token is active, false otherwise.
4019      * @throws SecurityException if admin is not a device or profile owner.
4020      * @throws IllegalStateException if no token has been set.
4021      */
4022     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
isResetPasswordTokenActive(ComponentName admin)4023     public boolean isResetPasswordTokenActive(ComponentName admin) {
4024         throwIfParentInstance("isResetPasswordTokenActive");
4025         if (mService != null) {
4026             try {
4027                 return mService.isResetPasswordTokenActive(admin);
4028             } catch (RemoteException e) {
4029                 throw e.rethrowFromSystemServer();
4030             }
4031         }
4032         return false;
4033     }
4034 
4035     /**
4036      * Called by device or profile owner to force set a new device unlock password or a managed
4037      * profile challenge on current user. This takes effect immediately.
4038      * <p>
4039      * Unlike {@link #resetPassword}, this API can change the password even before the user or
4040      * device is unlocked or decrypted. The supplied token must have been previously provisioned via
4041      * {@link #setResetPasswordToken}, and in active state {@link #isResetPasswordTokenActive}.
4042      * <p>
4043      * The given password must be sufficient for the current password quality and length constraints
4044      * as returned by {@link #getPasswordQuality(ComponentName)} and
4045      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
4046      * it will be rejected and false returned. Note that the password may be a stronger quality, for
4047      * example, a password containing alphanumeric characters when the requested quality is only
4048      * numeric.
4049      * <p>
4050      * Calling with a {@code null} or empty password will clear any existing PIN, pattern or
4051      * password if the current password constraints allow it.
4052      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
4053      * calling this methods has no effect - the password is always empty - and false is returned.
4054      *
4055      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4056      * @param password The new password for the user. {@code null} or empty clears the password.
4057      * @param token the password reset token previously provisioned by
4058      *        {@link #setResetPasswordToken}.
4059      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
4060      *        {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
4061      * @return Returns true if the password was applied, or false if it is not acceptable for the
4062      *         current constraints.
4063      * @throws SecurityException if admin is not a device or profile owner.
4064      * @throws IllegalStateException if the provided token is not valid.
4065      */
4066     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
resetPasswordWithToken(@onNull ComponentName admin, String password, byte[] token, int flags)4067     public boolean resetPasswordWithToken(@NonNull ComponentName admin, String password,
4068             byte[] token, int flags) {
4069         throwIfParentInstance("resetPassword");
4070         if (mService != null) {
4071             try {
4072                 return mService.resetPasswordWithToken(admin, password, token, flags);
4073             } catch (RemoteException e) {
4074                 throw e.rethrowFromSystemServer();
4075             }
4076         }
4077         return false;
4078     }
4079 
4080     /**
4081      * Called by an application that is administering the device to set the maximum time for user
4082      * activity until the device will lock. This limits the length that the user can set. It takes
4083      * effect immediately.
4084      * <p>
4085      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
4086      * to be able to call this method; if it has not, a security exception will be thrown.
4087      * <p>
4088      * This method can be called on the {@link DevicePolicyManager} instance returned by
4089      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4090      * profile.
4091      *
4092      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4093      * @param timeMs The new desired maximum time to lock in milliseconds. A value of 0 means there
4094      *            is no restriction.
4095      * @throws SecurityException if {@code admin} is not an active administrator or it does not use
4096      *             {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
4097      */
setMaximumTimeToLock(@onNull ComponentName admin, long timeMs)4098     public void setMaximumTimeToLock(@NonNull ComponentName admin, long timeMs) {
4099         if (mService != null) {
4100             try {
4101                 mService.setMaximumTimeToLock(admin, timeMs, mParentInstance);
4102             } catch (RemoteException e) {
4103                 throw e.rethrowFromSystemServer();
4104             }
4105         }
4106     }
4107 
4108     /**
4109      * Retrieve the current maximum time to unlock for a particular admin or all admins that set
4110      * restrictions on this user and its participating profiles. Restrictions on profiles that have
4111      * a separate challenge are not taken into account.
4112      *
4113      * <p>This method can be called on the {@link DevicePolicyManager} instance
4114      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4115      * restrictions on the parent profile.
4116      *
4117      * @param admin The name of the admin component to check, or {@code null} to aggregate
4118      * all admins.
4119      * @return time in milliseconds for the given admin or the minimum value (strictest) of
4120      * all admins if admin is null. Returns 0 if there are no restrictions.
4121      */
getMaximumTimeToLock(@ullable ComponentName admin)4122     public long getMaximumTimeToLock(@Nullable ComponentName admin) {
4123         return getMaximumTimeToLock(admin, myUserId());
4124     }
4125 
4126     /** @hide per-user version */
4127     @UnsupportedAppUsage
getMaximumTimeToLock(@ullable ComponentName admin, int userHandle)4128     public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) {
4129         if (mService != null) {
4130             try {
4131                 return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance);
4132             } catch (RemoteException e) {
4133                 throw e.rethrowFromSystemServer();
4134             }
4135         }
4136         return 0;
4137     }
4138 
4139     /**
4140      * Called by a device/profile owner to set the timeout after which unlocking with secondary, non
4141      * strong auth (e.g. fingerprint, face, trust agents) times out, i.e. the user has to use a
4142      * strong authentication method like password, pin or pattern.
4143      *
4144      * <p>This timeout is used internally to reset the timer to require strong auth again after
4145      * specified timeout each time it has been successfully used.
4146      *
4147      * <p>Fingerprint can also be disabled altogether using {@link #KEYGUARD_DISABLE_FINGERPRINT}.
4148      *
4149      * <p>Trust agents can also be disabled altogether using {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
4150      *
4151      * <p>The calling device admin must be a device or profile owner. If it is not,
4152      * a {@link SecurityException} will be thrown.
4153      *
4154      * <p>The calling device admin can verify the value it has set by calling
4155      * {@link #getRequiredStrongAuthTimeout(ComponentName)} and passing in its instance.
4156      *
4157      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
4158      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
4159      * profile.
4160      *
4161      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
4162      * calling this methods has no effect - i.e. the timeout is not set.
4163      *
4164      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4165      * @param timeoutMs The new timeout in milliseconds, after which the user will have to unlock
4166      *         with strong authentication method. A value of 0 means the admin is not participating
4167      *         in controlling the timeout.
4168      *         The minimum and maximum timeouts are platform-defined and are typically 1 hour and
4169      *         72 hours, respectively. Though discouraged, the admin may choose to require strong
4170      *         auth at all times using {@link #KEYGUARD_DISABLE_FINGERPRINT} and/or
4171      *         {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
4172      *
4173      * @throws SecurityException if {@code admin} is not a device or profile owner.
4174      */
4175     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setRequiredStrongAuthTimeout(@onNull ComponentName admin, long timeoutMs)4176     public void setRequiredStrongAuthTimeout(@NonNull ComponentName admin,
4177             long timeoutMs) {
4178         if (mService != null) {
4179             try {
4180                 mService.setRequiredStrongAuthTimeout(admin, timeoutMs, mParentInstance);
4181             } catch (RemoteException e) {
4182                 throw e.rethrowFromSystemServer();
4183             }
4184         }
4185     }
4186 
4187     /**
4188      * Determine for how long the user will be able to use secondary, non strong auth for
4189      * authentication, since last strong method authentication (password, pin or pattern) was used.
4190      * After the returned timeout the user is required to use strong authentication method.
4191      *
4192      * <p>This method can be called on the {@link DevicePolicyManager} instance
4193      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
4194      * restrictions on the parent profile.
4195      *
4196      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
4197      * 0 is returned to indicate that no timeout is configured.
4198      *
4199      * @param admin The name of the admin component to check, or {@code null} to aggregate
4200      *         across all participating admins.
4201      * @return The timeout in milliseconds or 0 if not configured for the provided admin.
4202      */
4203     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getRequiredStrongAuthTimeout(@ullable ComponentName admin)4204     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin) {
4205         return getRequiredStrongAuthTimeout(admin, myUserId());
4206     }
4207 
4208     /** @hide per-user version */
4209     @UnsupportedAppUsage
4210     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getRequiredStrongAuthTimeout(@ullable ComponentName admin, @UserIdInt int userId)4211     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin, @UserIdInt int userId) {
4212         if (mService != null) {
4213             try {
4214                 return mService.getRequiredStrongAuthTimeout(admin, userId, mParentInstance);
4215             } catch (RemoteException e) {
4216                 throw e.rethrowFromSystemServer();
4217             }
4218         }
4219         return DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4220     }
4221 
4222     /**
4223      * Flag for {@link #lockNow(int)}: also evict the user's credential encryption key from the
4224      * keyring. The user's credential will need to be entered again in order to derive the
4225      * credential encryption key that will be stored back in the keyring for future use.
4226      * <p>
4227      * This flag can only be used by a profile owner when locking a managed profile when
4228      * {@link #getStorageEncryptionStatus} returns {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
4229      * <p>
4230      * In order to secure user data, the user will be stopped and restarted so apps should wait
4231      * until they are next run to perform further actions.
4232      */
4233     public static final int FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY = 1;
4234 
4235     /** @hide */
4236     @Retention(RetentionPolicy.SOURCE)
4237     @IntDef(flag = true, prefix = { "FLAG_EVICT_" }, value = {
4238             FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY
4239     })
4240     public @interface LockNowFlag {}
4241 
4242     /**
4243      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
4244      * this call.
4245      * <p>
4246      * This method secures the device in response to an urgent situation, such as a lost or stolen
4247      * device. After this method is called, the device must be unlocked using strong authentication
4248      * (PIN, pattern, or password). This API is intended for use only by device admins.
4249      * <p>
4250      * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have
4251      * the LOCK_DEVICE permission or the device must have the device admin feature; if neither is
4252      * true, then the method will return without completing any action. Before version
4253      * {@link android.os.Build.VERSION_CODES#R}, the device needed the device admin feature,
4254      * regardless of the caller's permissions.
4255      * <p>
4256      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
4257      * to be able to call this method; if it has not, a security exception will be thrown.
4258      * <p>
4259      * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
4260      * the device. Device admins who find the device in this state can lock an otherwise-insecure
4261      * device by first calling {@link #resetPassword} to set the password and then lock the device.
4262      * <p>
4263      * This method can be called on the {@link DevicePolicyManager} instance returned by
4264      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
4265      * <p>
4266      * Equivalent to calling {@link #lockNow(int)} with no flags.
4267      *
4268      * @throws SecurityException if the calling application does not own an active administrator
4269      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
4270      */
lockNow()4271     public void lockNow() {
4272         lockNow(0);
4273     }
4274 
4275     /**
4276      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
4277      * this call.
4278      * <p>
4279      * This method secures the device in response to an urgent situation, such as a lost or stolen
4280      * device. After this method is called, the device must be unlocked using strong authentication
4281      * (PIN, pattern, or password). This API is intended for use only by device admins.
4282      * <p>
4283      * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have
4284      * the LOCK_DEVICE permission or the device must have the device admin feature; if neither is
4285      * true, then the method will return without completing any action. Before version
4286      * {@link android.os.Build.VERSION_CODES#R}, the device needed the device admin feature,
4287      * regardless of the caller's permissions.
4288      * <p>
4289      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
4290      * to be able to call this method; if it has not, a security exception will be thrown.
4291      * <p>
4292      * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
4293      * the device. Device admins who find the device in this state can lock an otherwise-insecure
4294      * device by first calling {@link #resetPassword} to set the password and then lock the device.
4295      * <p>
4296      * This method can be called on the {@link DevicePolicyManager} instance returned by
4297      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile as
4298      * well as the managed profile.
4299      * <p>
4300      * NOTE: In order to lock the parent profile and evict the encryption key of the managed
4301      * profile, {@link #lockNow()} must be called twice: First, {@link #lockNow()} should be called
4302      * on the {@link DevicePolicyManager} instance returned by
4303      * {@link #getParentProfileInstance(ComponentName)}, then {@link #lockNow(int)} should be
4304      * called on the {@link DevicePolicyManager} instance associated with the managed profile,
4305      * with the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag.
4306      * Calling the method twice in this order ensures that all users are locked and does not
4307      * stop the device admin on the managed profile from issuing a second call to lock its own
4308      * profile.
4309      *
4310      * @param flags May be 0 or {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}.
4311      * @throws SecurityException if the calling application does not own an active administrator
4312      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} or the
4313      *             {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is passed by an application
4314      *             that is not a profile
4315      *             owner of a managed profile.
4316      * @throws IllegalArgumentException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is
4317      *             passed when locking the parent profile.
4318      * @throws UnsupportedOperationException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}
4319      *             flag is passed when {@link #getStorageEncryptionStatus} does not return
4320      *             {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
4321      */
lockNow(@ockNowFlag int flags)4322     public void lockNow(@LockNowFlag int flags) {
4323         if (mService != null) {
4324             try {
4325                 mService.lockNow(flags, mParentInstance);
4326             } catch (RemoteException e) {
4327                 throw e.rethrowFromSystemServer();
4328             }
4329         }
4330     }
4331 
4332     /**
4333      * Flag for {@link #wipeData(int)}: also erase the device's external
4334      * storage (such as SD cards).
4335      */
4336     public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
4337 
4338     /**
4339      * Flag for {@link #wipeData(int)}: also erase the factory reset protection
4340      * data.
4341      *
4342      * <p>This flag may only be set by device owner admins; if it is set by
4343      * other admins a {@link SecurityException} will be thrown.
4344      */
4345     public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
4346 
4347     /**
4348      * Flag for {@link #wipeData(int)}: also erase the device's eUICC data.
4349      */
4350     public static final int WIPE_EUICC = 0x0004;
4351 
4352     /**
4353      * Flag for {@link #wipeData(int)}: won't show reason for wiping to the user.
4354      */
4355     public static final int WIPE_SILENTLY = 0x0008;
4356 
4357     /**
4358      * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
4359      * other users will remain unaffected. Calling from the primary user will cause the device to
4360      * reboot, erasing all device data - including all the secondary users and their data - while
4361      * booting up.
4362      * <p>
4363      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
4364      * be able to call this method; if it has not, a security exception will be thrown.
4365      *
4366      * If the caller is a profile owner of an organization-owned managed profile, it may
4367      * additionally call this method on the parent instance.
4368      * Calling this method on the parent {@link DevicePolicyManager} instance would wipe the
4369      * entire device, while calling it on the current profile instance would relinquish the device
4370      * for personal use, removing the managed profile and all policies set by the profile owner.
4371      *
4372      * @param flags Bit mask of additional options: currently supported flags are
4373      *            {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA},
4374      *            {@link #WIPE_EUICC} and {@link #WIPE_SILENTLY}.
4375      * @throws SecurityException if the calling application does not own an active administrator
4376      *            that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
4377      */
wipeData(int flags)4378     public void wipeData(int flags) {
4379         wipeDataInternal(flags, "");
4380     }
4381 
4382     /**
4383      * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
4384      * other users will remain unaffected, the provided reason for wiping data can be shown to
4385      * user. Calling from the primary user will cause the device to reboot, erasing all device data
4386      * - including all the secondary users and their data - while booting up. In this case, we don't
4387      * show the reason to the user since the device would be factory reset.
4388      * <p>
4389      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
4390      * be able to call this method; if it has not, a security exception will be thrown.
4391      *
4392      * If the caller is a profile owner of an organization-owned managed profile, it may
4393      * additionally call this method on the parent instance.
4394      * Calling this method on the parent {@link DevicePolicyManager} instance would wipe the
4395      * entire device, while calling it on the current profile instance would relinquish the device
4396      * for personal use, removing the managed profile and all policies set by the profile owner.
4397      *
4398      * @param flags Bit mask of additional options: currently supported flags are
4399      *            {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA} and
4400      *            {@link #WIPE_EUICC}.
4401      * @param reason a string that contains the reason for wiping data, which can be
4402      *            presented to the user.
4403      * @throws SecurityException if the calling application does not own an active administrator
4404      *            that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
4405      * @throws IllegalArgumentException if the input reason string is null or empty, or if
4406      *            {@link #WIPE_SILENTLY} is set.
4407      */
wipeData(int flags, @NonNull CharSequence reason)4408     public void wipeData(int flags, @NonNull CharSequence reason) {
4409         Objects.requireNonNull(reason, "reason string is null");
4410         Preconditions.checkStringNotEmpty(reason, "reason string is empty");
4411         Preconditions.checkArgument((flags & WIPE_SILENTLY) == 0, "WIPE_SILENTLY cannot be set");
4412         wipeDataInternal(flags, reason.toString());
4413     }
4414 
4415     /**
4416      * Internal function for both {@link #wipeData(int)} and
4417      * {@link #wipeData(int, CharSequence)} to call.
4418      *
4419      * @see #wipeData(int)
4420      * @see #wipeData(int, CharSequence)
4421      * @hide
4422      */
wipeDataInternal(int flags, @NonNull String wipeReasonForUser)4423     private void wipeDataInternal(int flags, @NonNull String wipeReasonForUser) {
4424         if (mService != null) {
4425             try {
4426                 mService.wipeDataWithReason(flags, wipeReasonForUser, mParentInstance);
4427             } catch (RemoteException e) {
4428                 throw e.rethrowFromSystemServer();
4429             }
4430         }
4431     }
4432 
4433     /**
4434      * Callable by device owner or profile owner of an organization-owned device, to set a
4435      * factory reset protection (FRP) policy. When a new policy is set, the system
4436      * notifies the FRP management agent of a policy change by broadcasting
4437      * {@code ACTION_RESET_PROTECTION_POLICY_CHANGED}.
4438      *
4439      * @param admin  Which {@link DeviceAdminReceiver} this request is associated with.
4440      * @param policy the new FRP policy, or {@code null} to clear the current policy.
4441      * @throws SecurityException if {@code admin} is not a device owner or a profile owner of
4442      *                           an organization-owned device.
4443      * @throws UnsupportedOperationException if factory reset protection is not
4444      *                           supported on the device.
4445      */
setFactoryResetProtectionPolicy(@onNull ComponentName admin, @Nullable FactoryResetProtectionPolicy policy)4446     public void setFactoryResetProtectionPolicy(@NonNull ComponentName admin,
4447             @Nullable FactoryResetProtectionPolicy policy) {
4448         throwIfParentInstance("setFactoryResetProtectionPolicy");
4449         if (mService != null) {
4450             try {
4451                 mService.setFactoryResetProtectionPolicy(admin, policy);
4452             } catch (RemoteException e) {
4453                 throw e.rethrowFromSystemServer();
4454             }
4455         }
4456     }
4457 
4458     /**
4459      * Callable by device owner or profile owner of an organization-owned device, to retrieve
4460      * the current factory reset protection (FRP) policy set previously by
4461      * {@link #setFactoryResetProtectionPolicy}.
4462      * <p>
4463      * This method can also be called by the FRP management agent on device or with the permission
4464      * {@link android.Manifest.permission#MASTER_CLEAR}, in which case, it can pass {@code null}
4465      * as the ComponentName.
4466      *
4467      * @param admin Which {@link DeviceAdminReceiver} this request is associated with or
4468      *              {@code null} if called by the FRP management agent on device or with the
4469      *              permission {@link android.Manifest.permission#MASTER_CLEAR}.
4470      * @return The current FRP policy object or {@code null} if no policy is set.
4471      * @throws SecurityException if {@code admin} is not a device owner, a profile owner of
4472      *                           an organization-owned device or the FRP management agent.
4473      * @throws UnsupportedOperationException if factory reset protection is not
4474      *                           supported on the device.
4475      */
getFactoryResetProtectionPolicy( @ullable ComponentName admin)4476     public @Nullable FactoryResetProtectionPolicy getFactoryResetProtectionPolicy(
4477             @Nullable ComponentName admin) {
4478         throwIfParentInstance("getFactoryResetProtectionPolicy");
4479         if (mService != null) {
4480             try {
4481                 return mService.getFactoryResetProtectionPolicy(admin);
4482             } catch (RemoteException e) {
4483                 throw e.rethrowFromSystemServer();
4484             }
4485         }
4486         return null;
4487     }
4488 
4489     /**
4490      * Called by an application that is administering the device to set the
4491      * global proxy and exclusion list.
4492      * <p>
4493      * The calling device admin must have requested
4494      * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
4495      * this method; if it has not, a security exception will be thrown.
4496      * Only the first device admin can set the proxy. If a second admin attempts
4497      * to set the proxy, the {@link ComponentName} of the admin originally setting the
4498      * proxy will be returned. If successful in setting the proxy, {@code null} will
4499      * be returned.
4500      * The method can be called repeatedly by the device admin alrady setting the
4501      * proxy to update the proxy and exclusion list.
4502      *
4503      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4504      * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
4505      *            Pass Proxy.NO_PROXY to reset the proxy.
4506      * @param exclusionList a list of domains to be excluded from the global proxy.
4507      * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
4508      *            of the device admin that sets the proxy.
4509      * @hide
4510      */
4511     @UnsupportedAppUsage
setGlobalProxy(@onNull ComponentName admin, Proxy proxySpec, List<String> exclusionList )4512     public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
4513             List<String> exclusionList ) {
4514         throwIfParentInstance("setGlobalProxy");
4515         if (proxySpec == null) {
4516             throw new NullPointerException();
4517         }
4518         if (mService != null) {
4519             try {
4520                 String hostSpec;
4521                 String exclSpec;
4522                 if (proxySpec.equals(Proxy.NO_PROXY)) {
4523                     hostSpec = null;
4524                     exclSpec = null;
4525                 } else {
4526                     if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
4527                         throw new IllegalArgumentException();
4528                     }
4529                     InetSocketAddress sa = (InetSocketAddress)proxySpec.address();
4530                     String hostName = sa.getHostName();
4531                     int port = sa.getPort();
4532                     StringBuilder hostBuilder = new StringBuilder();
4533                     hostSpec = hostBuilder.append(hostName)
4534                         .append(":").append(Integer.toString(port)).toString();
4535                     if (exclusionList == null) {
4536                         exclSpec = "";
4537                     } else {
4538                         StringBuilder listBuilder = new StringBuilder();
4539                         boolean firstDomain = true;
4540                         for (String exclDomain : exclusionList) {
4541                             if (!firstDomain) {
4542                                 listBuilder = listBuilder.append(",");
4543                             } else {
4544                                 firstDomain = false;
4545                             }
4546                             listBuilder = listBuilder.append(exclDomain.trim());
4547                         }
4548                         exclSpec = listBuilder.toString();
4549                     }
4550                     if (android.net.Proxy.validate(hostName, Integer.toString(port), exclSpec)
4551                             != android.net.Proxy.PROXY_VALID)
4552                         throw new IllegalArgumentException();
4553                 }
4554                 return mService.setGlobalProxy(admin, hostSpec, exclSpec);
4555             } catch (RemoteException e) {
4556                 throw e.rethrowFromSystemServer();
4557             }
4558         }
4559         return null;
4560     }
4561 
4562     /**
4563      * Set a network-independent global HTTP proxy. This is not normally what you want for typical
4564      * HTTP proxies - they are generally network dependent. However if you're doing something
4565      * unusual like general internal filtering this may be useful. On a private network where the
4566      * proxy is not accessible, you may break HTTP using this.
4567      * <p>
4568      * This method requires the caller to be the device owner.
4569      * <p>
4570      * This proxy is only a recommendation and it is possible that some apps will ignore it.
4571      *
4572      * @see ProxyInfo
4573      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4574      * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A
4575      *            {@code null} value will clear the global HTTP proxy.
4576      * @throws SecurityException if {@code admin} is not the device owner.
4577      */
setRecommendedGlobalProxy(@onNull ComponentName admin, @Nullable ProxyInfo proxyInfo)4578     public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
4579             proxyInfo) {
4580         throwIfParentInstance("setRecommendedGlobalProxy");
4581         if (mService != null) {
4582             try {
4583                 mService.setRecommendedGlobalProxy(admin, proxyInfo);
4584             } catch (RemoteException e) {
4585                 throw e.rethrowFromSystemServer();
4586             }
4587         }
4588     }
4589 
4590     /**
4591      * Returns the component name setting the global proxy.
4592      * @return ComponentName object of the device admin that set the global proxy, or {@code null}
4593      *         if no admin has set the proxy.
4594      * @hide
4595      */
getGlobalProxyAdmin()4596     public @Nullable ComponentName getGlobalProxyAdmin() {
4597         if (mService != null) {
4598             try {
4599                 return mService.getGlobalProxyAdmin(myUserId());
4600             } catch (RemoteException e) {
4601                 throw e.rethrowFromSystemServer();
4602             }
4603         }
4604         return null;
4605     }
4606 
4607     /**
4608      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
4609      * indicating that encryption is not supported.
4610      */
4611     public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
4612 
4613     /**
4614      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
4615      * indicating that encryption is supported, but is not currently active.
4616      */
4617     public static final int ENCRYPTION_STATUS_INACTIVE = 1;
4618 
4619     /**
4620      * Result code for {@link #getStorageEncryptionStatus}:
4621      * indicating that encryption is not currently active, but is currently
4622      * being activated.  This is only reported by devices that support
4623      * encryption of data and only when the storage is currently
4624      * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
4625      * to become encrypted will never return this value.
4626      */
4627     public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
4628 
4629     /**
4630      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
4631      * indicating that encryption is active.
4632      * <p>
4633      * Also see {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
4634      */
4635     public static final int ENCRYPTION_STATUS_ACTIVE = 3;
4636 
4637     /**
4638      * Result code for {@link #getStorageEncryptionStatus}:
4639      * indicating that encryption is active, but an encryption key has not
4640      * been set by the user.
4641      */
4642     public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
4643 
4644     /**
4645      * Result code for {@link #getStorageEncryptionStatus}:
4646      * indicating that encryption is active and the encryption key is tied to the user or profile.
4647      * <p>
4648      * This value is only returned to apps targeting API level 24 and above. For apps targeting
4649      * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the
4650      * encryption key is specific to the user or profile.
4651      */
4652     public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5;
4653 
4654     /**
4655      * Activity action: begin the process of encrypting data on the device.  This activity should
4656      * be launched after using {@link #setStorageEncryption} to request encryption be activated.
4657      * After resuming from this activity, use {@link #getStorageEncryption}
4658      * to check encryption status.  However, on some devices this activity may never return, as
4659      * it may trigger a reboot and in some cases a complete data wipe of the device.
4660      */
4661     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
4662     public static final String ACTION_START_ENCRYPTION
4663             = "android.app.action.START_ENCRYPTION";
4664 
4665     /**
4666      * Activity action: launch the DPC to check policy compliance. This intent is launched when
4667      * the user taps on the notification about personal apps suspension. When handling this intent
4668      * the DPC must check if personal apps should still be suspended and either unsuspend them or
4669      * instruct the user on how to resolve the noncompliance causing the suspension.
4670      *
4671      * @see #setPersonalAppsSuspended
4672      */
4673     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
4674     public static final String ACTION_CHECK_POLICY_COMPLIANCE =
4675             "android.app.action.CHECK_POLICY_COMPLIANCE";
4676 
4677     /**
4678      * Broadcast action: notify managed provisioning that new managed user is created.
4679      *
4680      * @hide
4681      */
4682     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4683     public static final String ACTION_MANAGED_USER_CREATED =
4684             "android.app.action.MANAGED_USER_CREATED";
4685 
4686     /**
4687      * Widgets are enabled in keyguard
4688      */
4689     public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
4690 
4691     /**
4692      * Disable all keyguard widgets. Has no effect starting from
4693      * {@link android.os.Build.VERSION_CODES#LOLLIPOP} since keyguard widget is only supported
4694      * on Android versions lower than 5.0.
4695      */
4696     public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
4697 
4698     /**
4699      * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
4700      */
4701     public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
4702 
4703     /**
4704      * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
4705      */
4706     public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
4707 
4708     /**
4709      * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
4710      */
4711     public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
4712 
4713     /**
4714      * Disable trust agents on secure keyguard screens (e.g. PIN/Pattern/Password).
4715      * By setting this flag alone, all trust agents are disabled. If the admin then wants to
4716      * whitelist specific features of some trust agent, {@link #setTrustAgentConfiguration} can be
4717      * used in conjuction to set trust-agent-specific configurations.
4718      */
4719     public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
4720 
4721     /**
4722      * Disable fingerprint authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
4723      */
4724     public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
4725 
4726     /**
4727      * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
4728      * This flag has no effect starting from version {@link android.os.Build.VERSION_CODES#N}
4729      */
4730     public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
4731 
4732     /**
4733      * Disable face authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
4734      */
4735     public static final int KEYGUARD_DISABLE_FACE = 1 << 7;
4736 
4737     /**
4738      * Disable iris authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
4739      */
4740     public static final int KEYGUARD_DISABLE_IRIS = 1 << 8;
4741 
4742     /**
4743      * NOTE: Please remember to update the DevicePolicyManagerTest's testKeyguardDisabledFeatures
4744      * CTS test when adding to the list above.
4745      */
4746 
4747     /**
4748      * Disable all biometric authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
4749      */
4750     public static final int KEYGUARD_DISABLE_BIOMETRICS =
4751             DevicePolicyManager.KEYGUARD_DISABLE_FACE
4752             | DevicePolicyManager.KEYGUARD_DISABLE_IRIS
4753             | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
4754 
4755     /**
4756      * Disable all current and future keyguard customizations.
4757      */
4758     public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
4759 
4760     /**
4761      * Keyguard features that when set on a non-organization-owned managed profile that doesn't
4762      * have its own challenge will affect the profile's parent user. These can also be set on the
4763      * managed profile's parent {@link DevicePolicyManager} instance to explicitly control the
4764      * parent user.
4765      *
4766      * <p>
4767      * Organization-owned managed profile supports disabling additional keyguard features on the
4768      * parent user as defined in {@link #ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY}.
4769      *
4770      * @hide
4771      */
4772     public static final int NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
4773             DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
4774             | DevicePolicyManager.KEYGUARD_DISABLE_BIOMETRICS;
4775 
4776     /**
4777      * Keyguard features that when set by the profile owner of an organization-owned managed
4778      * profile will affect the profile's parent user if set on the managed profile's parent
4779      * {@link DevicePolicyManager} instance.
4780      *
4781      * @hide
4782      */
4783     public static final int ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY =
4784             DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA
4785                     | DevicePolicyManager.KEYGUARD_DISABLE_SECURE_NOTIFICATIONS;
4786 
4787     /**
4788      * Keyguard features that when set on a normal or organization-owned managed profile, have
4789      * the potential to affect the profile's parent user.
4790      *
4791      * @hide
4792      */
4793     public static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
4794             DevicePolicyManager.NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER
4795                     | DevicePolicyManager.ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY;
4796 
4797     /**
4798      * @deprecated This method does not actually modify the storage encryption of the device.
4799      * It has never affected the encryption status of a device.
4800      *
4801      * Called by an application that is administering the device to request that the storage system
4802      * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
4803      * <p>
4804      * When multiple device administrators attempt to control device encryption, the most secure,
4805      * supported setting will always be used. If any device administrator requests device
4806      * encryption, it will be enabled; Conversely, if a device administrator attempts to disable
4807      * device encryption while another device administrator has enabled it, the call to disable will
4808      * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
4809      * <p>
4810      * This policy controls encryption of the secure (application data) storage area. Data written
4811      * to other storage areas may or may not be encrypted, and this policy does not require or
4812      * control the encryption of any other storage areas. There is one exception: If
4813      * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the
4814      * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be
4815      * written to disk within the encrypted storage area.
4816      * <p>
4817      * Important Note: On some devices, it is possible to encrypt storage without requiring the user
4818      * to create a device PIN or Password. In this case, the storage is encrypted, but the
4819      * encryption key may not be fully secured. For maximum security, the administrator should also
4820      * require (and check for) a pattern, PIN, or password.
4821      *
4822      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4823      * @param encrypt true to request encryption, false to release any previous request
4824      * @return the new total request status (for all active admins), or {@link
4825      *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user.
4826      *         Will be one of {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link
4827      *         #ENCRYPTION_STATUS_INACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value
4828      *         of the requests; use {@link #getStorageEncryptionStatus()} to query the actual device
4829      *         state.
4830      *
4831      * @throws SecurityException if {@code admin} is not an active administrator or does not use
4832      *             {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE}
4833      */
4834     @Deprecated
setStorageEncryption(@onNull ComponentName admin, boolean encrypt)4835     public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
4836         throwIfParentInstance("setStorageEncryption");
4837         if (mService != null) {
4838             try {
4839                 return mService.setStorageEncryption(admin, encrypt);
4840             } catch (RemoteException e) {
4841                 throw e.rethrowFromSystemServer();
4842             }
4843         }
4844         return ENCRYPTION_STATUS_UNSUPPORTED;
4845     }
4846 
4847     /**
4848      * @deprecated This method only returns the value set by {@link #setStorageEncryption}.
4849      * It does not actually reflect the storage encryption status.
4850      * Use {@link #getStorageEncryptionStatus} for that.
4851      *
4852      * Called by an application that is administering the device to
4853      * determine the requested setting for secure storage.
4854      *
4855      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
4856      * this will return the requested encryption setting as an aggregate of all active
4857      * administrators.
4858      * @return true if the admin(s) are requesting encryption, false if not.
4859      */
4860     @Deprecated
getStorageEncryption(@ullable ComponentName admin)4861     public boolean getStorageEncryption(@Nullable ComponentName admin) {
4862         throwIfParentInstance("getStorageEncryption");
4863         if (mService != null) {
4864             try {
4865                 return mService.getStorageEncryption(admin, myUserId());
4866             } catch (RemoteException e) {
4867                 throw e.rethrowFromSystemServer();
4868             }
4869         }
4870         return false;
4871     }
4872 
4873     /**
4874      * Called by an application that is administering the device to
4875      * determine the current encryption status of the device.
4876      * <p>
4877      * Depending on the returned status code, the caller may proceed in different
4878      * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
4879      * storage system does not support encryption.  If the
4880      * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
4881      * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
4882      * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
4883      * storage system has enabled encryption but no password is set so further action
4884      * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING},
4885      * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER},
4886      * no further action is required.
4887      *
4888      * @return current status of encryption. The value will be one of
4889      * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
4890      * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
4891      * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
4892      */
getStorageEncryptionStatus()4893     public int getStorageEncryptionStatus() {
4894         throwIfParentInstance("getStorageEncryptionStatus");
4895         return getStorageEncryptionStatus(myUserId());
4896     }
4897 
4898     /** @hide per-user version */
4899     @UnsupportedAppUsage
getStorageEncryptionStatus(int userHandle)4900     public int getStorageEncryptionStatus(int userHandle) {
4901         if (mService != null) {
4902             try {
4903                 return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle);
4904             } catch (RemoteException e) {
4905                 throw e.rethrowFromSystemServer();
4906             }
4907         }
4908         return ENCRYPTION_STATUS_UNSUPPORTED;
4909     }
4910 
4911     /**
4912      * Mark a CA certificate as approved by the device user. This means that they have been notified
4913      * of the installation, were made aware of the risks, viewed the certificate and still wanted to
4914      * keep the certificate on the device.
4915      *
4916      * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to
4917      * this certificate.
4918      *
4919      * @hide
4920      */
approveCaCert(String alias, int userHandle, boolean approval)4921     public boolean approveCaCert(String alias, int userHandle, boolean approval) {
4922         if (mService != null) {
4923             try {
4924                 return mService.approveCaCert(alias, userHandle, approval);
4925             } catch (RemoteException e) {
4926                 throw e.rethrowFromSystemServer();
4927             }
4928         }
4929         return false;
4930     }
4931 
4932     /**
4933      * Check whether a CA certificate has been approved by the device user.
4934      *
4935      * @hide
4936      */
isCaCertApproved(String alias, int userHandle)4937     public boolean isCaCertApproved(String alias, int userHandle) {
4938         if (mService != null) {
4939             try {
4940                 return mService.isCaCertApproved(alias, userHandle);
4941             } catch (RemoteException e) {
4942                 throw e.rethrowFromSystemServer();
4943             }
4944         }
4945         return false;
4946     }
4947 
4948     /**
4949      * Installs the given certificate as a user CA.
4950      * <p>
4951      * Inserted user CAs aren't automatically trusted by apps in Android 7.0 (API level 24) and
4952      * higher. App developers can change the default behavior for an app by adding a
4953      * <a href="{@docRoot}training/articles/security-config.html">Security Configuration
4954      * File</a> to the app manifest file.
4955      *
4956      * The caller must be a profile or device owner on that user, or a delegate package given the
4957      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
4958      * security exception will be thrown.
4959      *
4960      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4961      *              {@code null} if calling from a delegated certificate installer.
4962      * @param certBuffer encoded form of the certificate to install.
4963      *
4964      * @return false if the certBuffer cannot be parsed or installation is
4965      *         interrupted, true otherwise.
4966      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4967      *         owner.
4968      * @see #setDelegatedScopes
4969      * @see #DELEGATION_CERT_INSTALL
4970      */
installCaCert(@ullable ComponentName admin, byte[] certBuffer)4971     public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
4972         throwIfParentInstance("installCaCert");
4973         if (mService != null) {
4974             try {
4975                 return mService.installCaCert(admin, mContext.getPackageName(), certBuffer);
4976             } catch (RemoteException e) {
4977                 throw e.rethrowFromSystemServer();
4978             }
4979         }
4980         return false;
4981     }
4982 
4983     /**
4984      * Uninstalls the given certificate from trusted user CAs, if present.
4985      *
4986      * The caller must be a profile or device owner on that user, or a delegate package given the
4987      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
4988      * security exception will be thrown.
4989      *
4990      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4991      *              {@code null} if calling from a delegated certificate installer.
4992      * @param certBuffer encoded form of the certificate to remove.
4993      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4994      *         owner.
4995      * @see #setDelegatedScopes
4996      * @see #DELEGATION_CERT_INSTALL
4997      */
uninstallCaCert(@ullable ComponentName admin, byte[] certBuffer)4998     public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
4999         throwIfParentInstance("uninstallCaCert");
5000         if (mService != null) {
5001             try {
5002                 final String alias = getCaCertAlias(certBuffer);
5003                 mService.uninstallCaCerts(admin, mContext.getPackageName(), new String[] {alias});
5004             } catch (CertificateException e) {
5005                 Log.w(TAG, "Unable to parse certificate", e);
5006             } catch (RemoteException e) {
5007                 throw e.rethrowFromSystemServer();
5008             }
5009         }
5010     }
5011 
5012     /**
5013      * Returns all CA certificates that are currently trusted, excluding system CA certificates.
5014      * If a user has installed any certificates by other means than device policy these will be
5015      * included too.
5016      *
5017      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5018      *              {@code null} if calling from a delegated certificate installer.
5019      * @return a List of byte[] arrays, each encoding one user CA certificate.
5020      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5021      *         owner.
5022      */
getInstalledCaCerts(@ullable ComponentName admin)5023     public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
5024         final List<byte[]> certs = new ArrayList<byte[]>();
5025         throwIfParentInstance("getInstalledCaCerts");
5026         if (mService != null) {
5027             try {
5028                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
5029                 final TrustedCertificateStore certStore = new TrustedCertificateStore();
5030                 for (String alias : certStore.userAliases()) {
5031                     try {
5032                         certs.add(certStore.getCertificate(alias).getEncoded());
5033                     } catch (CertificateException ce) {
5034                         Log.w(TAG, "Could not encode certificate: " + alias, ce);
5035                     }
5036                 }
5037             } catch (RemoteException re) {
5038                 throw re.rethrowFromSystemServer();
5039             }
5040         }
5041         return certs;
5042     }
5043 
5044     /**
5045      * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
5046      * means other than device policy will also be removed, except for system CA certificates.
5047      *
5048      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5049      *              {@code null} if calling from a delegated certificate installer.
5050      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5051      *         owner.
5052      */
uninstallAllUserCaCerts(@ullable ComponentName admin)5053     public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
5054         throwIfParentInstance("uninstallAllUserCaCerts");
5055         if (mService != null) {
5056             try {
5057                 mService.uninstallCaCerts(admin, mContext.getPackageName(),
5058                         new TrustedCertificateStore().userAliases() .toArray(new String[0]));
5059             } catch (RemoteException re) {
5060                 throw re.rethrowFromSystemServer();
5061             }
5062         }
5063     }
5064 
5065     /**
5066      * Returns whether this certificate is installed as a trusted CA.
5067      *
5068      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5069      *              {@code null} if calling from a delegated certificate installer.
5070      * @param certBuffer encoded form of the certificate to look up.
5071      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5072      *         owner.
5073      */
hasCaCertInstalled(@ullable ComponentName admin, byte[] certBuffer)5074     public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
5075         throwIfParentInstance("hasCaCertInstalled");
5076         if (mService != null) {
5077             try {
5078                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
5079                 return getCaCertAlias(certBuffer) != null;
5080             } catch (RemoteException re) {
5081                 throw re.rethrowFromSystemServer();
5082             } catch (CertificateException ce) {
5083                 Log.w(TAG, "Could not parse certificate", ce);
5084             }
5085         }
5086         return false;
5087     }
5088 
5089     /**
5090      * Called by a device or profile owner, or delegated certificate installer, to install a
5091      * certificate and corresponding private key. All apps within the profile will be able to access
5092      * the certificate and use the private key, given direct user approval.
5093      *
5094      * <p>Access to the installed credentials will not be granted to the caller of this API without
5095      * direct user approval. This is for security - should a certificate installer become
5096      * compromised, certificates it had already installed will be protected.
5097      *
5098      * <p>If the installer must have access to the credentials, call
5099      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead.
5100      *
5101      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
5102      * have been given to access the key and certificates associated with this alias will be
5103      * revoked.
5104      *
5105      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5106      *            {@code null} if calling from a delegated certificate installer.
5107      * @param privKey The private key to install.
5108      * @param cert The certificate to install.
5109      * @param alias The private key alias under which to install the certificate. If a certificate
5110      * with that alias already exists, it will be overwritten.
5111      * @return {@code true} if the keys were installed, {@code false} otherwise.
5112      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5113      *         owner.
5114      * @see #setDelegatedScopes
5115      * @see #DELEGATION_CERT_INSTALL
5116      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate cert, @NonNull String alias)5117     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
5118             @NonNull Certificate cert, @NonNull String alias) {
5119         return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false);
5120     }
5121 
5122     /**
5123      * Called by a device or profile owner, or delegated certificate installer, to install a
5124      * certificate chain and corresponding private key for the leaf certificate. All apps within the
5125      * profile will be able to access the certificate chain and use the private key, given direct
5126      * user approval.
5127      *
5128      * <p>The caller of this API may grant itself access to the certificate and private key
5129      * immediately, without user approval. It is a best practice not to request this unless strictly
5130      * necessary since it opens up additional security vulnerabilities.
5131      *
5132      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
5133      * have been given to access the key and certificates associated with this alias will be
5134      * revoked.
5135      *
5136      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5137      *        {@code null} if calling from a delegated certificate installer.
5138      * @param privKey The private key to install.
5139      * @param certs The certificate chain to install. The chain should start with the leaf
5140      *        certificate and include the chain of trust in order. This will be returned by
5141      *        {@link android.security.KeyChain#getCertificateChain}.
5142      * @param alias The private key alias under which to install the certificate. If a certificate
5143      *        with that alias already exists, it will be overwritten.
5144      * @param requestAccess {@code true} to request that the calling app be granted access to the
5145      *        credentials immediately. Otherwise, access to the credentials will be gated by user
5146      *        approval.
5147      * @return {@code true} if the keys were installed, {@code false} otherwise.
5148      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5149      *         owner.
5150      * @see android.security.KeyChain#getCertificateChain
5151      * @see #setDelegatedScopes
5152      * @see #DELEGATION_CERT_INSTALL
5153      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess)5154     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
5155             @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) {
5156         int flags = INSTALLKEY_SET_USER_SELECTABLE;
5157         if (requestAccess) {
5158             flags |= INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
5159         }
5160         return installKeyPair(admin, privKey, certs, alias, flags);
5161     }
5162 
5163     /**
5164      * Called by a device or profile owner, or delegated certificate installer, to install a
5165      * certificate chain and corresponding private key for the leaf certificate. All apps within the
5166      * profile will be able to access the certificate chain and use the private key, given direct
5167      * user approval (if the user is allowed to select the private key).
5168      *
5169      * <p>The caller of this API may grant itself access to the certificate and private key
5170      * immediately, without user approval. It is a best practice not to request this unless strictly
5171      * necessary since it opens up additional security vulnerabilities.
5172      *
5173      * <p>Include {@link #INSTALLKEY_SET_USER_SELECTABLE} in the {@code flags} argument to allow
5174      * the user to select the key from a dialog.
5175      *
5176      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
5177      * have been given to access the key and certificates associated with this alias will be
5178      * revoked.
5179      *
5180      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5181      *        {@code null} if calling from a delegated certificate installer.
5182      * @param privKey The private key to install.
5183      * @param certs The certificate chain to install. The chain should start with the leaf
5184      *        certificate and include the chain of trust in order. This will be returned by
5185      *        {@link android.security.KeyChain#getCertificateChain}.
5186      * @param alias The private key alias under which to install the certificate. If a certificate
5187      *        with that alias already exists, it will be overwritten.
5188      * @param flags Flags to request that the calling app be granted access to the credentials
5189      *        and set the key to be user-selectable. See {@link #INSTALLKEY_SET_USER_SELECTABLE} and
5190      *        {@link #INSTALLKEY_REQUEST_CREDENTIALS_ACCESS}.
5191      * @return {@code true} if the keys were installed, {@code false} otherwise.
5192      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5193      *         owner.
5194      * @see android.security.KeyChain#getCertificateChain
5195      * @see #setDelegatedScopes
5196      * @see #DELEGATION_CERT_INSTALL
5197      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, int flags)5198     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
5199             @NonNull Certificate[] certs, @NonNull String alias, int flags) {
5200         throwIfParentInstance("installKeyPair");
5201         boolean requestAccess = (flags & INSTALLKEY_REQUEST_CREDENTIALS_ACCESS)
5202                 == INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
5203         boolean isUserSelectable = (flags & INSTALLKEY_SET_USER_SELECTABLE)
5204                 == INSTALLKEY_SET_USER_SELECTABLE;
5205         try {
5206             final byte[] pemCert = Credentials.convertToPem(certs[0]);
5207             byte[] pemChain = null;
5208             if (certs.length > 1) {
5209                 pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length));
5210             }
5211             final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
5212                     .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
5213             return mService.installKeyPair(admin, mContext.getPackageName(), pkcs8Key, pemCert,
5214                     pemChain, alias, requestAccess, isUserSelectable);
5215         } catch (RemoteException e) {
5216             throw e.rethrowFromSystemServer();
5217         } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
5218             Log.w(TAG, "Failed to obtain private key material", e);
5219         } catch (CertificateException | IOException e) {
5220             Log.w(TAG, "Could not pem-encode certificate", e);
5221         }
5222         return false;
5223     }
5224 
5225     /**
5226      * Called by a device or profile owner, or delegated certificate installer, to remove a
5227      * certificate and private key pair installed under a given alias.
5228      *
5229      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5230      *        {@code null} if calling from a delegated certificate installer.
5231      * @param alias The private key alias under which the certificate is installed.
5232      * @return {@code true} if the private key alias no longer exists, {@code false} otherwise.
5233      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5234      *         owner.
5235      * @see #setDelegatedScopes
5236      * @see #DELEGATION_CERT_INSTALL
5237      */
removeKeyPair(@ullable ComponentName admin, @NonNull String alias)5238     public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
5239         throwIfParentInstance("removeKeyPair");
5240         try {
5241             return mService.removeKeyPair(admin, mContext.getPackageName(), alias);
5242         } catch (RemoteException e) {
5243             throw e.rethrowFromSystemServer();
5244         }
5245     }
5246 
5247     /**
5248      * Called by a device or profile owner, or delegated certificate installer, to generate a
5249      * new private/public key pair. If the device supports key generation via secure hardware,
5250      * this method is useful for creating a key in KeyChain that never left the secure hardware.
5251      * Access to the key is controlled the same way as in {@link #installKeyPair}.
5252      *
5253      * <p>Because this method might take several seconds to complete, it should only be called from
5254      * a worker thread. This method returns {@code null} when called from the main thread.
5255      *
5256      * <p>This method is not thread-safe, calling it from multiple threads at the same time will
5257      * result in undefined behavior. If the calling thread is interrupted while the invocation is
5258      * in-flight, it will eventually terminate and return {@code null}.
5259      *
5260      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
5261      * have been given to access the key and certificates associated with this alias will be
5262      * revoked.
5263      *
5264      * <p>Attestation: to enable attestation, set an attestation challenge in {@code keySpec} via
5265      * {@link KeyGenParameterSpec.Builder#setAttestationChallenge}. By specifying flags to the
5266      * {@code idAttestationFlags} parameter, it is possible to request the device's unique
5267      * identity to be included in the attestation record.
5268      *
5269      * <p>Specific identifiers can be included in the attestation record, and an individual
5270      * attestation certificate can be used to sign the attestation record. To find out if the device
5271      * supports these features, refer to {@link #isDeviceIdAttestationSupported()} and
5272      * {@link #isUniqueDeviceAttestationSupported()}.
5273      *
5274      * <p>Device owner, profile owner and their delegated certificate installer can use
5275      * {@link #ID_TYPE_BASE_INFO} to request inclusion of the general device information
5276      * including manufacturer, model, brand, device and product in the attestation record.
5277      * Only device owner, profile owner on an organization-owned device and their delegated
5278      * certificate installers can use {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and
5279      * {@link #ID_TYPE_MEID} to request unique device identifiers to be attested (the serial number,
5280      * IMEI and MEID correspondingly), if supported by the device
5281      * (see {@link #isDeviceIdAttestationSupported()}).
5282      * Additionally, device owner, profile owner on an organization-owned device and their delegated
5283      * certificate installers can also request the attestation record to be signed using an
5284      * individual attestation certificate by specifying the {@link #ID_TYPE_INDIVIDUAL_ATTESTATION}
5285      * flag (if supported by the device, see {@link #isUniqueDeviceAttestationSupported()}).
5286      * <p>
5287      * If any of {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID}
5288      * is set, it is implicitly assumed that {@link #ID_TYPE_BASE_INFO} is also set.
5289      * <p>
5290      * Attestation using {@link #ID_TYPE_INDIVIDUAL_ATTESTATION} can only be requested if
5291      * key generation is done in StrongBox.
5292      *
5293      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5294      *            {@code null} if calling from a delegated certificate installer.
5295      * @param algorithm The key generation algorithm, see {@link java.security.KeyPairGenerator}.
5296      * @param keySpec Specification of the key to generate, see
5297      * {@link java.security.KeyPairGenerator}.
5298      * @param idAttestationFlags A bitmask of the identifiers that should be included in the
5299      *        attestation record ({@code ID_TYPE_BASE_INFO}, {@code ID_TYPE_SERIAL},
5300      *        {@code ID_TYPE_IMEI} and {@code ID_TYPE_MEID}), and
5301      *        {@code ID_TYPE_INDIVIDUAL_ATTESTATION} if the attestation record should be signed
5302      *        using an individual attestation certificate.
5303      *        <p>
5304      *        {@code 0} should be passed in if no device identification is required in the
5305      *        attestation record and the batch attestation certificate should be used.
5306      *        <p>
5307      *        If any flag is specified, then an attestation challenge must be included in the
5308      *        {@code keySpec}.
5309      * @return A non-null {@code AttestedKeyPair} if the key generation succeeded, null otherwise.
5310      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5311      *         owner. If Device ID attestation is requested (using {@link #ID_TYPE_SERIAL},
5312      *         {@link #ID_TYPE_IMEI} or {@link #ID_TYPE_MEID}), the caller must be the Device Owner
5313      *         or the Certificate Installer delegate.
5314      * @throws IllegalArgumentException in the following cases:
5315      *         <p>
5316      *         <ul>
5317      *         <li>The alias in {@code keySpec} is empty.</li>
5318      *         <li>The algorithm specification in {@code keySpec} is not
5319      *         {@code RSAKeyGenParameterSpec} or {@code ECGenParameterSpec}.</li>
5320      *         <li>Device ID attestation was requested but the {@code keySpec} does not contain an
5321      *         attestation challenge.</li>
5322      *         </ul>
5323      * @throws UnsupportedOperationException if Device ID attestation or individual attestation
5324      *         was requested but the underlying hardware does not support it.
5325      * @throws StrongBoxUnavailableException if the use of StrongBox for key generation was
5326      *         specified in {@code keySpec} but the device does not have one.
5327      * @see KeyGenParameterSpec.Builder#setAttestationChallenge(byte[])
5328      */
generateKeyPair(@ullable ComponentName admin, @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec, @AttestationIdType int idAttestationFlags)5329     public AttestedKeyPair generateKeyPair(@Nullable ComponentName admin,
5330             @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec,
5331             @AttestationIdType int idAttestationFlags) {
5332         throwIfParentInstance("generateKeyPair");
5333         try {
5334             final ParcelableKeyGenParameterSpec parcelableSpec =
5335                     new ParcelableKeyGenParameterSpec(keySpec);
5336             KeymasterCertificateChain attestationChain = new KeymasterCertificateChain();
5337 
5338             // Translate ID attestation flags to values used by AttestationUtils
5339             final boolean success = mService.generateKeyPair(
5340                     admin, mContext.getPackageName(), algorithm, parcelableSpec,
5341                     idAttestationFlags, attestationChain);
5342             if (!success) {
5343                 Log.e(TAG, "Error generating key via DevicePolicyManagerService.");
5344                 return null;
5345             }
5346 
5347             final String alias = keySpec.getKeystoreAlias();
5348             final KeyPair keyPair = KeyChain.getKeyPair(mContext, alias);
5349             Certificate[] outputChain = null;
5350             try {
5351                 if (AttestationUtils.isChainValid(attestationChain)) {
5352                     outputChain = AttestationUtils.parseCertificateChain(attestationChain);
5353                 }
5354             } catch (KeyAttestationException e) {
5355                 Log.e(TAG, "Error parsing attestation chain for alias " + alias, e);
5356                 mService.removeKeyPair(admin, mContext.getPackageName(), alias);
5357                 return null;
5358             }
5359             return new AttestedKeyPair(keyPair, outputChain);
5360         } catch (RemoteException e) {
5361             throw e.rethrowFromSystemServer();
5362         } catch (KeyChainException e) {
5363             Log.w(TAG, "Failed to generate key", e);
5364         } catch (InterruptedException e) {
5365             Log.w(TAG, "Interrupted while generating key", e);
5366             Thread.currentThread().interrupt();
5367         } catch (ServiceSpecificException e) {
5368             Log.w(TAG, String.format("Key Generation failure: %d", e.errorCode));
5369             switch (e.errorCode) {
5370                 case KEY_GEN_STRONGBOX_UNAVAILABLE:
5371                     throw new StrongBoxUnavailableException("No StrongBox for key generation.");
5372                 default:
5373                     throw new RuntimeException(
5374                             String.format("Unknown error while generating key: %d", e.errorCode));
5375             }
5376         }
5377         return null;
5378     }
5379 
5380 
5381     /**
5382      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
5383      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to grant an application access
5384      * to an already-installed (or generated) KeyChain key.
5385      * This is useful (in combination with {@link #installKeyPair} or {@link #generateKeyPair}) to
5386      * let an application call {@link android.security.KeyChain#getPrivateKey} without having to
5387      * call {@link android.security.KeyChain#choosePrivateKeyAlias} first.
5388      *
5389      * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED}
5390      * broadcast when access to a key is granted.
5391      *
5392      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5393      *        {@code null} if calling from a delegated certificate installer.
5394      * @param alias The alias of the key to grant access to.
5395      * @param packageName The name of the (already installed) package to grant access to.
5396      * @return {@code true} if the grant was set successfully, {@code false} otherwise.
5397      *
5398      * @throws SecurityException if the caller is not a device owner, a profile owner or
5399      *         delegated certificate chooser.
5400      * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if
5401      *         {@code packageName} is not a name of an installed package.
5402      * @see #revokeKeyPairFromApp
5403      */
grantKeyPairToApp(@ullable ComponentName admin, @NonNull String alias, @NonNull String packageName)5404     public boolean grantKeyPairToApp(@Nullable ComponentName admin, @NonNull String alias,
5405             @NonNull String packageName) {
5406         throwIfParentInstance("grantKeyPairToApp");
5407         try {
5408             return mService.setKeyGrantForApp(
5409                     admin, mContext.getPackageName(), alias, packageName, true);
5410         } catch (RemoteException e) {
5411             e.rethrowFromSystemServer();
5412         }
5413         return false;
5414     }
5415 
5416     /**
5417      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
5418      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to revoke an application's
5419      * grant to a KeyChain key pair.
5420      * Calls by the application to {@link android.security.KeyChain#getPrivateKey}
5421      * will fail after the grant is revoked.
5422      *
5423      * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED}
5424      * broadcast when access to a key is revoked.
5425      *
5426      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5427      *        {@code null} if calling from a delegated certificate installer.
5428      * @param alias The alias of the key to revoke access from.
5429      * @param packageName The name of the (already installed) package to revoke access from.
5430      * @return {@code true} if the grant was revoked successfully, {@code false} otherwise.
5431      *
5432      * @throws SecurityException if the caller is not a device owner, a profile owner or
5433      *         delegated certificate chooser.
5434      * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if
5435      *         {@code packageName} is not a name of an installed package.
5436      * @see #grantKeyPairToApp
5437      */
revokeKeyPairFromApp(@ullable ComponentName admin, @NonNull String alias, @NonNull String packageName)5438     public boolean revokeKeyPairFromApp(@Nullable ComponentName admin, @NonNull String alias,
5439             @NonNull String packageName) {
5440         throwIfParentInstance("revokeKeyPairFromApp");
5441         try {
5442             return mService.setKeyGrantForApp(
5443                     admin, mContext.getPackageName(), alias, packageName, false);
5444         } catch (RemoteException e) {
5445             e.rethrowFromSystemServer();
5446         }
5447         return false;
5448     }
5449 
5450     /**
5451      * Returns {@code true} if the device supports attestation of device identifiers in addition
5452      * to key attestation. See
5453      * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}
5454      * @return {@code true} if Device ID attestation is supported.
5455      */
isDeviceIdAttestationSupported()5456     public boolean isDeviceIdAttestationSupported() {
5457         PackageManager pm = mContext.getPackageManager();
5458         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ID_ATTESTATION);
5459     }
5460 
5461     /**
5462      * Returns {@code true} if the StrongBox Keymaster implementation on the device was provisioned
5463      * with an individual attestation certificate and can sign attestation records using it (as
5464      * attestation using an individual attestation certificate is a feature only Keymaster
5465      * implementations with StrongBox security level can implement).
5466      * For use prior to calling
5467      * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}.
5468      * @return {@code true} if individual attestation is supported.
5469      */
isUniqueDeviceAttestationSupported()5470     public boolean isUniqueDeviceAttestationSupported() {
5471         PackageManager pm = mContext.getPackageManager();
5472         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_UNIQUE_ATTESTATION);
5473     }
5474 
5475     /**
5476      * Called by a device or profile owner, or delegated certificate installer, to associate
5477      * certificates with a key pair that was generated using {@link #generateKeyPair}, and
5478      * set whether the key is available for the user to choose in the certificate selection
5479      * prompt.
5480      *
5481      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5482      *            {@code null} if calling from a delegated certificate installer.
5483      * @param alias The private key alias under which to install the certificate. The {@code alias}
5484      *        should denote an existing private key. If a certificate with that alias already
5485      *        exists, it will be overwritten.
5486      * @param certs The certificate chain to install. The chain should start with the leaf
5487      *        certificate and include the chain of trust in order. This will be returned by
5488      *        {@link android.security.KeyChain#getCertificateChain}.
5489      * @param isUserSelectable {@code true} to indicate that a user can select this key via the
5490      *        certificate selection prompt, {@code false} to indicate that this key can only be
5491      *        granted access by implementing
5492      *        {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
5493      * @return {@code true} if the provided {@code alias} exists and the certificates has been
5494      *        successfully associated with it, {@code false} otherwise.
5495      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5496      *         owner, or {@code admin} is null but the calling application is not a delegated
5497      *         certificate installer.
5498      */
setKeyPairCertificate(@ullable ComponentName admin, @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable)5499     public boolean setKeyPairCertificate(@Nullable ComponentName admin,
5500             @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable) {
5501         throwIfParentInstance("setKeyPairCertificate");
5502         try {
5503             final byte[] pemCert = Credentials.convertToPem(certs.get(0));
5504             byte[] pemChain = null;
5505             if (certs.size() > 1) {
5506                 pemChain = Credentials.convertToPem(
5507                         certs.subList(1, certs.size()).toArray(new Certificate[0]));
5508             }
5509             return mService.setKeyPairCertificate(admin, mContext.getPackageName(), alias, pemCert,
5510                     pemChain, isUserSelectable);
5511         } catch (RemoteException e) {
5512             throw e.rethrowFromSystemServer();
5513         } catch (CertificateException | IOException e) {
5514             Log.w(TAG, "Could not pem-encode certificate", e);
5515         }
5516         return false;
5517     }
5518 
5519 
5520     /**
5521      * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
5522      * doesn't exist.
5523      */
getCaCertAlias(byte[] certBuffer)5524     private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
5525         final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
5526         final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
5527                               new ByteArrayInputStream(certBuffer));
5528         return new TrustedCertificateStore().getCertificateAlias(cert);
5529     }
5530 
5531     /**
5532      * Called by a profile owner or device owner to grant access to privileged certificate
5533      * manipulation APIs to a third-party certificate installer app. Granted APIs include
5534      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
5535      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
5536      * <p>
5537      * Delegated certificate installer is a per-user state. The delegated access is persistent until
5538      * it is later cleared by calling this method with a null value or uninstallling the certificate
5539      * installer.
5540      * <p>
5541      * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
5542      * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
5543      * supplied certificate installer package must be installed when calling this API, otherwise an
5544      * {@link IllegalArgumentException} will be thrown.
5545      *
5546      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5547      * @param installerPackage The package name of the certificate installer which will be given
5548      *            access. If {@code null} is given the current package will be cleared.
5549      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5550      *
5551      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
5552      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
5553      */
5554     @Deprecated
setCertInstallerPackage(@onNull ComponentName admin, @Nullable String installerPackage)5555     public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
5556             installerPackage) throws SecurityException {
5557         throwIfParentInstance("setCertInstallerPackage");
5558         if (mService != null) {
5559             try {
5560                 mService.setCertInstallerPackage(admin, installerPackage);
5561             } catch (RemoteException e) {
5562                 throw e.rethrowFromSystemServer();
5563             }
5564         }
5565     }
5566 
5567     /**
5568      * Called by a profile owner or device owner to retrieve the certificate installer for the user,
5569      * or {@code null} if none is set. If there are multiple delegates this function will return one
5570      * of them.
5571      *
5572      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5573      * @return The package name of the current delegated certificate installer, or {@code null} if
5574      *         none is set.
5575      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5576      *
5577      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
5578      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
5579      */
5580     @Deprecated
getCertInstallerPackage(@onNull ComponentName admin)5581     public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
5582             throws SecurityException {
5583         throwIfParentInstance("getCertInstallerPackage");
5584         if (mService != null) {
5585             try {
5586                 return mService.getCertInstallerPackage(admin);
5587             } catch (RemoteException e) {
5588                 throw e.rethrowFromSystemServer();
5589             }
5590         }
5591         return null;
5592     }
5593 
5594     /**
5595      * Called by a profile owner or device owner to grant access to privileged APIs to another app.
5596      * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*}
5597      * constants.
5598      * <p>
5599      * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be
5600      * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra
5601      * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the
5602      * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag.
5603      * <p>
5604      * Delegated scopes are a per-user state. The delegated access is persistent until it is later
5605      * cleared by calling this method with an empty {@code scopes} list or uninstalling the
5606      * {@code delegatePackage}.
5607      *
5608      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5609      * @param delegatePackage The package name of the app which will be given access.
5610      * @param scopes The groups of privileged APIs whose access should be granted to
5611      *            {@code delegatedPackage}.
5612      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5613      */
setDelegatedScopes(@onNull ComponentName admin, @NonNull String delegatePackage, @NonNull List<String> scopes)5614      public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage,
5615             @NonNull List<String> scopes) {
5616         throwIfParentInstance("setDelegatedScopes");
5617         if (mService != null) {
5618             try {
5619                 mService.setDelegatedScopes(admin, delegatePackage, scopes);
5620             } catch (RemoteException e) {
5621                 throw e.rethrowFromSystemServer();
5622             }
5623         }
5624     }
5625 
5626     /**
5627      * Called by a profile owner or device owner to retrieve a list of the scopes given to a
5628      * delegate package. Other apps can use this method to retrieve their own delegated scopes by
5629      * passing {@code null} for {@code admin} and their own package name as
5630      * {@code delegatedPackage}.
5631      *
5632      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5633      *            {@code null} if the caller is {@code delegatedPackage}.
5634      * @param delegatedPackage The package name of the app whose scopes should be retrieved.
5635      * @return A list containing the scopes given to {@code delegatedPackage}.
5636      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5637      */
5638      @NonNull
getDelegatedScopes(@ullable ComponentName admin, @NonNull String delegatedPackage)5639      public List<String> getDelegatedScopes(@Nullable ComponentName admin,
5640              @NonNull String delegatedPackage) {
5641          throwIfParentInstance("getDelegatedScopes");
5642          if (mService != null) {
5643              try {
5644                  return mService.getDelegatedScopes(admin, delegatedPackage);
5645              } catch (RemoteException e) {
5646                  throw e.rethrowFromSystemServer();
5647              }
5648          }
5649          return null;
5650     }
5651 
5652     /**
5653      * Called by a profile owner or device owner to retrieve a list of delegate packages that were
5654      * granted a delegation scope.
5655      *
5656      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5657      * @param delegationScope The scope whose delegates should be retrieved.
5658      * @return A list of package names of the current delegated packages for
5659                {@code delegationScope}.
5660      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5661      */
5662      @Nullable
getDelegatePackages(@onNull ComponentName admin, @NonNull String delegationScope)5663      public List<String> getDelegatePackages(@NonNull ComponentName admin,
5664              @NonNull String delegationScope) {
5665         throwIfParentInstance("getDelegatePackages");
5666         if (mService != null) {
5667             try {
5668                 return mService.getDelegatePackages(admin, delegationScope);
5669             } catch (RemoteException e) {
5670                 throw e.rethrowFromSystemServer();
5671             }
5672         }
5673         return null;
5674     }
5675 
5676     /**
5677      * Service-specific error code used in implementation of {@code setAlwaysOnVpnPackage} methods.
5678      * @hide
5679      */
5680     public static final int ERROR_VPN_PACKAGE_NOT_FOUND = 1;
5681 
5682     /**
5683      * Called by a device or profile owner to configure an always-on VPN connection through a
5684      * specific application for the current user. This connection is automatically granted and
5685      * persisted after a reboot.
5686      * <p> To support the always-on feature, an app must
5687      * <ul>
5688      *     <li>declare a {@link android.net.VpnService} in its manifest, guarded by
5689      *         {@link android.Manifest.permission#BIND_VPN_SERVICE};</li>
5690      *     <li>target {@link android.os.Build.VERSION_CODES#N API 24} or above; and</li>
5691      *     <li><i>not</i> explicitly opt out of the feature through
5692      *         {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}.</li>
5693      * </ul>
5694      * The call will fail if called with the package name of an unsupported VPN app.
5695      * <p> Enabling lockdown via {@code lockdownEnabled} argument carries the risk that any failure
5696      * of the VPN provider could break networking for all apps. This method clears any lockdown
5697      * whitelist set by {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)}.
5698      *
5699      * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
5700      *        remove an existing always-on VPN configuration.
5701      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
5702      *        {@code false} otherwise. This has no effect when clearing.
5703      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5704      * @throws NameNotFoundException if {@code vpnPackage} is not installed.
5705      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
5706      *         set as always-on, or if always-on VPN is not available.
5707      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
5708      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled)5709     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
5710             boolean lockdownEnabled) throws NameNotFoundException {
5711         setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled, Collections.emptySet());
5712     }
5713 
5714     /**
5715      * A version of {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} that allows the
5716      * admin to specify a set of apps that should be able to access the network directly when VPN
5717      * is not connected. When VPN connects these apps switch over to VPN if allowed to use that VPN.
5718      * System apps can always bypass VPN.
5719      * <p> Note that the system doesn't update the whitelist when packages are installed or
5720      * uninstalled, the admin app must call this method to keep the list up to date.
5721      * <p> When {@code lockdownEnabled} is false {@code lockdownWhitelist} is ignored . When
5722      * {@code lockdownEnabled} is {@code true} and {@code lockdownWhitelist} is {@code null} or
5723      * empty, only system apps can bypass VPN.
5724      * <p> Setting always-on VPN package to {@code null} or using
5725      * {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} clears lockdown whitelist.
5726      *
5727      * @param vpnPackage package name for an installed VPN app on the device, or {@code null}
5728      *         to remove an existing always-on VPN configuration
5729      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
5730      *         {@code false} otherwise. This has no effect when clearing.
5731      * @param lockdownWhitelist Packages that will be able to access the network directly when VPN
5732      *         is in lockdown mode but not connected. Has no effect when clearing.
5733      * @throws SecurityException if {@code admin} is not a device or a profile
5734      *         owner.
5735      * @throws NameNotFoundException if {@code vpnPackage} or one of
5736      *         {@code lockdownWhitelist} is not installed.
5737      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does
5738      *         not support being set as always-on, or if always-on VPN is not
5739      *         available.
5740      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled, @Nullable Set<String> lockdownWhitelist)5741     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
5742             boolean lockdownEnabled, @Nullable Set<String> lockdownWhitelist)
5743             throws NameNotFoundException {
5744         throwIfParentInstance("setAlwaysOnVpnPackage");
5745         if (mService != null) {
5746             try {
5747                 mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled,
5748                         lockdownWhitelist == null ? null : new ArrayList<>(lockdownWhitelist));
5749             } catch (ServiceSpecificException e) {
5750                 switch (e.errorCode) {
5751                     case ERROR_VPN_PACKAGE_NOT_FOUND:
5752                         throw new NameNotFoundException(e.getMessage());
5753                     default:
5754                         throw new RuntimeException(
5755                                 "Unknown error setting always-on VPN: " + e.errorCode, e);
5756                 }
5757             } catch (RemoteException e) {
5758                 throw e.rethrowFromSystemServer();
5759             }
5760         }
5761     }
5762 
5763     /**
5764      * Called by device or profile owner to query whether current always-on VPN is configured in
5765      * lockdown mode. Returns {@code false} when no always-on configuration is set.
5766      *
5767      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5768      *
5769      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5770      *
5771      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean)
5772      */
isAlwaysOnVpnLockdownEnabled(@onNull ComponentName admin)5773     public boolean isAlwaysOnVpnLockdownEnabled(@NonNull ComponentName admin) {
5774         throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
5775         if (mService != null) {
5776             try {
5777                 // Starting from Android R, the caller can pass the permission check in
5778                 // DevicePolicyManagerService if it holds android.permission.MAINLINE_NETWORK_STACK.
5779                 // Note that the android.permission.MAINLINE_NETWORK_STACK is a signature permission
5780                 // which is used by the NetworkStack mainline module.
5781                 return mService.isAlwaysOnVpnLockdownEnabled(admin);
5782             } catch (RemoteException e) {
5783                 throw e.rethrowFromSystemServer();
5784             }
5785         }
5786         return false;
5787     }
5788 
5789     /**
5790      * Returns whether the admin has enabled always-on VPN lockdown for the current user.
5791      *
5792      * Only callable by the system.
5793     * @hide
5794     */
5795     @UserHandleAware
isAlwaysOnVpnLockdownEnabled()5796     public boolean isAlwaysOnVpnLockdownEnabled() {
5797         throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
5798         if (mService != null) {
5799             try {
5800                 return mService.isAlwaysOnVpnLockdownEnabledForUser(myUserId());
5801             } catch (RemoteException e) {
5802                 throw e.rethrowFromSystemServer();
5803             }
5804         }
5805         return false;
5806     }
5807 
5808     /**
5809      * Called by device or profile owner to query the set of packages that are allowed to access
5810      * the network directly when always-on VPN is in lockdown mode but not connected. Returns
5811      * {@code null} when always-on VPN is not active or not in lockdown mode.
5812      *
5813      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5814      *
5815      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5816      *
5817      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
5818      */
getAlwaysOnVpnLockdownWhitelist(@onNull ComponentName admin)5819     public @Nullable Set<String> getAlwaysOnVpnLockdownWhitelist(@NonNull ComponentName admin) {
5820         throwIfParentInstance("getAlwaysOnVpnLockdownWhitelist");
5821         if (mService != null) {
5822             try {
5823                 final List<String> whitelist =
5824                         mService.getAlwaysOnVpnLockdownWhitelist(admin);
5825                 return whitelist == null ? null : new HashSet<>(whitelist);
5826             } catch (RemoteException e) {
5827                 throw e.rethrowFromSystemServer();
5828             }
5829         }
5830         return null;
5831     }
5832 
5833     /**
5834      * Called by a device or profile owner to read the name of the package administering an
5835      * always-on VPN connection for the current user. If there is no such package, or the always-on
5836      * VPN is provided by the system instead of by an application, {@code null} will be returned.
5837      *
5838      * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
5839      *         is set.
5840      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5841      */
getAlwaysOnVpnPackage(@onNull ComponentName admin)5842     public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
5843         throwIfParentInstance("getAlwaysOnVpnPackage");
5844         if (mService != null) {
5845             try {
5846                 return mService.getAlwaysOnVpnPackage(admin);
5847             } catch (RemoteException e) {
5848                 throw e.rethrowFromSystemServer();
5849             }
5850         }
5851         return null;
5852     }
5853 
5854     /**
5855      * Returns the VPN package name if the admin has enabled always-on VPN on the current user,
5856      * or {@code null} if none is set.
5857      *
5858      * Only callable by the system.
5859      * @hide
5860      */
5861     @UserHandleAware
getAlwaysOnVpnPackage()5862     public @Nullable String getAlwaysOnVpnPackage() {
5863         throwIfParentInstance("getAlwaysOnVpnPackage");
5864         if (mService != null) {
5865             try {
5866                 return mService.getAlwaysOnVpnPackageForUser(myUserId());
5867             } catch (RemoteException e) {
5868                 throw e.rethrowFromSystemServer();
5869             }
5870         }
5871         return null;
5872     }
5873 
5874     /**
5875      * Called by an application that is administering the device to disable all cameras on the
5876      * device, for this user. After setting this, no applications running as this user will be able
5877      * to access any cameras on the device.
5878      * <p>
5879      * This method can be called on the {@link DevicePolicyManager} instance,
5880      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
5881      * the profile owner of an organization-owned managed profile.
5882      * <p>
5883      * If the caller is device owner, then the restriction will be applied to all users. If
5884      * called on the parent instance, then the restriction will be applied on the personal profile.
5885      * <p>
5886      * The calling device admin must have requested
5887      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
5888      * not, a security exception will be thrown.
5889      * <p>
5890      * <b>Note</b>, this policy type is deprecated for legacy device admins since
5891      * {@link android.os.Build.VERSION_CODES#Q}. On Android
5892      * {@link android.os.Build.VERSION_CODES#Q} devices, legacy device admins targeting SDK
5893      * version {@link android.os.Build.VERSION_CODES#P} or below can still call this API to
5894      * disable camera, while legacy device admins targeting SDK version
5895      * {@link android.os.Build.VERSION_CODES#Q} will receive a SecurityException. Starting
5896      * from Android {@link android.os.Build.VERSION_CODES#R}, requests to disable camera from
5897      * legacy device admins targeting SDK version {@link android.os.Build.VERSION_CODES#P} or
5898      * below will be silently ignored.
5899      *
5900      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5901      * @param disabled Whether or not the camera should be disabled.
5902      * @throws SecurityException if {@code admin} is not an active administrator or does not use
5903      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
5904      */
setCameraDisabled(@onNull ComponentName admin, boolean disabled)5905     public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
5906         if (mService != null) {
5907             try {
5908                 mService.setCameraDisabled(admin, disabled, mParentInstance);
5909             } catch (RemoteException e) {
5910                 throw e.rethrowFromSystemServer();
5911             }
5912         }
5913     }
5914 
5915     /**
5916      * Determine whether or not the device's cameras have been disabled for this user,
5917      * either by the calling admin, if specified, or all admins.
5918      * <p>
5919      * This method can be called on the {@link DevicePolicyManager} instance,
5920      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
5921      * the profile owner of an organization-owned managed profile.
5922      *
5923      * @param admin The name of the admin component to check, or {@code null} to check whether any admins
5924      * have disabled the camera
5925      */
getCameraDisabled(@ullable ComponentName admin)5926     public boolean getCameraDisabled(@Nullable ComponentName admin) {
5927         return getCameraDisabled(admin, myUserId());
5928     }
5929 
5930     /** @hide per-user version */
5931     @UnsupportedAppUsage
getCameraDisabled(@ullable ComponentName admin, int userHandle)5932     public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
5933         if (mService != null) {
5934             try {
5935                 return mService.getCameraDisabled(admin, userHandle, mParentInstance);
5936             } catch (RemoteException e) {
5937                 throw e.rethrowFromSystemServer();
5938             }
5939         }
5940         return false;
5941     }
5942 
5943     /**
5944      * Called by a device owner to request a bugreport.
5945      * <p>
5946      * If the device contains secondary users or profiles, they must be affiliated with the device.
5947      * Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
5948      *
5949      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5950      * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
5951      *         wasn't triggered because a previous bugreport operation is still active (either the
5952      *         bugreport is still running or waiting for the user to share or decline)
5953      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
5954      *         profile or secondary user that is not affiliated with the device.
5955      * @see #isAffiliatedUser
5956      */
requestBugreport(@onNull ComponentName admin)5957     public boolean requestBugreport(@NonNull ComponentName admin) {
5958         throwIfParentInstance("requestBugreport");
5959         if (mService != null) {
5960             try {
5961                 return mService.requestBugreport(admin);
5962             } catch (RemoteException e) {
5963                 throw e.rethrowFromSystemServer();
5964             }
5965         }
5966         return false;
5967     }
5968 
5969     /**
5970      * Determine whether or not creating a guest user has been disabled for the device
5971      *
5972      * @hide
5973      */
getGuestUserDisabled(@ullable ComponentName admin)5974     public boolean getGuestUserDisabled(@Nullable ComponentName admin) {
5975         // Currently guest users can always be created if multi-user is enabled
5976         // TODO introduce a policy for guest user creation
5977         return false;
5978     }
5979 
5980     /**
5981      * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
5982      * screen capture also prevents the content from being shown on display devices that do not have
5983      * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
5984      * secure surfaces and secure displays.
5985      * <p>
5986      * This method can be called on the {@link DevicePolicyManager} instance, returned by
5987      * {@link #getParentProfileInstance(ComponentName)}, where the calling device admin must be
5988      * the profile owner of an organization-owned managed profile. If it is not, a security
5989      * exception will be thrown.
5990      * <p>
5991      * If the caller is device owner or called on the parent instance by a profile owner of an
5992      * organization-owned managed profile, then the restriction will be applied to all users.
5993      * <p>
5994      * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
5995      * assist requests for all activities of the relevant user.
5996      *
5997      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5998      * @param disabled Whether screen capture is disabled or not.
5999      * @throws SecurityException if {@code admin} is not a device or profile owner or if
6000      *                           called on the parent profile and the {@code admin} is not a
6001      *                           profile owner of an organization-owned managed profile.
6002      */
setScreenCaptureDisabled(@onNull ComponentName admin, boolean disabled)6003     public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
6004         if (mService != null) {
6005             try {
6006                 mService.setScreenCaptureDisabled(admin, disabled, mParentInstance);
6007             } catch (RemoteException e) {
6008                 throw e.rethrowFromSystemServer();
6009             }
6010         }
6011     }
6012 
6013     /**
6014      * Determine whether or not screen capture has been disabled by the calling
6015      * admin, if specified, or all admins.
6016      * <p>
6017      * This method can be called on the {@link DevicePolicyManager} instance,
6018      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
6019      * the profile owner of an organization-owned managed profile (the calling admin must be
6020      * specified).
6021      *
6022      * @param admin The name of the admin component to check, or {@code null} to check whether any
6023      *              admins have disabled screen capture.
6024      */
getScreenCaptureDisabled(@ullable ComponentName admin)6025     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
6026         return getScreenCaptureDisabled(admin, myUserId());
6027     }
6028 
6029     /** @hide per-user version */
getScreenCaptureDisabled(@ullable ComponentName admin, int userHandle)6030     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
6031         if (mService != null) {
6032             try {
6033                 return mService.getScreenCaptureDisabled(admin, userHandle, mParentInstance);
6034             } catch (RemoteException e) {
6035                 throw e.rethrowFromSystemServer();
6036             }
6037         }
6038         return false;
6039     }
6040 
6041     /**
6042      * Called by a device owner, or alternatively a profile owner from Android 8.0 (API level 26) or
6043      * higher, to set whether auto time is required. If auto time is required, no user will be able
6044      * set the date and time and network date and time will be used.
6045      * <p>
6046      * Note: if auto time is required the user can still manually set the time zone.
6047      * <p>
6048      * The calling device admin must be a device owner, or alternatively a profile owner from
6049      * Android 8.0 (API level 26) or higher. If it is not, a security exception will be thrown.
6050      * <p>
6051      * Staring from Android 11, this API switches to use
6052      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} to enforce the auto time settings. Calling
6053      * this API to enforce auto time will result in
6054      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being set, while calling this API to lift
6055      * the requirement will result in {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being cleared.
6056      * From Android 11, this API can also no longer be called on a managed profile.
6057      *
6058      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6059      * @param required Whether auto time is set required or not.
6060      * @throws SecurityException if {@code admin} is not a device owner, not a profile owner or
6061      * if this API is called on a managed profile.
6062      * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #setAutoTimeEnabled}
6063      * to turn auto time on or off and use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
6064      * to prevent the user from changing this setting.
6065      */
6066     @Deprecated
setAutoTimeRequired(@onNull ComponentName admin, boolean required)6067     public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
6068         throwIfParentInstance("setAutoTimeRequired");
6069         if (mService != null) {
6070             try {
6071                 mService.setAutoTimeRequired(admin, required);
6072             } catch (RemoteException e) {
6073                 throw e.rethrowFromSystemServer();
6074             }
6075         }
6076     }
6077 
6078     /**
6079      * @return true if auto time is required.
6080      * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #getAutoTimeEnabled}
6081      */
6082     @Deprecated
getAutoTimeRequired()6083     public boolean getAutoTimeRequired() {
6084         throwIfParentInstance("getAutoTimeRequired");
6085         if (mService != null) {
6086             try {
6087                 return mService.getAutoTimeRequired();
6088             } catch (RemoteException e) {
6089                 throw e.rethrowFromSystemServer();
6090             }
6091         }
6092         return false;
6093     }
6094 
6095     /**
6096      * Called by a device owner, a profile owner for the primary user or a profile
6097      * owner of an organization-owned managed profile to turn auto time on and off.
6098      * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
6099      * to prevent the user from changing this setting.
6100      * <p>
6101      * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
6102      * no user will be able set the date and time. Instead, the network date
6103      * and time will be used.
6104      *
6105      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6106      * @param enabled Whether time should be obtained automatically from the network or not.
6107      * @throws SecurityException if caller is not a device owner, a profile owner for the
6108      * primary user, or a profile owner of an organization-owned managed profile.
6109      */
setAutoTimeEnabled(@onNull ComponentName admin, boolean enabled)6110     public void setAutoTimeEnabled(@NonNull ComponentName admin, boolean enabled) {
6111         if (mService != null) {
6112             try {
6113                 mService.setAutoTimeEnabled(admin, enabled);
6114             } catch (RemoteException e) {
6115                 throw e.rethrowFromSystemServer();
6116             }
6117         }
6118     }
6119 
6120     /**
6121      * @return true if auto time is enabled on the device.
6122      * @throws SecurityException if caller is not a device owner, a profile owner for the
6123      * primary user, or a profile owner of an organization-owned managed profile.
6124      */
getAutoTimeEnabled(@onNull ComponentName admin)6125     public boolean getAutoTimeEnabled(@NonNull ComponentName admin) {
6126         if (mService != null) {
6127             try {
6128                 return mService.getAutoTimeEnabled(admin);
6129             } catch (RemoteException e) {
6130                 throw e.rethrowFromSystemServer();
6131             }
6132         }
6133         return false;
6134     }
6135 
6136     /**
6137      * Called by a device owner, a profile owner for the primary user or a profile
6138      * owner of an organization-owned managed profile to turn auto time zone on and off.
6139      * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
6140      * to prevent the user from changing this setting.
6141      * <p>
6142      * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
6143      * no user will be able set the date and time zone. Instead, the network date
6144      * and time zone will be used.
6145      *
6146      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6147      * @param enabled Whether time zone should be obtained automatically from the network or not.
6148      * @throws SecurityException if caller is not a device owner, a profile owner for the
6149      * primary user, or a profile owner of an organization-owned managed profile.
6150      */
setAutoTimeZoneEnabled(@onNull ComponentName admin, boolean enabled)6151     public void setAutoTimeZoneEnabled(@NonNull ComponentName admin, boolean enabled) {
6152         throwIfParentInstance("setAutoTimeZone");
6153         if (mService != null) {
6154             try {
6155                 mService.setAutoTimeZoneEnabled(admin, enabled);
6156             } catch (RemoteException e) {
6157                 throw e.rethrowFromSystemServer();
6158             }
6159         }
6160     }
6161 
6162     /**
6163      * @return true if auto time zone is enabled on the device.
6164      * @throws SecurityException if caller is not a device owner, a profile owner for the
6165      * primary user, or a profile owner of an organization-owned managed profile.
6166      */
getAutoTimeZoneEnabled(@onNull ComponentName admin)6167     public boolean getAutoTimeZoneEnabled(@NonNull ComponentName admin) {
6168         throwIfParentInstance("getAutoTimeZone");
6169         if (mService != null) {
6170             try {
6171                 return mService.getAutoTimeZoneEnabled(admin);
6172             } catch (RemoteException e) {
6173                 throw e.rethrowFromSystemServer();
6174             }
6175         }
6176         return false;
6177     }
6178 
6179     /**
6180      * Called by a device owner to set whether all users created on the device should be ephemeral.
6181      * <p>
6182      * The system user is exempt from this policy - it is never ephemeral.
6183      * <p>
6184      * The calling device admin must be the device owner. If it is not, a security exception will be
6185      * thrown.
6186      *
6187      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6188      * @param forceEphemeralUsers If true, all the existing users will be deleted and all
6189      *            subsequently created users will be ephemeral.
6190      * @throws SecurityException if {@code admin} is not a device owner.
6191      * @hide
6192      */
setForceEphemeralUsers( @onNull ComponentName admin, boolean forceEphemeralUsers)6193     public void setForceEphemeralUsers(
6194             @NonNull ComponentName admin, boolean forceEphemeralUsers) {
6195         throwIfParentInstance("setForceEphemeralUsers");
6196         if (mService != null) {
6197             try {
6198                 mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
6199             } catch (RemoteException e) {
6200                 throw e.rethrowFromSystemServer();
6201             }
6202         }
6203     }
6204 
6205     /**
6206      * @return true if all users are created ephemeral.
6207      * @throws SecurityException if {@code admin} is not a device owner.
6208      * @hide
6209      */
getForceEphemeralUsers(@onNull ComponentName admin)6210     public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
6211         throwIfParentInstance("getForceEphemeralUsers");
6212         if (mService != null) {
6213             try {
6214                 return mService.getForceEphemeralUsers(admin);
6215             } catch (RemoteException e) {
6216                 throw e.rethrowFromSystemServer();
6217             }
6218         }
6219         return false;
6220     }
6221 
6222     /**
6223      * Called by an application that is administering the device to disable keyguard customizations,
6224      * such as widgets. After setting this, keyguard features will be disabled according to the
6225      * provided feature list.
6226      * <p>
6227      * The calling device admin must have requested
6228      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
6229      * if it has not, a security exception will be thrown.
6230      * <p>
6231      * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
6232      * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
6233      * profile owner of a managed profile can set:
6234      * <ul>
6235      * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
6236      * is no separate challenge set on the managed profile.
6237      * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FACE} or
6238      * {@link #KEYGUARD_DISABLE_IRIS} which affects the managed profile challenge if
6239      * there is one, or the parent user otherwise.
6240      * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
6241      * by applications in the managed profile.
6242      * </ul>
6243      * <p>
6244      * From version {@link android.os.Build.VERSION_CODES#R} the profile owner of an
6245      * organization-owned managed profile can set:
6246      * <ul>
6247      * <li>{@link #KEYGUARD_DISABLE_SECURE_CAMERA} which affects the parent user when called on the
6248      * parent profile.
6249      * <li>{@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS} which affects the parent user when called
6250      * on the parent profile.
6251      * </ul>
6252      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, {@link #KEYGUARD_DISABLE_FINGERPRINT},
6253      * {@link #KEYGUARD_DISABLE_FACE}, {@link #KEYGUARD_DISABLE_IRIS},
6254      * {@link #KEYGUARD_DISABLE_SECURE_CAMERA} and {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS}
6255      * can also be set on the {@link DevicePolicyManager} instance returned by
6256      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
6257      * profile. {@link #KEYGUARD_DISABLE_SECURE_CAMERA} can only be set on the parent profile
6258      * instance if the calling device admin is the profile owner of an organization-owned
6259      * managed profile.
6260      * <p>
6261      * Requests to disable other features on a managed profile will be ignored.
6262      * <p>
6263      * The admin can check which features have been disabled by calling
6264      * {@link #getKeyguardDisabledFeatures(ComponentName)}
6265      *
6266      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6267      * @param which The disabled features flag which can be either
6268      *            {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
6269      *            {@link #KEYGUARD_DISABLE_FEATURES_ALL}, or a combination of
6270      *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
6271      *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
6272      *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
6273      *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
6274      *            {@link #KEYGUARD_DISABLE_FINGERPRINT},
6275      *            {@link #KEYGUARD_DISABLE_FACE},
6276      *            {@link #KEYGUARD_DISABLE_IRIS}.
6277      * @throws SecurityException if {@code admin} is not an active administrator or does not user
6278      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
6279      */
setKeyguardDisabledFeatures(@onNull ComponentName admin, int which)6280     public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
6281         if (mService != null) {
6282             try {
6283                 mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
6284             } catch (RemoteException e) {
6285                 throw e.rethrowFromSystemServer();
6286             }
6287         }
6288     }
6289 
6290     /**
6291      * Determine whether or not features have been disabled in keyguard either by the calling
6292      * admin, if specified, or all admins that set restrictions on this user and its participating
6293      * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
6294      *
6295      * <p>This method can be called on the {@link DevicePolicyManager} instance
6296      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
6297      * restrictions on the parent profile.
6298      *
6299      * @param admin The name of the admin component to check, or {@code null} to check whether any
6300      * admins have disabled features in keyguard.
6301      * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
6302      * for a list.
6303      */
getKeyguardDisabledFeatures(@ullable ComponentName admin)6304     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
6305         return getKeyguardDisabledFeatures(admin, myUserId());
6306     }
6307 
6308     /** @hide per-user version */
6309     @UnsupportedAppUsage
getKeyguardDisabledFeatures(@ullable ComponentName admin, int userHandle)6310     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
6311         if (mService != null) {
6312             try {
6313                 return mService.getKeyguardDisabledFeatures(admin, userHandle, mParentInstance);
6314             } catch (RemoteException e) {
6315                 throw e.rethrowFromSystemServer();
6316             }
6317         }
6318         return KEYGUARD_DISABLE_FEATURES_NONE;
6319     }
6320 
6321     /**
6322      * @hide
6323      */
6324     @UnsupportedAppUsage
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing, int userHandle)6325     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
6326             int userHandle) {
6327         if (mService != null) {
6328             try {
6329                 mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
6330             } catch (RemoteException e) {
6331                 throw e.rethrowFromSystemServer();
6332             }
6333         }
6334     }
6335 
6336     /**
6337      * @hide
6338      */
6339     @UnsupportedAppUsage
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing)6340     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
6341         setActiveAdmin(policyReceiver, refreshing, myUserId());
6342     }
6343 
6344     /**
6345      * @hide
6346      */
getRemoveWarning(@ullable ComponentName admin, RemoteCallback result)6347     public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
6348         if (mService != null) {
6349             try {
6350                 mService.getRemoveWarning(admin, result, myUserId());
6351             } catch (RemoteException e) {
6352                 throw e.rethrowFromSystemServer();
6353             }
6354         }
6355     }
6356 
6357     /**
6358      * @hide
6359      */
6360     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportPasswordChanged(@serIdInt int userId)6361     public void reportPasswordChanged(@UserIdInt int userId) {
6362         if (mService != null) {
6363             try {
6364                 mService.reportPasswordChanged(userId);
6365             } catch (RemoteException e) {
6366                 throw e.rethrowFromSystemServer();
6367             }
6368         }
6369     }
6370 
6371     /**
6372      * @hide
6373      */
6374     @UnsupportedAppUsage
6375     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedPasswordAttempt(int userHandle)6376     public void reportFailedPasswordAttempt(int userHandle) {
6377         if (mService != null) {
6378             try {
6379                 mService.reportFailedPasswordAttempt(userHandle);
6380             } catch (RemoteException e) {
6381                 throw e.rethrowFromSystemServer();
6382             }
6383         }
6384     }
6385 
6386     /**
6387      * @hide
6388      */
6389     @UnsupportedAppUsage
6390     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulPasswordAttempt(int userHandle)6391     public void reportSuccessfulPasswordAttempt(int userHandle) {
6392         if (mService != null) {
6393             try {
6394                 mService.reportSuccessfulPasswordAttempt(userHandle);
6395             } catch (RemoteException e) {
6396                 throw e.rethrowFromSystemServer();
6397             }
6398         }
6399     }
6400 
6401     /**
6402      * @hide
6403      */
6404     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedBiometricAttempt(int userHandle)6405     public void reportFailedBiometricAttempt(int userHandle) {
6406         if (mService != null) {
6407             try {
6408                 mService.reportFailedBiometricAttempt(userHandle);
6409             } catch (RemoteException e) {
6410                 throw e.rethrowFromSystemServer();
6411             }
6412         }
6413     }
6414 
6415     /**
6416      * @hide
6417      */
6418     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulBiometricAttempt(int userHandle)6419     public void reportSuccessfulBiometricAttempt(int userHandle) {
6420         if (mService != null) {
6421             try {
6422                 mService.reportSuccessfulBiometricAttempt(userHandle);
6423             } catch (RemoteException e) {
6424                 throw e.rethrowFromSystemServer();
6425             }
6426         }
6427     }
6428 
6429     /**
6430      * Should be called when keyguard has been dismissed.
6431      * @hide
6432      */
reportKeyguardDismissed(int userHandle)6433     public void reportKeyguardDismissed(int userHandle) {
6434         if (mService != null) {
6435             try {
6436                 mService.reportKeyguardDismissed(userHandle);
6437             } catch (RemoteException e) {
6438                 throw e.rethrowFromSystemServer();
6439             }
6440         }
6441     }
6442 
6443     /**
6444      * Should be called when keyguard view has been shown to the user.
6445      * @hide
6446      */
reportKeyguardSecured(int userHandle)6447     public void reportKeyguardSecured(int userHandle) {
6448         if (mService != null) {
6449             try {
6450                 mService.reportKeyguardSecured(userHandle);
6451             } catch (RemoteException e) {
6452                 throw e.rethrowFromSystemServer();
6453             }
6454         }
6455     }
6456 
6457     /**
6458      * @hide
6459      * Sets the given package as the device owner.
6460      * Same as {@link #setDeviceOwner(ComponentName, String)} but without setting a device owner name.
6461      * @param who the component name to be registered as device owner.
6462      * @return whether the package was successfully registered as the device owner.
6463      * @throws IllegalArgumentException if the package name is null or invalid
6464      * @throws IllegalStateException If the preconditions mentioned are not met.
6465      */
setDeviceOwner(ComponentName who)6466     public boolean setDeviceOwner(ComponentName who) {
6467         return setDeviceOwner(who, null);
6468     }
6469 
6470     /**
6471      * @hide
6472      */
setDeviceOwner(ComponentName who, int userId)6473     public boolean setDeviceOwner(ComponentName who, int userId)  {
6474         return setDeviceOwner(who, null, userId);
6475     }
6476 
6477     /**
6478      * @hide
6479      */
setDeviceOwner(ComponentName who, String ownerName)6480     public boolean setDeviceOwner(ComponentName who, String ownerName) {
6481         return setDeviceOwner(who, ownerName, UserHandle.USER_SYSTEM);
6482     }
6483 
6484     /**
6485      * @hide
6486      * Sets the given package as the device owner. The package must already be installed. There
6487      * must not already be a device owner.
6488      * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
6489      * this method.
6490      * Calling this after the setup phase of the primary user has completed is allowed only if
6491      * the caller is the shell uid, and there are no additional users and no accounts.
6492      * @param who the component name to be registered as device owner.
6493      * @param ownerName the human readable name of the institution that owns this device.
6494      * @param userId ID of the user on which the device owner runs.
6495      * @return whether the package was successfully registered as the device owner.
6496      * @throws IllegalArgumentException if the package name is null or invalid
6497      * @throws IllegalStateException If the preconditions mentioned are not met.
6498      */
setDeviceOwner(ComponentName who, String ownerName, int userId)6499     public boolean setDeviceOwner(ComponentName who, String ownerName, int userId)
6500             throws IllegalArgumentException, IllegalStateException {
6501         if (mService != null) {
6502             try {
6503                 return mService.setDeviceOwner(who, ownerName, userId);
6504             } catch (RemoteException re) {
6505                 throw re.rethrowFromSystemServer();
6506             }
6507         }
6508         return false;
6509     }
6510 
6511     /**
6512      * Used to determine if a particular package has been registered as a Device Owner app.
6513      * A device owner app is a special device admin that cannot be deactivated by the user, once
6514      * activated as a device admin. It also cannot be uninstalled. To check whether a particular
6515      * package is currently registered as the device owner app, pass in the package name from
6516      * {@link Context#getPackageName()} to this method.<p/>This is useful for device
6517      * admin apps that want to check whether they are also registered as the device owner app. The
6518      * exact mechanism by which a device admin app is registered as a device owner app is defined by
6519      * the setup process.
6520      * @param packageName the package name of the app, to compare with the registered device owner
6521      * app, if any.
6522      * @return whether or not the package is registered as the device owner app.
6523      */
isDeviceOwnerApp(String packageName)6524     public boolean isDeviceOwnerApp(String packageName) {
6525         throwIfParentInstance("isDeviceOwnerApp");
6526         return isDeviceOwnerAppOnCallingUser(packageName);
6527     }
6528 
6529     /**
6530      * @return true if a package is registered as device owner, only when it's running on the
6531      * calling user.
6532      *
6533      * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
6534      * @hide
6535      */
isDeviceOwnerAppOnCallingUser(String packageName)6536     public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
6537         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
6538     }
6539 
6540     /**
6541      * @return true if a package is registered as device owner, even if it's running on a different
6542      * user.
6543      *
6544      * <p>Requires the MANAGE_USERS permission.
6545      *
6546      * @hide
6547      */
isDeviceOwnerAppOnAnyUser(String packageName)6548     public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
6549         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
6550     }
6551 
6552     /**
6553      * @return device owner component name, only when it's running on the calling user.
6554      *
6555      * @hide
6556      */
getDeviceOwnerComponentOnCallingUser()6557     public ComponentName getDeviceOwnerComponentOnCallingUser() {
6558         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
6559     }
6560 
6561     /**
6562      * @return device owner component name, even if it's running on a different user.
6563      *
6564      * @hide
6565      */
6566     @SystemApi
6567     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwnerComponentOnAnyUser()6568     public ComponentName getDeviceOwnerComponentOnAnyUser() {
6569         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
6570     }
6571 
isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly)6572     private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
6573         if (packageName == null) {
6574             return false;
6575         }
6576         final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
6577         if (deviceOwner == null) {
6578             return false;
6579         }
6580         return packageName.equals(deviceOwner.getPackageName());
6581     }
6582 
getDeviceOwnerComponentInner(boolean callingUserOnly)6583     private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
6584         if (mService != null) {
6585             try {
6586                 return mService.getDeviceOwnerComponent(callingUserOnly);
6587             } catch (RemoteException re) {
6588                 throw re.rethrowFromSystemServer();
6589             }
6590         }
6591         return null;
6592     }
6593 
6594     /**
6595      * @return Handle of the user who runs device owner, or {@code null} if there's no device owner.
6596      *
6597      * @hide
6598      */
6599     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
6600     @SystemApi
getDeviceOwnerUser()6601     public @Nullable UserHandle getDeviceOwnerUser() {
6602         if (mService != null) {
6603             try {
6604                 int userId = mService.getDeviceOwnerUserId();
6605 
6606                 if (userId != UserHandle.USER_NULL) {
6607                     return UserHandle.of(userId);
6608                 }
6609             } catch (RemoteException re) {
6610                 throw re.rethrowFromSystemServer();
6611             }
6612         }
6613         return null;
6614     }
6615 
6616     /**
6617      * @hide
6618      */
getDeviceOwnerUserId()6619     public int getDeviceOwnerUserId() {
6620         if (mService != null) {
6621             try {
6622                 return mService.getDeviceOwnerUserId();
6623             } catch (RemoteException re) {
6624                 throw re.rethrowFromSystemServer();
6625             }
6626         }
6627         return UserHandle.USER_NULL;
6628     }
6629 
6630     /**
6631      * Clears the current device owner. The caller must be the device owner. This function should be
6632      * used cautiously as once it is called it cannot be undone. The device owner can only be set as
6633      * a part of device setup, before it completes.
6634      * <p>
6635      * While some policies previously set by the device owner will be cleared by this method, it is
6636      * a best-effort process and some other policies will still remain in place after the device
6637      * owner is cleared.
6638      *
6639      * @param packageName The package name of the device owner.
6640      * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
6641      *             does not own the current device owner component.
6642      *
6643      * @deprecated This method is expected to be used for testing purposes only. The device owner
6644      * will lose control of the device and its data after calling it. In order to protect any
6645      * sensitive data that remains on the device, it is advised that the device owner factory resets
6646      * the device instead of calling this method. See {@link #wipeData(int)}.
6647      */
6648     @Deprecated
clearDeviceOwnerApp(String packageName)6649     public void clearDeviceOwnerApp(String packageName) {
6650         throwIfParentInstance("clearDeviceOwnerApp");
6651         if (mService != null) {
6652             try {
6653                 mService.clearDeviceOwner(packageName);
6654             } catch (RemoteException re) {
6655                 throw re.rethrowFromSystemServer();
6656             }
6657         }
6658     }
6659 
6660     /**
6661      * Returns the device owner package name, only if it's running on the calling user.
6662      *
6663      * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
6664      *
6665      * @hide
6666      */
6667     @SystemApi
6668     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwner()6669     public @Nullable String getDeviceOwner() {
6670         throwIfParentInstance("getDeviceOwner");
6671         final ComponentName name = getDeviceOwnerComponentOnCallingUser();
6672         return name != null ? name.getPackageName() : null;
6673     }
6674 
6675     /**
6676      * Called by the system to find out whether the device is managed by a Device Owner.
6677      *
6678      * @return whether the device is managed by a Device Owner.
6679      * @throws SecurityException if the caller is not the device owner, does not hold the
6680      *         MANAGE_USERS permission and is not the system.
6681      *
6682      * @hide
6683      */
6684     @SystemApi
6685     @TestApi
6686     @SuppressLint("Doclava125")
isDeviceManaged()6687     public boolean isDeviceManaged() {
6688         try {
6689             return mService.hasDeviceOwner();
6690         } catch (RemoteException re) {
6691             throw re.rethrowFromSystemServer();
6692         }
6693     }
6694 
6695     /**
6696      * Returns the device owner name.  Note this method *will* return the device owner
6697      * name when it's running on a different user.
6698      *
6699      * @hide
6700      */
6701     @SystemApi
6702     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwnerNameOnAnyUser()6703     public String getDeviceOwnerNameOnAnyUser() {
6704         throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
6705         if (mService != null) {
6706             try {
6707                 return mService.getDeviceOwnerName();
6708             } catch (RemoteException re) {
6709                 throw re.rethrowFromSystemServer();
6710             }
6711         }
6712         return null;
6713     }
6714 
6715     /**
6716      * @hide
6717      * @deprecated Use #ACTION_SET_PROFILE_OWNER
6718      * Sets the given component as an active admin and registers the package as the profile
6719      * owner for this user. The package must already be installed and there shouldn't be
6720      * an existing profile owner registered for this user. Also, this method must be called
6721      * before the user setup has been completed.
6722      * <p>
6723      * This method can only be called by system apps that hold MANAGE_USERS permission and
6724      * MANAGE_DEVICE_ADMINS permission.
6725      * @param admin The component to register as an active admin and profile owner.
6726      * @param ownerName The user-visible name of the entity that is managing this user.
6727      * @return whether the admin was successfully registered as the profile owner.
6728      * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
6729      *         the user has already been set up.
6730      */
6731     @Deprecated
6732     @SystemApi
6733     @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
setActiveProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName)6734     public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
6735             throws IllegalArgumentException {
6736         throwIfParentInstance("setActiveProfileOwner");
6737         if (mService != null) {
6738             try {
6739                 final int myUserId = myUserId();
6740                 mService.setActiveAdmin(admin, false, myUserId);
6741                 return mService.setProfileOwner(admin, ownerName, myUserId);
6742             } catch (RemoteException re) {
6743                 throw re.rethrowFromSystemServer();
6744             }
6745         }
6746         return false;
6747     }
6748 
6749     /**
6750      * Clears the active profile owner. The caller must be the profile owner of this user, otherwise
6751      * a SecurityException will be thrown. This method is not available to managed profile owners.
6752      * <p>
6753      * While some policies previously set by the profile owner will be cleared by this method, it is
6754      * a best-effort process and some other policies will still remain in place after the profile
6755      * owner is cleared.
6756      *
6757      * @param admin The component to remove as the profile owner.
6758      * @throws SecurityException if {@code admin} is not an active profile owner, or the method is
6759      * being called from a managed profile.
6760      *
6761      * @deprecated This method is expected to be used for testing purposes only. The profile owner
6762      * will lose control of the user and its data after calling it. In order to protect any
6763      * sensitive data that remains on this user, it is advised that the profile owner deletes it
6764      * instead of calling this method. See {@link #wipeData(int)}.
6765      */
6766     @Deprecated
clearProfileOwner(@onNull ComponentName admin)6767     public void clearProfileOwner(@NonNull ComponentName admin) {
6768         throwIfParentInstance("clearProfileOwner");
6769         if (mService != null) {
6770             try {
6771                 mService.clearProfileOwner(admin);
6772             } catch (RemoteException re) {
6773                 throw re.rethrowFromSystemServer();
6774             }
6775         }
6776     }
6777 
6778     /**
6779      * @hide
6780      * Checks whether the user was already setup.
6781      */
hasUserSetupCompleted()6782     public boolean hasUserSetupCompleted() {
6783         if (mService != null) {
6784             try {
6785                 return mService.hasUserSetupCompleted();
6786             } catch (RemoteException re) {
6787                 throw re.rethrowFromSystemServer();
6788             }
6789         }
6790         return true;
6791     }
6792 
6793     /**
6794      * @hide
6795      * Sets the given component as the profile owner of the given user profile. The package must
6796      * already be installed. There must not already be a profile owner for this user.
6797      * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
6798      * this method.
6799      * Calling this after the setup phase of the specified user has completed is allowed only if:
6800      * - the caller is SYSTEM_UID.
6801      * - or the caller is the shell uid, and there are no accounts on the specified user.
6802      * @param admin the component name to be registered as profile owner.
6803      * @param ownerName the human readable name of the organisation associated with this DPM.
6804      * @param userHandle the userId to set the profile owner for.
6805      * @return whether the component was successfully registered as the profile owner.
6806      * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
6807      * preconditions mentioned are not met.
6808      */
setProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName, int userHandle)6809     public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
6810             int userHandle) throws IllegalArgumentException {
6811         if (mService != null) {
6812             try {
6813                 if (ownerName == null) {
6814                     ownerName = "";
6815                 }
6816                 return mService.setProfileOwner(admin, ownerName, userHandle);
6817             } catch (RemoteException re) {
6818                 throw re.rethrowFromSystemServer();
6819             }
6820         }
6821         return false;
6822     }
6823 
6824     /**
6825      * Sets the device owner information to be shown on the lock screen.
6826      * <p>
6827      * Device owner information set using this method overrides any owner information manually set
6828      * by the user and prevents the user from further changing it.
6829      * <p>
6830      * If the device owner information is {@code null} or empty then the device owner info is
6831      * cleared and the user owner info is shown on the lock screen if it is set.
6832      * <p>
6833      * If the device owner information contains only whitespaces then the message on the lock screen
6834      * will be blank and the user will not be allowed to change it.
6835      * <p>
6836      * If the device owner information needs to be localized, it is the responsibility of the
6837      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
6838      * and set a new version of this string accordingly.
6839      * <p>
6840      * May be called by the device owner or the profile owner of an organization-owned device.
6841      *
6842      * @param admin The name of the admin component to check.
6843      * @param info Device owner information which will be displayed instead of the user owner info.
6844      * @throws SecurityException if {@code admin} is not a device owner.
6845      */
setDeviceOwnerLockScreenInfo(@onNull ComponentName admin, CharSequence info)6846     public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
6847         throwIfParentInstance("setDeviceOwnerLockScreenInfo");
6848         if (mService != null) {
6849             try {
6850                 mService.setDeviceOwnerLockScreenInfo(admin, info);
6851             } catch (RemoteException re) {
6852                 throw re.rethrowFromSystemServer();
6853             }
6854         }
6855     }
6856 
6857     /**
6858      * @return The device owner information. If it is not set returns {@code null}.
6859      */
getDeviceOwnerLockScreenInfo()6860     public CharSequence getDeviceOwnerLockScreenInfo() {
6861         throwIfParentInstance("getDeviceOwnerLockScreenInfo");
6862         if (mService != null) {
6863             try {
6864                 return mService.getDeviceOwnerLockScreenInfo();
6865             } catch (RemoteException re) {
6866                 throw re.rethrowFromSystemServer();
6867             }
6868         }
6869         return null;
6870     }
6871 
6872     /**
6873      * Called by device or profile owners to suspend packages for this user. This function can be
6874      * called by a device owner, profile owner, or by a delegate given the
6875      * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}.
6876      * <p>
6877      * A suspended package will not be able to start activities. Its notifications will be hidden,
6878      * it will not show up in recents, will not be able to show toasts or dialogs or ring the
6879      * device.
6880      * <p>
6881      * The package must already be installed. If the package is uninstalled while suspended the
6882      * package will no longer be suspended. The admin can block this by using
6883      * {@link #setUninstallBlocked}.
6884      *
6885      * <p>Some apps cannot be suspended, such as device admins, the active launcher, the required
6886      * package installer, the required package uninstaller, the required package verifier, the
6887      * default dialer, and the permission controller.
6888      *
6889      * @param admin The name of the admin component to check, or {@code null} if the caller is a
6890      *            package access delegate.
6891      * @param packageNames The package names to suspend or unsuspend.
6892      * @param suspended If set to {@code true} than the packages will be suspended, if set to
6893      *            {@code false} the packages will be unsuspended.
6894      * @return an array of package names for which the suspended status is not set as requested in
6895      *         this method.
6896      * @throws SecurityException if {@code admin} is not a device or profile owner.
6897      * @see #setDelegatedScopes
6898      * @see #DELEGATION_PACKAGE_ACCESS
6899      */
setPackagesSuspended(@onNull ComponentName admin, @NonNull String[] packageNames, boolean suspended)6900     public @NonNull String[] setPackagesSuspended(@NonNull ComponentName admin,
6901             @NonNull String[] packageNames, boolean suspended) {
6902         throwIfParentInstance("setPackagesSuspended");
6903         if (mService != null) {
6904             try {
6905                 return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames,
6906                         suspended);
6907             } catch (RemoteException re) {
6908                 throw re.rethrowFromSystemServer();
6909             }
6910         }
6911         return packageNames;
6912     }
6913 
6914     /**
6915      * Determine if a package is suspended. This function can be called by a device owner, profile
6916      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
6917      * {@link #setDelegatedScopes}.
6918      *
6919      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6920      *            {@code null} if the caller is a package access delegate.
6921      * @param packageName The name of the package to retrieve the suspended status of.
6922      * @return {@code true} if the package is suspended or {@code false} if the package is not
6923      *         suspended, could not be found or an error occurred.
6924      * @throws SecurityException if {@code admin} is not a device or profile owner.
6925      * @throws NameNotFoundException if the package could not be found.
6926      * @see #setDelegatedScopes
6927      * @see #DELEGATION_PACKAGE_ACCESS
6928      */
isPackageSuspended(@onNull ComponentName admin, String packageName)6929     public boolean isPackageSuspended(@NonNull ComponentName admin, String packageName)
6930             throws NameNotFoundException {
6931         throwIfParentInstance("isPackageSuspended");
6932         if (mService != null) {
6933             try {
6934                 return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName);
6935             } catch (RemoteException e) {
6936                 throw e.rethrowFromSystemServer();
6937             } catch (IllegalArgumentException ex) {
6938                 throw new NameNotFoundException(packageName);
6939             }
6940         }
6941         return false;
6942     }
6943 
6944     /**
6945      * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
6946      * be used. Only the profile owner can call this.
6947      *
6948      * @see #isProfileOwnerApp
6949      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6950      * @throws SecurityException if {@code admin} is not a profile owner.
6951      */
setProfileEnabled(@onNull ComponentName admin)6952     public void setProfileEnabled(@NonNull ComponentName admin) {
6953         throwIfParentInstance("setProfileEnabled");
6954         if (mService != null) {
6955             try {
6956                 mService.setProfileEnabled(admin);
6957             } catch (RemoteException e) {
6958                 throw e.rethrowFromSystemServer();
6959             }
6960         }
6961     }
6962 
6963     /**
6964      * Sets the name of the profile. In the device owner case it sets the name of the user which it
6965      * is called from. Only a profile owner or device owner can call this. If this is never called
6966      * by the profile or device owner, the name will be set to default values.
6967      *
6968      * @see #isProfileOwnerApp
6969      * @see #isDeviceOwnerApp
6970      * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
6971      * @param profileName The name of the profile.
6972      * @throws SecurityException if {@code admin} is not a device or profile owner.
6973      */
setProfileName(@onNull ComponentName admin, String profileName)6974     public void setProfileName(@NonNull ComponentName admin, String profileName) {
6975         throwIfParentInstance("setProfileName");
6976         if (mService != null) {
6977             try {
6978                 mService.setProfileName(admin, profileName);
6979             } catch (RemoteException e) {
6980                 throw e.rethrowFromSystemServer();
6981             }
6982         }
6983     }
6984 
6985     /**
6986      * Used to determine if a particular package is registered as the profile owner for the
6987      * user. A profile owner is a special device admin that has additional privileges
6988      * within the profile.
6989      *
6990      * @param packageName The package name of the app to compare with the registered profile owner.
6991      * @return Whether or not the package is registered as the profile owner.
6992      */
isProfileOwnerApp(String packageName)6993     public boolean isProfileOwnerApp(String packageName) {
6994         throwIfParentInstance("isProfileOwnerApp");
6995         if (mService != null) {
6996             try {
6997                 ComponentName profileOwner = mService.getProfileOwner(myUserId());
6998                 return profileOwner != null
6999                         && profileOwner.getPackageName().equals(packageName);
7000             } catch (RemoteException re) {
7001                 throw re.rethrowFromSystemServer();
7002             }
7003         }
7004         return false;
7005     }
7006 
7007     /**
7008      * @hide
7009      * @return the packageName of the owner of the given user profile or {@code null} if no profile
7010      * owner has been set for that user.
7011      * @throws IllegalArgumentException if the userId is invalid.
7012      */
7013     @SystemApi
getProfileOwner()7014     public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
7015         throwIfParentInstance("getProfileOwner");
7016         return getProfileOwnerAsUser(mContext.getUserId());
7017     }
7018 
7019     /**
7020      * @see #getProfileOwner()
7021      * @hide
7022      */
7023     @RequiresPermission(value = android.Manifest.permission.INTERACT_ACROSS_USERS,
7024             conditional = true)
getProfileOwnerAsUser(@onNull UserHandle user)7025     public @Nullable ComponentName getProfileOwnerAsUser(@NonNull UserHandle user) {
7026         if (mService != null) {
7027             try {
7028                 return mService.getProfileOwnerAsUser(user.getIdentifier());
7029             } catch (RemoteException re) {
7030                 throw re.rethrowFromSystemServer();
7031             }
7032         }
7033         return null;
7034     }
7035 
7036     /**
7037      * @hide
7038      */
7039     @UnsupportedAppUsage
getProfileOwnerAsUser(final int userId)7040     public @Nullable ComponentName getProfileOwnerAsUser(final int userId) {
7041         if (mService != null) {
7042             try {
7043                 return mService.getProfileOwnerAsUser(userId);
7044             } catch (RemoteException re) {
7045                 throw re.rethrowFromSystemServer();
7046             }
7047         }
7048         return null;
7049     }
7050 
7051     /**
7052      * Returns the configured supervision app if it exists and is the device owner or policy owner.
7053      * @hide
7054      */
getProfileOwnerOrDeviceOwnerSupervisionComponent( @onNull UserHandle user)7055     public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent(
7056             @NonNull UserHandle user) {
7057         if (mService != null) {
7058             try {
7059                 return mService.getProfileOwnerOrDeviceOwnerSupervisionComponent(user);
7060             } catch (RemoteException re) {
7061                 throw re.rethrowFromSystemServer();
7062             }
7063         }
7064         return null;
7065     }
7066 
7067     /**
7068      * @hide
7069      * @return the human readable name of the organisation associated with this DPM or {@code null}
7070      *         if one is not set.
7071      * @throws IllegalArgumentException if the userId is invalid.
7072      */
getProfileOwnerName()7073     public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
7074         if (mService != null) {
7075             try {
7076                 return mService.getProfileOwnerName(mContext.getUserId());
7077             } catch (RemoteException re) {
7078                 throw re.rethrowFromSystemServer();
7079             }
7080         }
7081         return null;
7082     }
7083 
7084     /**
7085      * @hide
7086      * @param userId The user for whom to fetch the profile owner name, if any.
7087      * @return the human readable name of the organisation associated with this profile owner or
7088      *         null if one is not set.
7089      * @throws IllegalArgumentException if the userId is invalid.
7090      */
7091     @SystemApi
7092     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getProfileOwnerNameAsUser(int userId)7093     public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
7094         throwIfParentInstance("getProfileOwnerNameAsUser");
7095         if (mService != null) {
7096             try {
7097                 return mService.getProfileOwnerName(userId);
7098             } catch (RemoteException re) {
7099                 throw re.rethrowFromSystemServer();
7100             }
7101         }
7102         return null;
7103     }
7104 
7105     /**
7106      * Apps can use this method to find out if the device was provisioned as
7107      * organization-owend device with a managed profile.
7108      *
7109      * This, together with checking whether the device has a device owner (by calling
7110      * {@link #isDeviceOwnerApp}), could be used to learn whether the device is owned by an
7111      * organization or an individual:
7112      * If this method returns true OR {@link #isDeviceOwnerApp} returns true (for any package),
7113      * then the device is owned by an organization. Otherwise, it's owned by an individual.
7114      *
7115      * @return {@code true} if the device was provisioned as organization-owned device,
7116      * {@code false} otherwise.
7117      */
isOrganizationOwnedDeviceWithManagedProfile()7118     public boolean isOrganizationOwnedDeviceWithManagedProfile() {
7119         throwIfParentInstance("isOrganizationOwnedDeviceWithManagedProfile");
7120         if (mService != null) {
7121             try {
7122                 return mService.isOrganizationOwnedDeviceWithManagedProfile();
7123             } catch (RemoteException re) {
7124                 throw re.rethrowFromSystemServer();
7125             }
7126         }
7127         return false;
7128     }
7129 
7130     /**
7131      * Returns whether the specified package can read the device identifiers.
7132      *
7133      * @param packageName The package name of the app to check for device identifier access.
7134      * @param pid The process id of the package to be checked.
7135      * @param uid The uid of the package to be checked.
7136      * @return whether the package can read the device identifiers.
7137      *
7138      * @hide
7139      */
hasDeviceIdentifierAccess(@onNull String packageName, int pid, int uid)7140     public boolean hasDeviceIdentifierAccess(@NonNull String packageName, int pid, int uid) {
7141         throwIfParentInstance("hasDeviceIdentifierAccess");
7142         if (packageName == null) {
7143             return false;
7144         }
7145         if (mService != null) {
7146             try {
7147                 return mService.checkDeviceIdentifierAccess(packageName, pid, uid);
7148             } catch (RemoteException re) {
7149                 throw re.rethrowFromSystemServer();
7150             }
7151         }
7152         return false;
7153     }
7154 
7155     /**
7156      * Called by a profile owner or device owner to set a default activity that the system selects
7157      * to handle intents that match the given {@link IntentFilter}. This activity will remain the
7158      * default intent handler even if the set of potential event handlers for the intent filter
7159      * changes and if the intent preferences are reset.
7160      * <p>
7161      * Note that the caller should still declare the activity in the manifest, the API just sets
7162      * the activity to be the default one to handle the given intent filter.
7163      * <p>
7164      * The default disambiguation mechanism takes over if the activity is not installed (anymore).
7165      * When the activity is (re)installed, it is automatically reset as default intent handler for
7166      * the filter.
7167      * <p>
7168      * The calling device admin must be a profile owner or device owner. If it is not, a security
7169      * exception will be thrown.
7170      *
7171      * <p>NOTE: Performs disk I/O and shouldn't be called on the main thread.
7172      *
7173      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7174      * @param filter The IntentFilter for which a default handler is added.
7175      * @param activity The Activity that is added as default intent handler.
7176      * @throws SecurityException if {@code admin} is not a device or profile owner.
7177      */
addPersistentPreferredActivity(@onNull ComponentName admin, IntentFilter filter, @NonNull ComponentName activity)7178     public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
7179             @NonNull ComponentName activity) {
7180         throwIfParentInstance("addPersistentPreferredActivity");
7181         if (mService != null) {
7182             try {
7183                 mService.addPersistentPreferredActivity(admin, filter, activity);
7184             } catch (RemoteException e) {
7185                 throw e.rethrowFromSystemServer();
7186             }
7187         }
7188     }
7189 
7190     /**
7191      * Called by a profile owner or device owner to remove all persistent intent handler preferences
7192      * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
7193      * <p>
7194      * The calling device admin must be a profile owner. If it is not, a security exception will be
7195      * thrown.
7196      *
7197      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7198      * @param packageName The name of the package for which preferences are removed.
7199      * @throws SecurityException if {@code admin} is not a device or profile owner.
7200      */
clearPackagePersistentPreferredActivities(@onNull ComponentName admin, String packageName)7201     public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
7202             String packageName) {
7203         throwIfParentInstance("clearPackagePersistentPreferredActivities");
7204         if (mService != null) {
7205             try {
7206                 mService.clearPackagePersistentPreferredActivities(admin, packageName);
7207             } catch (RemoteException e) {
7208                 throw e.rethrowFromSystemServer();
7209             }
7210         }
7211     }
7212 
7213     /**
7214      * Must be called by a device owner or a profile owner of an organization-owned managed profile
7215      * to set the default SMS application.
7216      * <p>
7217      * This method can be called on the {@link DevicePolicyManager} instance, returned by
7218      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
7219      * of an organization-owned managed profile and the package must be a pre-installed system
7220      * package. If called on the parent instance, then the default SMS application is set on the
7221      * personal profile.
7222      *
7223      * @param admin       Which {@link DeviceAdminReceiver} this request is associated with.
7224      * @param packageName The name of the package to set as the default SMS application.
7225      * @throws SecurityException        if {@code admin} is not a device or profile owner or if
7226      *                                  called on the parent profile and the {@code admin} is not a
7227      *                                  profile owner of an organization-owned managed profile.
7228      * @throws IllegalArgumentException if called on the parent profile and the package
7229      *                                  provided is not a pre-installed system package.
7230      */
setDefaultSmsApplication(@onNull ComponentName admin, @NonNull String packageName)7231     public void setDefaultSmsApplication(@NonNull ComponentName admin,
7232             @NonNull String packageName) {
7233         if (mService != null) {
7234             try {
7235                 mService.setDefaultSmsApplication(admin, packageName, mParentInstance);
7236             } catch (RemoteException e) {
7237                 throw e.rethrowFromSystemServer();
7238             }
7239         }
7240     }
7241 
7242     /**
7243      * Called by a profile owner or device owner to grant permission to a package to manage
7244      * application restrictions for the calling user via {@link #setApplicationRestrictions} and
7245      * {@link #getApplicationRestrictions}.
7246      * <p>
7247      * This permission is persistent until it is later cleared by calling this method with a
7248      * {@code null} value or uninstalling the managing package.
7249      * <p>
7250      * The supplied application restriction managing package must be installed when calling this
7251      * API, otherwise an {@link NameNotFoundException} will be thrown.
7252      *
7253      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7254      * @param packageName The package name which will be given access to application restrictions
7255      *            APIs. If {@code null} is given the current package will be cleared.
7256      * @throws SecurityException if {@code admin} is not a device or profile owner.
7257      * @throws NameNotFoundException if {@code packageName} is not found
7258      *
7259      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
7260      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
7261      */
7262     @Deprecated
setApplicationRestrictionsManagingPackage(@onNull ComponentName admin, @Nullable String packageName)7263     public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
7264             @Nullable String packageName) throws NameNotFoundException {
7265         throwIfParentInstance("setApplicationRestrictionsManagingPackage");
7266         if (mService != null) {
7267             try {
7268                 if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
7269                     throw new NameNotFoundException(packageName);
7270                 }
7271             } catch (RemoteException e) {
7272                 throw e.rethrowFromSystemServer();
7273             }
7274         }
7275     }
7276 
7277     /**
7278      * Called by a profile owner or device owner to retrieve the application restrictions managing
7279      * package for the current user, or {@code null} if none is set. If there are multiple
7280      * delegates this function will return one of them.
7281      *
7282      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7283      * @return The package name allowed to manage application restrictions on the current user, or
7284      *         {@code null} if none is set.
7285      * @throws SecurityException if {@code admin} is not a device or profile owner.
7286      *
7287      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
7288      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
7289      */
7290     @Deprecated
7291     @Nullable
getApplicationRestrictionsManagingPackage( @onNull ComponentName admin)7292     public String getApplicationRestrictionsManagingPackage(
7293             @NonNull ComponentName admin) {
7294         throwIfParentInstance("getApplicationRestrictionsManagingPackage");
7295         if (mService != null) {
7296             try {
7297                 return mService.getApplicationRestrictionsManagingPackage(admin);
7298             } catch (RemoteException e) {
7299                 throw e.rethrowFromSystemServer();
7300             }
7301         }
7302         return null;
7303     }
7304 
7305     /**
7306      * Called by any application to find out whether it has been granted permission via
7307      * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
7308      * for the calling user.
7309      *
7310      * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
7311      * that method.
7312      *
7313      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes}
7314      * instead.
7315      */
7316     @Deprecated
isCallerApplicationRestrictionsManagingPackage()7317     public boolean isCallerApplicationRestrictionsManagingPackage() {
7318         throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
7319         if (mService != null) {
7320             try {
7321                 return mService.isCallerApplicationRestrictionsManagingPackage(
7322                         mContext.getPackageName());
7323             } catch (RemoteException e) {
7324                 throw e.rethrowFromSystemServer();
7325             }
7326         }
7327         return false;
7328     }
7329 
7330     /**
7331      * Sets the application restrictions for a given target application running in the calling user.
7332      * <p>
7333      * The caller must be a profile or device owner on that user, or the package allowed to manage
7334      * application restrictions via {@link #setDelegatedScopes} with the
7335      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
7336      * <p>
7337      * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
7338      * <ul>
7339      * <li>{@code boolean}
7340      * <li>{@code int}
7341      * <li>{@code String} or {@code String[]}
7342      * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
7343      * </ul>
7344      * <p>
7345      * If the restrictions are not available yet, but may be applied in the near future, the caller
7346      * can notify the target application of that by adding
7347      * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
7348      * <p>
7349      * The application restrictions are only made visible to the target application via
7350      * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
7351      * owner, and the application restrictions managing package via
7352      * {@link #getApplicationRestrictions}.
7353      *
7354      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
7355      *
7356      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7357      *            {@code null} if called by the application restrictions managing package.
7358      * @param packageName The name of the package to update restricted settings for.
7359      * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
7360      *            set of active restrictions.
7361      * @throws SecurityException if {@code admin} is not a device or profile owner.
7362      * @see #setDelegatedScopes
7363      * @see #DELEGATION_APP_RESTRICTIONS
7364      * @see UserManager#KEY_RESTRICTIONS_PENDING
7365      */
7366     @WorkerThread
setApplicationRestrictions(@ullable ComponentName admin, String packageName, Bundle settings)7367     public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
7368             Bundle settings) {
7369         throwIfParentInstance("setApplicationRestrictions");
7370         if (mService != null) {
7371             try {
7372                 mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName,
7373                         settings);
7374             } catch (RemoteException e) {
7375                 throw e.rethrowFromSystemServer();
7376             }
7377         }
7378     }
7379 
7380     /**
7381      * Sets a list of configuration features to enable for a trust agent component. This is meant to
7382      * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
7383      * agents but those enabled by this function call. If flag
7384      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
7385      * <p>
7386      * For any specific trust agent, whether it is disabled or not depends on the aggregated state
7387      * of each admin's {@link #KEYGUARD_DISABLE_TRUST_AGENTS} setting and its trust agent
7388      * configuration as set by this function call. In particular: if any admin sets
7389      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and does not additionally set any
7390      * trust agent configuration, the trust agent is disabled completely. Otherwise, the trust agent
7391      * will receive the list of configurations from all admins who set
7392      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and aggregate the configurations to determine its
7393      * behavior. The exact meaning of aggregation is trust-agent-specific.
7394      * <p>
7395      * The calling device admin must have requested
7396      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
7397      * if not, a security exception will be thrown.
7398      * <p>
7399      * This method can be called on the {@link DevicePolicyManager} instance returned by
7400      * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
7401      * the parent profile.
7402      * <p>
7403      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, calling
7404      * this method has no effect - no trust agent configuration will be set.
7405      *
7406      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7407      * @param target Component name of the agent to be configured.
7408      * @param configuration Trust-agent-specific feature configuration bundle. Please consult
7409      *        documentation of the specific trust agent to determine the interpretation of this
7410      *        bundle.
7411      * @throws SecurityException if {@code admin} is not an active administrator or does not use
7412      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
7413      */
7414     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setTrustAgentConfiguration(@onNull ComponentName admin, @NonNull ComponentName target, PersistableBundle configuration)7415     public void setTrustAgentConfiguration(@NonNull ComponentName admin,
7416             @NonNull ComponentName target, PersistableBundle configuration) {
7417         if (mService != null) {
7418             try {
7419                 mService.setTrustAgentConfiguration(admin, target, configuration, mParentInstance);
7420             } catch (RemoteException e) {
7421                 throw e.rethrowFromSystemServer();
7422             }
7423         }
7424     }
7425 
7426     /**
7427      * Gets configuration for the given trust agent based on aggregating all calls to
7428      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
7429      * all device admins.
7430      * <p>
7431      * This method can be called on the {@link DevicePolicyManager} instance returned by
7432      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
7433      * on the parent profile.
7434      * <p>
7435      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, null is
7436      * always returned.
7437      *
7438      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
7439      * this function returns a list of configurations for all admins that declare
7440      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
7441      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
7442      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
7443      * for this {@param agent} or calls it with a null configuration, null is returned.
7444      * @param agent Which component to get enabled features for.
7445      * @return configuration for the given trust agent.
7446      */
7447     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent)7448     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
7449             @Nullable ComponentName admin, @NonNull ComponentName agent) {
7450         return getTrustAgentConfiguration(admin, agent, myUserId());
7451     }
7452 
7453     /** @hide per-user version */
7454     @UnsupportedAppUsage
7455     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent, int userHandle)7456     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
7457             @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
7458         if (mService != null) {
7459             try {
7460                 return mService.getTrustAgentConfiguration(admin, agent, userHandle,
7461                         mParentInstance);
7462             } catch (RemoteException e) {
7463                 throw e.rethrowFromSystemServer();
7464             }
7465         }
7466         return new ArrayList<PersistableBundle>(); // empty list
7467     }
7468 
7469     /**
7470      * Called by a profile owner of a managed profile to set whether caller-Id information from the
7471      * managed profile will be shown in the parent profile, for incoming calls.
7472      * <p>
7473      * The calling device admin must be a profile owner. If it is not, a security exception will be
7474      * thrown.
7475      *
7476      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7477      * @param disabled If true caller-Id information in the managed profile is not displayed.
7478      * @throws SecurityException if {@code admin} is not a profile owner.
7479      */
setCrossProfileCallerIdDisabled(@onNull ComponentName admin, boolean disabled)7480     public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
7481         throwIfParentInstance("setCrossProfileCallerIdDisabled");
7482         if (mService != null) {
7483             try {
7484                 mService.setCrossProfileCallerIdDisabled(admin, disabled);
7485             } catch (RemoteException e) {
7486                 throw e.rethrowFromSystemServer();
7487             }
7488         }
7489     }
7490 
7491     /**
7492      * Called by a profile owner of a managed profile to determine whether or not caller-Id
7493      * information has been disabled.
7494      * <p>
7495      * The calling device admin must be a profile owner. If it is not, a security exception will be
7496      * thrown.
7497      *
7498      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7499      * @throws SecurityException if {@code admin} is not a profile owner.
7500      */
getCrossProfileCallerIdDisabled(@onNull ComponentName admin)7501     public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
7502         throwIfParentInstance("getCrossProfileCallerIdDisabled");
7503         if (mService != null) {
7504             try {
7505                 return mService.getCrossProfileCallerIdDisabled(admin);
7506             } catch (RemoteException e) {
7507                 throw e.rethrowFromSystemServer();
7508             }
7509         }
7510         return false;
7511     }
7512 
7513     /**
7514      * Determine whether or not caller-Id information has been disabled.
7515      *
7516      * @param userHandle The user for whom to check the caller-id permission
7517      * @hide
7518      */
getCrossProfileCallerIdDisabled(UserHandle userHandle)7519     public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
7520         if (mService != null) {
7521             try {
7522                 return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
7523             } catch (RemoteException e) {
7524                 throw e.rethrowFromSystemServer();
7525             }
7526         }
7527         return false;
7528     }
7529 
7530     /**
7531      * Called by a profile owner of a managed profile to set whether contacts search from the
7532      * managed profile will be shown in the parent profile, for incoming calls.
7533      * <p>
7534      * The calling device admin must be a profile owner. If it is not, a security exception will be
7535      * thrown.
7536      *
7537      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7538      * @param disabled If true contacts search in the managed profile is not displayed.
7539      * @throws SecurityException if {@code admin} is not a profile owner.
7540      */
setCrossProfileContactsSearchDisabled(@onNull ComponentName admin, boolean disabled)7541     public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
7542             boolean disabled) {
7543         throwIfParentInstance("setCrossProfileContactsSearchDisabled");
7544         if (mService != null) {
7545             try {
7546                 mService.setCrossProfileContactsSearchDisabled(admin, disabled);
7547             } catch (RemoteException e) {
7548                 throw e.rethrowFromSystemServer();
7549             }
7550         }
7551     }
7552 
7553     /**
7554      * Called by a profile owner of a managed profile to determine whether or not contacts search
7555      * has been disabled.
7556      * <p>
7557      * The calling device admin must be a profile owner. If it is not, a security exception will be
7558      * thrown.
7559      *
7560      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7561      * @throws SecurityException if {@code admin} is not a profile owner.
7562      */
getCrossProfileContactsSearchDisabled(@onNull ComponentName admin)7563     public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
7564         throwIfParentInstance("getCrossProfileContactsSearchDisabled");
7565         if (mService != null) {
7566             try {
7567                 return mService.getCrossProfileContactsSearchDisabled(admin);
7568             } catch (RemoteException e) {
7569                 throw e.rethrowFromSystemServer();
7570             }
7571         }
7572         return false;
7573     }
7574 
7575 
7576     /**
7577      * Determine whether or not contacts search has been disabled.
7578      *
7579      * @param userHandle The user for whom to check the contacts search permission
7580      * @hide
7581      */
getCrossProfileContactsSearchDisabled(@onNull UserHandle userHandle)7582     public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
7583         if (mService != null) {
7584             try {
7585                 return mService
7586                         .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
7587             } catch (RemoteException e) {
7588                 throw e.rethrowFromSystemServer();
7589             }
7590         }
7591         return false;
7592     }
7593 
7594     /**
7595      * Start Quick Contact on the managed profile for the user, if the policy allows.
7596      *
7597      * @hide
7598      */
startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long directoryId, Intent originalIntent)7599     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7600             boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
7601         if (mService != null) {
7602             try {
7603                 mService.startManagedQuickContact(actualLookupKey, actualContactId,
7604                         isContactIdIgnored, directoryId, originalIntent);
7605             } catch (RemoteException e) {
7606                 throw e.rethrowFromSystemServer();
7607             }
7608         }
7609     }
7610 
7611     /**
7612      * Start Quick Contact on the managed profile for the user, if the policy allows.
7613      * @hide
7614      */
startManagedQuickContact(String actualLookupKey, long actualContactId, Intent originalIntent)7615     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7616             Intent originalIntent) {
7617         startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
7618                 originalIntent);
7619     }
7620 
7621     /**
7622      * Called by a profile owner of a managed profile to set whether bluetooth devices can access
7623      * enterprise contacts.
7624      * <p>
7625      * The calling device admin must be a profile owner. If it is not, a security exception will be
7626      * thrown.
7627      * <p>
7628      * This API works on managed profile only.
7629      *
7630      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7631      * @param disabled If true, bluetooth devices cannot access enterprise contacts.
7632      * @throws SecurityException if {@code admin} is not a profile owner.
7633      */
setBluetoothContactSharingDisabled(@onNull ComponentName admin, boolean disabled)7634     public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
7635         throwIfParentInstance("setBluetoothContactSharingDisabled");
7636         if (mService != null) {
7637             try {
7638                 mService.setBluetoothContactSharingDisabled(admin, disabled);
7639             } catch (RemoteException e) {
7640                 throw e.rethrowFromSystemServer();
7641             }
7642         }
7643     }
7644 
7645     /**
7646      * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
7647      * cannot access enterprise contacts.
7648      * <p>
7649      * The calling device admin must be a profile owner. If it is not, a security exception will be
7650      * thrown.
7651      * <p>
7652      * This API works on managed profile only.
7653      *
7654      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7655      * @throws SecurityException if {@code admin} is not a profile owner.
7656      */
getBluetoothContactSharingDisabled(@onNull ComponentName admin)7657     public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
7658         throwIfParentInstance("getBluetoothContactSharingDisabled");
7659         if (mService != null) {
7660             try {
7661                 return mService.getBluetoothContactSharingDisabled(admin);
7662             } catch (RemoteException e) {
7663                 throw e.rethrowFromSystemServer();
7664             }
7665         }
7666         return true;
7667     }
7668 
7669     /**
7670      * Determine whether or not Bluetooth devices cannot access contacts.
7671      * <p>
7672      * This API works on managed profile UserHandle only.
7673      *
7674      * @param userHandle The user for whom to check the caller-id permission
7675      * @hide
7676      */
7677     @SystemApi
7678     @RequiresPermission(permission.INTERACT_ACROSS_USERS)
getBluetoothContactSharingDisabled(@onNull UserHandle userHandle)7679     public boolean getBluetoothContactSharingDisabled(@NonNull UserHandle userHandle) {
7680         if (mService != null) {
7681             try {
7682                 return mService.getBluetoothContactSharingDisabledForUser(userHandle
7683                         .getIdentifier());
7684             } catch (RemoteException e) {
7685                 throw e.rethrowFromSystemServer();
7686             }
7687         }
7688         return true;
7689     }
7690 
7691     /**
7692      * Called by the profile owner of a managed profile so that some intents sent in the managed
7693      * profile can also be resolved in the parent, or vice versa. Only activity intents are
7694      * supported.
7695      *
7696      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7697      * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
7698      *            other profile
7699      * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
7700      *            {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
7701      * @throws SecurityException if {@code admin} is not a device or profile owner.
7702      */
addCrossProfileIntentFilter(@onNull ComponentName admin, IntentFilter filter, int flags)7703     public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
7704         throwIfParentInstance("addCrossProfileIntentFilter");
7705         if (mService != null) {
7706             try {
7707                 mService.addCrossProfileIntentFilter(admin, filter, flags);
7708             } catch (RemoteException e) {
7709                 throw e.rethrowFromSystemServer();
7710             }
7711         }
7712     }
7713 
7714     /**
7715      * Called by a profile owner of a managed profile to remove the cross-profile intent filters
7716      * that go from the managed profile to the parent, or from the parent to the managed profile.
7717      * Only removes those that have been set by the profile owner.
7718      * <p>
7719      * <em>Note</em>: A list of default cross profile intent filters are set up by the system when
7720      * the profile is created, some of them ensure the proper functioning of the profile, while
7721      * others enable sharing of data from the parent to the managed profile for user convenience.
7722      * These default intent filters are not cleared when this API is called. If the default cross
7723      * profile data sharing is not desired, they can be disabled with
7724      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE}.
7725      *
7726      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7727      * @throws SecurityException if {@code admin} is not a profile owner.
7728      */
clearCrossProfileIntentFilters(@onNull ComponentName admin)7729     public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
7730         throwIfParentInstance("clearCrossProfileIntentFilters");
7731         if (mService != null) {
7732             try {
7733                 mService.clearCrossProfileIntentFilters(admin);
7734             } catch (RemoteException e) {
7735                 throw e.rethrowFromSystemServer();
7736             }
7737         }
7738     }
7739 
7740     /**
7741      * Called by a profile or device owner to set the permitted
7742      * {@link android.accessibilityservice.AccessibilityService}. When set by
7743      * a device owner or profile owner the restriction applies to all profiles of the user the
7744      * device owner or profile owner is an admin for. By default, the user can use any accessibility
7745      * service. When zero or more packages have been added, accessibility services that are not in
7746      * the list and not part of the system can not be enabled by the user.
7747      * <p>
7748      * Calling with a null value for the list disables the restriction so that all services can be
7749      * used, calling with an empty list only allows the built-in system services. Any non-system
7750      * accessibility service that's currently enabled must be included in the list.
7751      * <p>
7752      * System accessibility services are always available to the user and this method can't
7753      * disable them.
7754      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7755      * @param packageNames List of accessibility service package names.
7756      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
7757      *         contain every enabled non-system accessibility service.
7758      * @throws SecurityException if {@code admin} is not a device or profile owner.
7759      */
setPermittedAccessibilityServices(@onNull ComponentName admin, List<String> packageNames)7760     public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
7761             List<String> packageNames) {
7762         throwIfParentInstance("setPermittedAccessibilityServices");
7763         if (mService != null) {
7764             try {
7765                 return mService.setPermittedAccessibilityServices(admin, packageNames);
7766             } catch (RemoteException e) {
7767                 throw e.rethrowFromSystemServer();
7768             }
7769         }
7770         return false;
7771     }
7772 
7773     /**
7774      * Returns the list of permitted accessibility services set by this device or profile owner.
7775      * <p>
7776      * An empty list means no accessibility services except system services are allowed. Null means
7777      * all accessibility services are allowed.
7778      *
7779      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7780      * @return List of accessiblity service package names.
7781      * @throws SecurityException if {@code admin} is not a device or profile owner.
7782      */
getPermittedAccessibilityServices(@onNull ComponentName admin)7783     public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
7784         throwIfParentInstance("getPermittedAccessibilityServices");
7785         if (mService != null) {
7786             try {
7787                 return mService.getPermittedAccessibilityServices(admin);
7788             } catch (RemoteException e) {
7789                 throw e.rethrowFromSystemServer();
7790             }
7791         }
7792         return null;
7793     }
7794 
7795     /**
7796      * Called by the system to check if a specific accessibility service is disabled by admin.
7797      *
7798      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7799      * @param packageName Accessibility service package name that needs to be checked.
7800      * @param userHandle user id the admin is running as.
7801      * @return true if the accessibility service is permitted, otherwise false.
7802      *
7803      * @hide
7804      */
isAccessibilityServicePermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)7805     public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
7806             @NonNull String packageName, int userHandle) {
7807         if (mService != null) {
7808             try {
7809                 return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
7810                         userHandle);
7811             } catch (RemoteException e) {
7812                 throw e.rethrowFromSystemServer();
7813             }
7814         }
7815         return false;
7816     }
7817 
7818     /**
7819      * Returns the list of accessibility services permitted by the device or profiles
7820      * owners of this user.
7821      *
7822      * <p>Null means all accessibility services are allowed, if a non-null list is returned
7823      * it will contain the intersection of the permitted lists for any device or profile
7824      * owners that apply to this user. It will also include any system accessibility services.
7825      *
7826      * @param userId which user to check for.
7827      * @return List of accessiblity service package names.
7828      * @hide
7829      */
7830      @SystemApi
7831      @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getPermittedAccessibilityServices(int userId)7832      public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
7833         throwIfParentInstance("getPermittedAccessibilityServices");
7834         if (mService != null) {
7835             try {
7836                 return mService.getPermittedAccessibilityServicesForUser(userId);
7837             } catch (RemoteException e) {
7838                 throw e.rethrowFromSystemServer();
7839             }
7840         }
7841         return null;
7842      }
7843 
7844     /**
7845      * Called by a profile or device owner to set the permitted input methods services for this
7846      * user. By default, the user can use any input method.
7847      * <p>
7848      * When zero or more packages have been added, input method that are not in the list and not
7849      * part of the system can not be enabled by the user. This method will fail if it is called for
7850      * a admin that is not for the foreground user or a profile of the foreground user. Any
7851      * non-system input method service that's currently enabled must be included in the list.
7852      * <p>
7853      * Calling with a null value for the list disables the restriction so that all input methods can
7854      * be used, calling with an empty list disables all but the system's own input methods.
7855      * <p>
7856      * System input methods are always available to the user - this method can't modify this.
7857      *
7858      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7859      * @param packageNames List of input method package names.
7860      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
7861      *        contain every enabled non-system input method service.
7862      * @throws SecurityException if {@code admin} is not a device or profile owner.
7863      */
setPermittedInputMethods( @onNull ComponentName admin, List<String> packageNames)7864     public boolean setPermittedInputMethods(
7865             @NonNull ComponentName admin, List<String> packageNames) {
7866         throwIfParentInstance("setPermittedInputMethods");
7867         if (mService != null) {
7868             try {
7869                 return mService.setPermittedInputMethods(admin, packageNames);
7870             } catch (RemoteException e) {
7871                 throw e.rethrowFromSystemServer();
7872             }
7873         }
7874         return false;
7875     }
7876 
7877 
7878     /**
7879      * Returns the list of permitted input methods set by this device or profile owner.
7880      * <p>
7881      * An empty list means no input methods except system input methods are allowed. Null means all
7882      * input methods are allowed.
7883      *
7884      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7885      * @return List of input method package names.
7886      * @throws SecurityException if {@code admin} is not a device or profile owner.
7887      */
getPermittedInputMethods(@onNull ComponentName admin)7888     public @Nullable List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
7889         throwIfParentInstance("getPermittedInputMethods");
7890         if (mService != null) {
7891             try {
7892                 return mService.getPermittedInputMethods(admin);
7893             } catch (RemoteException e) {
7894                 throw e.rethrowFromSystemServer();
7895             }
7896         }
7897         return null;
7898     }
7899 
7900     /**
7901      * Called by the system to check if a specific input method is disabled by admin.
7902      *
7903      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7904      * @param packageName Input method package name that needs to be checked.
7905      * @param userHandle user id the admin is running as.
7906      * @return true if the input method is permitted, otherwise false.
7907      *
7908      * @hide
7909      */
isInputMethodPermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)7910     public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
7911             @NonNull String packageName, int userHandle) {
7912         if (mService != null) {
7913             try {
7914                 return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle);
7915             } catch (RemoteException e) {
7916                 throw e.rethrowFromSystemServer();
7917             }
7918         }
7919         return false;
7920     }
7921 
7922     /**
7923      * Returns the list of input methods permitted by the device or profiles owners.
7924      *
7925      * <p>On {@link android.os.Build.VERSION_CODES#Q} and later devices, this method returns the
7926      * result for the calling user.</p>
7927      *
7928      * <p>On Android P and prior devices, this method returns the result for the current user.</p>
7929      *
7930      * <p>Null means all input methods are allowed, if a non-null list is returned
7931      * it will contain the intersection of the permitted lists for any device or profile
7932      * owners that apply to this user. It will also include any system input methods.
7933      *
7934      * @return List of input method package names.
7935      * @hide
7936      */
7937     @SystemApi
7938     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getPermittedInputMethodsForCurrentUser()7939     public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
7940         throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
7941         if (mService != null) {
7942             try {
7943                 return mService.getPermittedInputMethodsForCurrentUser();
7944             } catch (RemoteException e) {
7945                 throw e.rethrowFromSystemServer();
7946             }
7947         }
7948         return null;
7949     }
7950 
7951     /**
7952      * Called by a profile owner of a managed profile to set the packages that are allowed to use
7953      * a {@link android.service.notification.NotificationListenerService} in the primary user to
7954      * see notifications from the managed profile. By default all packages are permitted by this
7955      * policy. When zero or more packages have been added, notification listeners installed on the
7956      * primary user that are not in the list and are not part of the system won't receive events
7957      * for managed profile notifications.
7958      * <p>
7959      * Calling with a {@code null} value for the list disables the restriction so that all
7960      * notification listener services be used. Calling with an empty list disables all but the
7961      * system's own notification listeners. System notification listener services are always
7962      * available to the user.
7963      * <p>
7964      * If a device or profile owner want to stop notification listeners in their user from seeing
7965      * that user's notifications they should prevent that service from running instead (e.g. via
7966      * {@link #setApplicationHidden(ComponentName, String, boolean)})
7967      *
7968      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7969      * @param packageList List of package names to whitelist
7970      * @return true if setting the restriction succeeded. It will fail if called outside a managed
7971      * profile
7972      * @throws SecurityException if {@code admin} is not a profile owner.
7973      *
7974      * @see android.service.notification.NotificationListenerService
7975      */
setPermittedCrossProfileNotificationListeners( @onNull ComponentName admin, @Nullable List<String> packageList)7976     public boolean setPermittedCrossProfileNotificationListeners(
7977             @NonNull ComponentName admin, @Nullable List<String> packageList) {
7978         throwIfParentInstance("setPermittedCrossProfileNotificationListeners");
7979         if (mService != null) {
7980             try {
7981                 return mService.setPermittedCrossProfileNotificationListeners(admin, packageList);
7982             } catch (RemoteException e) {
7983                 throw e.rethrowFromSystemServer();
7984             }
7985         }
7986         return false;
7987     }
7988 
7989     /**
7990      * Returns the list of packages installed on the primary user that allowed to use a
7991      * {@link android.service.notification.NotificationListenerService} to receive
7992      * notifications from this managed profile, as set by the profile owner.
7993      * <p>
7994      * An empty list means no notification listener services except system ones are allowed.
7995      * A {@code null} return value indicates that all notification listeners are allowed.
7996      */
getPermittedCrossProfileNotificationListeners( @onNull ComponentName admin)7997     public @Nullable List<String> getPermittedCrossProfileNotificationListeners(
7998             @NonNull ComponentName admin) {
7999         throwIfParentInstance("getPermittedCrossProfileNotificationListeners");
8000         if (mService != null) {
8001             try {
8002                 return mService.getPermittedCrossProfileNotificationListeners(admin);
8003             } catch (RemoteException e) {
8004                 throw e.rethrowFromSystemServer();
8005             }
8006         }
8007         return null;
8008     }
8009 
8010     /**
8011      * Returns true if {@code NotificationListenerServices} from the given package are allowed to
8012      * receive events for notifications from the given user id. Can only be called by the system uid
8013      *
8014      * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List)
8015      *
8016      * @hide
8017      */
isNotificationListenerServicePermitted( @onNull String packageName, @UserIdInt int userId)8018     public boolean isNotificationListenerServicePermitted(
8019             @NonNull String packageName, @UserIdInt int userId) {
8020         if (mService != null) {
8021             try {
8022                 return mService.isNotificationListenerServicePermitted(packageName, userId);
8023             } catch (RemoteException e) {
8024                 throw e.rethrowFromSystemServer();
8025             }
8026         }
8027         return true;
8028     }
8029 
8030     /**
8031      * Get the list of apps to keep around as APKs even if no user has currently installed it. This
8032      * function can be called by a device owner or by a delegate given the
8033      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
8034      * <p>
8035      * Please note that packages returned in this method are not automatically pre-cached.
8036      *
8037      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8038      *            {@code null} if the caller is a keep uninstalled packages delegate.
8039      * @return List of package names to keep cached.
8040      * @see #setDelegatedScopes
8041      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
8042      */
getKeepUninstalledPackages(@ullable ComponentName admin)8043     public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) {
8044         throwIfParentInstance("getKeepUninstalledPackages");
8045         if (mService != null) {
8046             try {
8047                 return mService.getKeepUninstalledPackages(admin, mContext.getPackageName());
8048             } catch (RemoteException e) {
8049                 throw e.rethrowFromSystemServer();
8050             }
8051         }
8052         return null;
8053     }
8054 
8055     /**
8056      * Set a list of apps to keep around as APKs even if no user has currently installed it. This
8057      * function can be called by a device owner or by a delegate given the
8058      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
8059      *
8060      * <p>Please note that setting this policy does not imply that specified apps will be
8061      * automatically pre-cached.</p>
8062      *
8063      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8064      *            {@code null} if the caller is a keep uninstalled packages delegate.
8065      * @param packageNames List of package names to keep cached.
8066      * @throws SecurityException if {@code admin} is not a device owner.
8067      * @see #setDelegatedScopes
8068      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
8069      */
setKeepUninstalledPackages(@ullable ComponentName admin, @NonNull List<String> packageNames)8070     public void setKeepUninstalledPackages(@Nullable ComponentName admin,
8071             @NonNull List<String> packageNames) {
8072         throwIfParentInstance("setKeepUninstalledPackages");
8073         if (mService != null) {
8074             try {
8075                 mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames);
8076             } catch (RemoteException e) {
8077                 throw e.rethrowFromSystemServer();
8078             }
8079         }
8080     }
8081 
8082     /**
8083       * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
8084       */
8085     public static final int SKIP_SETUP_WIZARD = 0x0001;
8086 
8087     /**
8088      * Flag used by {@link #createAndManageUser} to specify that the user should be created
8089      * ephemeral. Ephemeral users will be removed after switching to another user or rebooting the
8090      * device.
8091      */
8092     public static final int MAKE_USER_EPHEMERAL = 0x0002;
8093 
8094     /**
8095      * Flag used by {@link #createAndManageUser} to specify that the user should be created as a
8096      * demo user.
8097      * @hide
8098      */
8099     public static final int MAKE_USER_DEMO = 0x0004;
8100 
8101     /**
8102      * Flag used by {@link #createAndManageUser} to specify that the newly created user should skip
8103      * the disabling of system apps during provisioning.
8104      */
8105     public static final int LEAVE_ALL_SYSTEM_APPS_ENABLED = 0x0010;
8106 
8107     /**
8108      * @hide
8109      */
8110     @IntDef(flag = true, prefix = { "SKIP_", "MAKE_USER_", "START_", "LEAVE_" }, value = {
8111             SKIP_SETUP_WIZARD,
8112             MAKE_USER_EPHEMERAL,
8113             MAKE_USER_DEMO,
8114             LEAVE_ALL_SYSTEM_APPS_ENABLED
8115     })
8116     @Retention(RetentionPolicy.SOURCE)
8117     public @interface CreateAndManageUserFlags {}
8118 
8119     /**
8120      * Called by a device owner to create a user with the specified name and a given component of
8121      * the calling package as profile owner. The UserHandle returned by this method should not be
8122      * persisted as user handles are recycled as users are removed and created. If you need to
8123      * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
8124      * user will not be started in the background.
8125      * <p>
8126      * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
8127      * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
8128      * be registered as an active admin on the new user. The profile owner package will be installed
8129      * on the new user.
8130      * <p>
8131      * If the adminExtras are not null, they will be stored on the device until the user is started
8132      * for the first time. Then the extras will be passed to the admin when onEnable is called.
8133      * <p>From {@link android.os.Build.VERSION_CODES#P} onwards, if targeting
8134      * {@link android.os.Build.VERSION_CODES#P}, throws {@link UserOperationException} instead of
8135      * returning {@code null} on failure.
8136      *
8137      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8138      * @param name The user's name.
8139      * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
8140      *            same package as admin, otherwise no user is created and an
8141      *            IllegalArgumentException is thrown.
8142      * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
8143      *            user.
8144      * @param flags {@link #SKIP_SETUP_WIZARD}, {@link #MAKE_USER_EPHEMERAL} and
8145      *        {@link #LEAVE_ALL_SYSTEM_APPS_ENABLED} are supported.
8146      * @see UserHandle
8147      * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
8148      *         user could not be created.
8149      * @throws SecurityException if {@code admin} is not a device owner.
8150      * @throws UserOperationException if the user could not be created and the calling app is
8151      * targeting {@link android.os.Build.VERSION_CODES#P} and running on
8152      * {@link android.os.Build.VERSION_CODES#P}.
8153      */
createAndManageUser(@onNull ComponentName admin, @NonNull String name, @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras, @CreateAndManageUserFlags int flags)8154     public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
8155             @NonNull String name,
8156             @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
8157             @CreateAndManageUserFlags int flags) {
8158         throwIfParentInstance("createAndManageUser");
8159         try {
8160             return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
8161         } catch (ServiceSpecificException e) {
8162             throw new UserOperationException(e.getMessage(), e.errorCode);
8163         } catch (RemoteException re) {
8164             throw re.rethrowFromSystemServer();
8165         }
8166     }
8167 
8168     /**
8169      * Called by a device owner to remove a user/profile and all associated data. The primary user
8170      * can not be removed.
8171      *
8172      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8173      * @param userHandle the user to remove.
8174      * @return {@code true} if the user was removed, {@code false} otherwise.
8175      * @throws SecurityException if {@code admin} is not a device owner.
8176      */
removeUser(@onNull ComponentName admin, @NonNull UserHandle userHandle)8177     public boolean removeUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) {
8178         throwIfParentInstance("removeUser");
8179         try {
8180             return mService.removeUser(admin, userHandle);
8181         } catch (RemoteException re) {
8182             throw re.rethrowFromSystemServer();
8183         }
8184     }
8185 
8186     /**
8187      * Called by a device owner to switch the specified secondary user to the foreground.
8188      *
8189      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8190      * @param userHandle the user to switch to; null will switch to primary.
8191      * @return {@code true} if the switch was successful, {@code false} otherwise.
8192      * @throws SecurityException if {@code admin} is not a device owner.
8193      * @see Intent#ACTION_USER_FOREGROUND
8194      * @see #getSecondaryUsers(ComponentName)
8195      */
switchUser(@onNull ComponentName admin, @Nullable UserHandle userHandle)8196     public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
8197         throwIfParentInstance("switchUser");
8198         try {
8199             return mService.switchUser(admin, userHandle);
8200         } catch (RemoteException re) {
8201             throw re.rethrowFromSystemServer();
8202         }
8203     }
8204 
8205     /**
8206      * Called by a device owner to start the specified secondary user in background.
8207      *
8208      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8209      * @param userHandle the user to be started in background.
8210      * @return one of the following result codes:
8211      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
8212      * {@link UserManager#USER_OPERATION_SUCCESS},
8213      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
8214      * {@link UserManager#USER_OPERATION_ERROR_MAX_RUNNING_USERS},
8215      * @throws SecurityException if {@code admin} is not a device owner.
8216      * @see #getSecondaryUsers(ComponentName)
8217      */
startUserInBackground( @onNull ComponentName admin, @NonNull UserHandle userHandle)8218     public @UserOperationResult int startUserInBackground(
8219             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
8220         throwIfParentInstance("startUserInBackground");
8221         try {
8222             return mService.startUserInBackground(admin, userHandle);
8223         } catch (RemoteException re) {
8224             throw re.rethrowFromSystemServer();
8225         }
8226     }
8227 
8228     /**
8229      * Called by a device owner to stop the specified secondary user.
8230      *
8231      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8232      * @param userHandle the user to be stopped.
8233      * @return one of the following result codes:
8234      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
8235      * {@link UserManager#USER_OPERATION_SUCCESS},
8236      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
8237      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
8238      * @throws SecurityException if {@code admin} is not a device owner.
8239      * @see #getSecondaryUsers(ComponentName)
8240      */
stopUser( @onNull ComponentName admin, @NonNull UserHandle userHandle)8241     public @UserOperationResult int stopUser(
8242             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
8243         throwIfParentInstance("stopUser");
8244         try {
8245             return mService.stopUser(admin, userHandle);
8246         } catch (RemoteException re) {
8247             throw re.rethrowFromSystemServer();
8248         }
8249     }
8250 
8251     /**
8252      * Called by a profile owner of secondary user that is affiliated with the device to stop the
8253      * calling user and switch back to primary.
8254      *
8255      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8256      * @return one of the following result codes:
8257      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
8258      * {@link UserManager#USER_OPERATION_SUCCESS},
8259      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
8260      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
8261      * @throws SecurityException if {@code admin} is not a profile owner affiliated with the device.
8262      * @see #getSecondaryUsers(ComponentName)
8263      */
logoutUser(@onNull ComponentName admin)8264     public @UserOperationResult int logoutUser(@NonNull ComponentName admin) {
8265         throwIfParentInstance("logoutUser");
8266         try {
8267             return mService.logoutUser(admin);
8268         } catch (RemoteException re) {
8269             throw re.rethrowFromSystemServer();
8270         }
8271     }
8272 
8273     /**
8274      * Called by a device owner to list all secondary users on the device. Managed profiles are not
8275      * considered as secondary users.
8276      * <p> Used for various user management APIs, including {@link #switchUser}, {@link #removeUser}
8277      * and {@link #stopUser}.
8278      *
8279      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8280      * @return list of other {@link UserHandle}s on the device.
8281      * @throws SecurityException if {@code admin} is not a device owner.
8282      * @see #removeUser(ComponentName, UserHandle)
8283      * @see #switchUser(ComponentName, UserHandle)
8284      * @see #startUserInBackground(ComponentName, UserHandle)
8285      * @see #stopUser(ComponentName, UserHandle)
8286      */
getSecondaryUsers(@onNull ComponentName admin)8287     public List<UserHandle> getSecondaryUsers(@NonNull ComponentName admin) {
8288         throwIfParentInstance("getSecondaryUsers");
8289         try {
8290             return mService.getSecondaryUsers(admin);
8291         } catch (RemoteException re) {
8292             throw re.rethrowFromSystemServer();
8293         }
8294     }
8295 
8296     /**
8297      * Checks if the profile owner is running in an ephemeral user.
8298      *
8299      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8300      * @return whether the profile owner is running in an ephemeral user.
8301      */
isEphemeralUser(@onNull ComponentName admin)8302     public boolean isEphemeralUser(@NonNull ComponentName admin) {
8303         throwIfParentInstance("isEphemeralUser");
8304         try {
8305             return mService.isEphemeralUser(admin);
8306         } catch (RemoteException re) {
8307             throw re.rethrowFromSystemServer();
8308         }
8309     }
8310 
8311     /**
8312      * Retrieves the application restrictions for a given target application running in the calling
8313      * user.
8314      * <p>
8315      * The caller must be a profile or device owner on that user, or the package allowed to manage
8316      * application restrictions via {@link #setDelegatedScopes} with the
8317      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
8318      *
8319      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
8320      *
8321      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8322      *            {@code null} if called by the application restrictions managing package.
8323      * @param packageName The name of the package to fetch restricted settings of.
8324      * @return {@link Bundle} of settings corresponding to what was set last time
8325      *         {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
8326      *         {@link Bundle} if no restrictions have been set.
8327      * @throws SecurityException if {@code admin} is not a device or profile owner.
8328      * @see #setDelegatedScopes
8329      * @see #DELEGATION_APP_RESTRICTIONS
8330      */
8331     @WorkerThread
getApplicationRestrictions( @ullable ComponentName admin, String packageName)8332     public @NonNull Bundle getApplicationRestrictions(
8333             @Nullable ComponentName admin, String packageName) {
8334         throwIfParentInstance("getApplicationRestrictions");
8335         if (mService != null) {
8336             try {
8337                 return mService.getApplicationRestrictions(admin, mContext.getPackageName(),
8338                         packageName);
8339             } catch (RemoteException e) {
8340                 throw e.rethrowFromSystemServer();
8341             }
8342         }
8343         return null;
8344     }
8345 
8346     /**
8347      * Called by a profile or device owner to set a user restriction specified by the key.
8348      * <p>
8349      * The calling device admin must be a profile or device owner; if it is not, a security
8350      * exception will be thrown.
8351      * <p>
8352      * The profile owner of an organization-owned managed profile may invoke this method on
8353      * the {@link DevicePolicyManager} instance it obtained from
8354      * {@link #getParentProfileInstance(ComponentName)}, for enforcing device-wide restrictions.
8355      * <p>
8356      * See the constants in {@link android.os.UserManager} for the list of restrictions that can
8357      * be enforced device-wide.
8358      *
8359      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8360      * @param key   The key of the restriction.
8361      * @throws SecurityException if {@code admin} is not a device or profile owner.
8362      */
addUserRestriction(@onNull ComponentName admin, @UserManager.UserRestrictionKey String key)8363     public void addUserRestriction(@NonNull ComponentName admin,
8364             @UserManager.UserRestrictionKey String key) {
8365         if (mService != null) {
8366             try {
8367                 mService.setUserRestriction(admin, key, true, mParentInstance);
8368             } catch (RemoteException e) {
8369                 throw e.rethrowFromSystemServer();
8370             }
8371         }
8372     }
8373 
8374     /**
8375      * Called by a profile or device owner to clear a user restriction specified by the key.
8376      * <p>
8377      * The calling device admin must be a profile or device owner; if it is not, a security
8378      * exception will be thrown.
8379      * <p>
8380      * The profile owner of an organization-owned managed profile may invoke this method on
8381      * the {@link DevicePolicyManager} instance it obtained from
8382      * {@link #getParentProfileInstance(ComponentName)}, for clearing device-wide restrictions.
8383      * <p>
8384      * See the constants in {@link android.os.UserManager} for the list of restrictions.
8385      *
8386      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8387      * @param key   The key of the restriction.
8388      * @throws SecurityException if {@code admin} is not a device or profile owner.
8389      */
clearUserRestriction(@onNull ComponentName admin, @UserManager.UserRestrictionKey String key)8390     public void clearUserRestriction(@NonNull ComponentName admin,
8391             @UserManager.UserRestrictionKey String key) {
8392         if (mService != null) {
8393             try {
8394                 mService.setUserRestriction(admin, key, false, mParentInstance);
8395             } catch (RemoteException e) {
8396                 throw e.rethrowFromSystemServer();
8397             }
8398         }
8399     }
8400 
8401     /**
8402      * Called by a profile or device owner to get user restrictions set with
8403      * {@link #addUserRestriction(ComponentName, String)}.
8404      * <p>
8405      * The target user may have more restrictions set by the system or other device owner / profile
8406      * owner. To get all the user restrictions currently set, use
8407      * {@link UserManager#getUserRestrictions()}.
8408      * <p>
8409      * The profile owner of an organization-owned managed profile may invoke this method on
8410      * the {@link DevicePolicyManager} instance it obtained from
8411      * {@link #getParentProfileInstance(ComponentName)}, for retrieving device-wide restrictions
8412      * it previously set with {@link #addUserRestriction(ComponentName, String)}.
8413      *
8414      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8415      * @throws SecurityException if {@code admin} is not a device or profile owner.
8416      */
getUserRestrictions(@onNull ComponentName admin)8417     public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
8418         Bundle ret = null;
8419         if (mService != null) {
8420             try {
8421                 ret = mService.getUserRestrictions(admin, mParentInstance);
8422             } catch (RemoteException e) {
8423                 throw e.rethrowFromSystemServer();
8424             }
8425         }
8426         return ret == null ? new Bundle() : ret;
8427     }
8428 
8429     /**
8430      * Called by any app to display a support dialog when a feature was disabled by an admin.
8431      * This returns an intent that can be used with {@link Context#startActivity(Intent)} to
8432      * display the dialog. It will tell the user that the feature indicated by {@code restriction}
8433      * was disabled by an admin, and include a link for more information. The default content of
8434      * the dialog can be changed by the restricting admin via
8435      * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not
8436      * set (i.e. the feature is available), then the return value will be {@code null}.
8437      * @param restriction Indicates for which feature the dialog should be displayed. Can be a
8438      *            user restriction from {@link UserManager}, e.g.
8439      *            {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants
8440      *            {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
8441      * @return Intent An intent to be used to start the dialog-activity if the restriction is
8442      *            set by an admin, or null if the restriction does not exist or no admin set it.
8443      */
createAdminSupportIntent(@onNull String restriction)8444     public Intent createAdminSupportIntent(@NonNull String restriction) {
8445         throwIfParentInstance("createAdminSupportIntent");
8446         if (mService != null) {
8447             try {
8448                 return mService.createAdminSupportIntent(restriction);
8449             } catch (RemoteException e) {
8450                 throw e.rethrowFromSystemServer();
8451             }
8452         }
8453         return null;
8454     }
8455 
8456     /**
8457      * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and
8458      * actual package file remain. This function can be called by a device owner, profile owner, or
8459      * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
8460      * {@link #setDelegatedScopes}.
8461      * <p>
8462      * This method can be called on the {@link DevicePolicyManager} instance, returned by
8463      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
8464      * of an organization-owned managed profile and the package must be a system package. If called
8465      * on the parent instance, then the package is hidden or unhidden in the personal profile.
8466      *
8467      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8468      *            {@code null} if the caller is a package access delegate.
8469      * @param packageName The name of the package to hide or unhide.
8470      * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
8471      *            unhidden.
8472      * @return boolean Whether the hidden setting of the package was successfully updated.
8473      * @throws SecurityException if {@code admin} is not a device or profile owner or if called on
8474      *            the parent profile and the {@code admin} is not a profile owner of an
8475      *            organization-owned managed profile.
8476      * @throws IllegalArgumentException if called on the parent profile and the package provided
8477      *            is not a system package.
8478      * @see #setDelegatedScopes
8479      * @see #DELEGATION_PACKAGE_ACCESS
8480      */
setApplicationHidden(@onNull ComponentName admin, String packageName, boolean hidden)8481     public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
8482             boolean hidden) {
8483         if (mService != null) {
8484             try {
8485                 return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName,
8486                         hidden, mParentInstance);
8487             } catch (RemoteException e) {
8488                 throw e.rethrowFromSystemServer();
8489             }
8490         }
8491         return false;
8492     }
8493 
8494     /**
8495      * Determine if a package is hidden. This function can be called by a device owner, profile
8496      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
8497      * {@link #setDelegatedScopes}.
8498      * <p>
8499      * This method can be called on the {@link DevicePolicyManager} instance, returned by
8500      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
8501      * of an organization-owned managed profile and the package must be a system package. If called
8502      * on the parent instance, this will determine whether the package is hidden or unhidden in the
8503      * personal profile.
8504      *
8505      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8506      *            {@code null} if the caller is a package access delegate.
8507      * @param packageName The name of the package to retrieve the hidden status of.
8508      * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
8509      * @throws SecurityException if {@code admin} is not a device or profile owner or if called on
8510      *            the parent profile and the {@code admin} is not a profile owner of an
8511      *            organization-owned managed profile.
8512      * @throws IllegalArgumentException if called on the parent profile and the package provided
8513      *            is not a system package.
8514      * @see #setDelegatedScopes
8515      * @see #DELEGATION_PACKAGE_ACCESS
8516      */
isApplicationHidden(@onNull ComponentName admin, String packageName)8517     public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
8518         if (mService != null) {
8519             try {
8520                 return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName,
8521                         mParentInstance);
8522             } catch (RemoteException e) {
8523                 throw e.rethrowFromSystemServer();
8524             }
8525         }
8526         return false;
8527     }
8528 
8529     /**
8530      * Re-enable a system app that was disabled by default when the user was initialized. This
8531      * function can be called by a device owner, profile owner, or by a delegate given the
8532      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
8533      *
8534      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8535      *            {@code null} if the caller is an enable system app delegate.
8536      * @param packageName The package to be re-enabled in the calling profile.
8537      * @throws SecurityException if {@code admin} is not a device or profile owner.
8538      * @see #setDelegatedScopes
8539      * @see #DELEGATION_PACKAGE_ACCESS
8540      */
enableSystemApp(@onNull ComponentName admin, String packageName)8541     public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
8542         throwIfParentInstance("enableSystemApp");
8543         if (mService != null) {
8544             try {
8545                 mService.enableSystemApp(admin, mContext.getPackageName(), packageName);
8546             } catch (RemoteException e) {
8547                 throw e.rethrowFromSystemServer();
8548             }
8549         }
8550     }
8551 
8552     /**
8553      * Re-enable system apps by intent that were disabled by default when the user was initialized.
8554      * This function can be called by a device owner, profile owner, or by a delegate given the
8555      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
8556      *
8557      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8558      *            {@code null} if the caller is an enable system app delegate.
8559      * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
8560      *            intent will be re-enabled in the calling profile.
8561      * @return int The number of activities that matched the intent and were installed.
8562      * @throws SecurityException if {@code admin} is not a device or profile owner.
8563      * @see #setDelegatedScopes
8564      * @see #DELEGATION_PACKAGE_ACCESS
8565      */
enableSystemApp(@onNull ComponentName admin, Intent intent)8566     public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
8567         throwIfParentInstance("enableSystemApp");
8568         if (mService != null) {
8569             try {
8570                 return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent);
8571             } catch (RemoteException e) {
8572                 throw e.rethrowFromSystemServer();
8573             }
8574         }
8575         return 0;
8576     }
8577 
8578     /**
8579      * Install an existing package that has been installed in another user, or has been kept after
8580      * removal via {@link #setKeepUninstalledPackages}.
8581      * This function can be called by a device owner, profile owner or a delegate given
8582      * the {@link #DELEGATION_INSTALL_EXISTING_PACKAGE} scope via {@link #setDelegatedScopes}.
8583      * When called in a secondary user or managed profile, the user/profile must be affiliated with
8584      * the device. See {@link #isAffiliatedUser}.
8585      *
8586      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8587      * @param packageName The package to be installed in the calling profile.
8588      * @return {@code true} if the app is installed; {@code false} otherwise.
8589      * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
8590      * an affiliated user or profile.
8591      * @see #setKeepUninstalledPackages
8592      * @see #setDelegatedScopes
8593      * @see #isAffiliatedUser
8594      * @see #DELEGATION_PACKAGE_ACCESS
8595      */
installExistingPackage(@onNull ComponentName admin, String packageName)8596     public boolean installExistingPackage(@NonNull ComponentName admin, String packageName) {
8597         throwIfParentInstance("installExistingPackage");
8598         if (mService != null) {
8599             try {
8600                 return mService.installExistingPackage(admin, mContext.getPackageName(),
8601                         packageName);
8602             } catch (RemoteException e) {
8603                 throw e.rethrowFromSystemServer();
8604             }
8605         }
8606         return false;
8607     }
8608 
8609     /**
8610      * Called by a device owner or profile owner to disable account management for a specific type
8611      * of account.
8612      * <p>
8613      * The calling device admin must be a device owner or profile owner. If it is not, a security
8614      * exception will be thrown.
8615      * <p>
8616      * When account management is disabled for an account type, adding or removing an account of
8617      * that type will not be possible.
8618      * <p>
8619      * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
8620      * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
8621      * management for a specific type is disabled.
8622      * <p>
8623      * This method may be called on the {@code DevicePolicyManager} instance returned from
8624      * {@link #getParentProfileInstance(ComponentName)} by the profile owner on an
8625      * organization-owned device, to restrict accounts that may not be managed on the primary
8626      * profile.
8627      *
8628      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8629      * @param accountType For which account management is disabled or enabled.
8630      * @param disabled The boolean indicating that account management will be disabled (true) or
8631      *            enabled (false).
8632      * @throws SecurityException if {@code admin} is not a device or profile owner.
8633      */
setAccountManagementDisabled(@onNull ComponentName admin, String accountType, boolean disabled)8634     public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
8635             boolean disabled) {
8636         if (mService != null) {
8637             try {
8638                 mService.setAccountManagementDisabled(admin, accountType, disabled,
8639                         mParentInstance);
8640             } catch (RemoteException e) {
8641                 throw e.rethrowFromSystemServer();
8642             }
8643         }
8644     }
8645 
8646     /**
8647      * Gets the array of accounts for which account management is disabled by the profile owner
8648      * or device owner.
8649      *
8650      * <p> Account management can be disabled/enabled by calling
8651      * {@link #setAccountManagementDisabled}.
8652      * <p>
8653      * This method may be called on the {@code DevicePolicyManager} instance returned from
8654      * {@link #getParentProfileInstance(ComponentName)}. Note that only a profile owner on
8655      * an organization-owned device can affect account types on the parent profile instance.
8656      *
8657      * @return a list of account types for which account management has been disabled.
8658      *
8659      * @see #setAccountManagementDisabled
8660      */
getAccountTypesWithManagementDisabled()8661     public @Nullable String[] getAccountTypesWithManagementDisabled() {
8662         return getAccountTypesWithManagementDisabledAsUser(myUserId(), mParentInstance);
8663     }
8664 
8665     /**
8666      * @see #getAccountTypesWithManagementDisabled()
8667      * Note that calling this method on the parent profile instance will return the same
8668      * value as calling it on the main {@code DevicePolicyManager} instance.
8669      * @hide
8670      */
getAccountTypesWithManagementDisabledAsUser(int userId)8671     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
8672         return getAccountTypesWithManagementDisabledAsUser(userId, false);
8673     }
8674 
8675     /**
8676      * @see #getAccountTypesWithManagementDisabled()
8677      * @hide
8678      */
getAccountTypesWithManagementDisabledAsUser( int userId, boolean parentInstance)8679     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(
8680             int userId, boolean parentInstance) {
8681         if (mService != null) {
8682             try {
8683                 return mService.getAccountTypesWithManagementDisabledAsUser(userId, parentInstance);
8684             } catch (RemoteException e) {
8685                 throw e.rethrowFromSystemServer();
8686             }
8687         }
8688 
8689         return null;
8690     }
8691 
8692     /**
8693      * Called by device owner or profile owner to set whether a secondary lockscreen needs to be
8694      * shown.
8695      *
8696      * <p>The secondary lockscreen will by displayed after the primary keyguard security screen
8697      * requirements are met. To provide the lockscreen content the DO/PO will need to provide a
8698      * service handling the {@link #ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE} intent action,
8699      * extending the {@link DevicePolicyKeyguardService} class.
8700      *
8701      * <p>Relevant interactions on the secondary lockscreen should be communicated back to the
8702      * keyguard via {@link IKeyguardCallback}, such as when the screen is ready to be dismissed.
8703      *
8704      * <p>This API, and associated APIs, can only be called by the default supervision app when it
8705      * is set as the device owner or profile owner.
8706      *
8707      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8708      * @param enabled Whether or not the lockscreen needs to be shown.
8709      * @throws SecurityException if {@code admin} is not a device or profile owner.
8710      * @see #isSecondaryLockscreenEnabled
8711      * @hide
8712      **/
8713     @SystemApi
setSecondaryLockscreenEnabled(@onNull ComponentName admin, boolean enabled)8714     public void setSecondaryLockscreenEnabled(@NonNull ComponentName admin, boolean enabled) {
8715         throwIfParentInstance("setSecondaryLockscreenEnabled");
8716         if (mService != null) {
8717             try {
8718                 mService.setSecondaryLockscreenEnabled(admin, enabled);
8719             } catch (RemoteException e) {
8720                 throw e.rethrowFromSystemServer();
8721             }
8722         }
8723     }
8724 
8725     /**
8726      * Returns whether the secondary lock screen needs to be shown.
8727      * @see #setSecondaryLockscreenEnabled
8728      * @hide
8729      */
8730     @SystemApi
isSecondaryLockscreenEnabled(@onNull UserHandle userHandle)8731     public boolean isSecondaryLockscreenEnabled(@NonNull UserHandle userHandle) {
8732         throwIfParentInstance("isSecondaryLockscreenEnabled");
8733         if (mService != null) {
8734             try {
8735                 return mService.isSecondaryLockscreenEnabled(userHandle);
8736             } catch (RemoteException e) {
8737                 throw e.rethrowFromSystemServer();
8738             }
8739         }
8740         return false;
8741     }
8742 
8743     /**
8744      * Sets which packages may enter lock task mode.
8745      * <p>
8746      * Any packages that share uid with an allowed package will also be allowed to activate lock
8747      * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
8748      * package list results in locked tasks belonging to those packages to be finished.
8749      * <p>
8750      * This function can only be called by the device owner, a profile owner of an affiliated user
8751      * or profile, or the profile owner when no device owner is set. See {@link #isAffiliatedUser}.
8752      * Any package set via this method will be cleared if the user becomes unaffiliated.
8753      *
8754      * @param packages The list of packages allowed to enter lock task mode
8755      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8756      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
8757      * affiliated user or profile, or the profile owner when no device owner is set.
8758      * @see #isAffiliatedUser
8759      * @see Activity#startLockTask()
8760      * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
8761      * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
8762      * @see UserManager#DISALLOW_CREATE_WINDOWS
8763      */
setLockTaskPackages(@onNull ComponentName admin, @NonNull String[] packages)8764     public void setLockTaskPackages(@NonNull ComponentName admin, @NonNull String[] packages)
8765             throws SecurityException {
8766         throwIfParentInstance("setLockTaskPackages");
8767         if (mService != null) {
8768             try {
8769                 mService.setLockTaskPackages(admin, packages);
8770             } catch (RemoteException e) {
8771                 throw e.rethrowFromSystemServer();
8772             }
8773         }
8774     }
8775 
8776     /**
8777      * Returns the list of packages allowed to start the lock task mode.
8778      *
8779      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
8780      * affiliated user or profile, or the profile owner when no device owner is set.
8781      * @see #isAffiliatedUser
8782      * @see #setLockTaskPackages
8783      */
getLockTaskPackages(@onNull ComponentName admin)8784     public @NonNull String[] getLockTaskPackages(@NonNull ComponentName admin) {
8785         throwIfParentInstance("getLockTaskPackages");
8786         if (mService != null) {
8787             try {
8788                 return mService.getLockTaskPackages(admin);
8789             } catch (RemoteException e) {
8790                 throw e.rethrowFromSystemServer();
8791             }
8792         }
8793         return new String[0];
8794     }
8795 
8796     /**
8797      * This function lets the caller know whether the given component is allowed to start the
8798      * lock task mode.
8799      * @param pkg The package to check
8800      */
isLockTaskPermitted(String pkg)8801     public boolean isLockTaskPermitted(String pkg) {
8802         throwIfParentInstance("isLockTaskPermitted");
8803         if (mService != null) {
8804             try {
8805                 return mService.isLockTaskPermitted(pkg);
8806             } catch (RemoteException e) {
8807                 throw e.rethrowFromSystemServer();
8808             }
8809         }
8810         return false;
8811     }
8812 
8813     /**
8814      * Sets which system features are enabled when the device runs in lock task mode. This method
8815      * doesn't affect the features when lock task mode is inactive. Any system features not included
8816      * in {@code flags} are implicitly disabled when calling this method. By default, only
8817      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS} is enabled; all the other features are disabled. To
8818      * disable the global actions dialog, call this method omitting
8819      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}.
8820      *
8821      * <p>This method can only be called by the device owner, a profile owner of an affiliated
8822      * user or profile, or the profile owner when no device owner is set. See
8823      * {@link #isAffiliatedUser}.
8824      * Any features set using this method are cleared if the user becomes unaffiliated.
8825      *
8826      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8827      * @param flags The system features enabled during lock task mode.
8828      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
8829      * affiliated user or profile, or the profile owner when no device owner is set.
8830      * @see #isAffiliatedUser
8831      **/
setLockTaskFeatures(@onNull ComponentName admin, @LockTaskFeature int flags)8832     public void setLockTaskFeatures(@NonNull ComponentName admin, @LockTaskFeature int flags) {
8833         throwIfParentInstance("setLockTaskFeatures");
8834         if (mService != null) {
8835             try {
8836                 mService.setLockTaskFeatures(admin, flags);
8837             } catch (RemoteException e) {
8838                 throw e.rethrowFromSystemServer();
8839             }
8840         }
8841     }
8842 
8843     /**
8844      * Gets which system features are enabled for LockTask mode.
8845      *
8846      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8847      * @return bitfield of flags. See {@link #setLockTaskFeatures(ComponentName, int)} for a list.
8848      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
8849      * affiliated user or profile, or the profile owner when no device owner is set.
8850      * @see #isAffiliatedUser
8851      * @see #setLockTaskFeatures
8852      */
getLockTaskFeatures(@onNull ComponentName admin)8853     public @LockTaskFeature int getLockTaskFeatures(@NonNull ComponentName admin) {
8854         throwIfParentInstance("getLockTaskFeatures");
8855         if (mService != null) {
8856             try {
8857                 return mService.getLockTaskFeatures(admin);
8858             } catch (RemoteException e) {
8859                 throw e.rethrowFromSystemServer();
8860             }
8861         }
8862         return 0;
8863     }
8864 
8865     /**
8866      * This method is mostly deprecated.
8867      * Most of the settings that still have an effect have dedicated setter methods or user
8868      * restrictions. See individual settings for details.
8869      * <p>
8870      * Called by device owner to update {@link android.provider.Settings.Global} settings.
8871      * Validation that the value of the setting is in the correct form for the setting type should
8872      * be performed by the caller.
8873      * <p>
8874      * The settings that can be updated with this method are:
8875      * <ul>
8876      * <li>{@link android.provider.Settings.Global#ADB_ENABLED} : use
8877      * {@link UserManager#DISALLOW_DEBUGGING_FEATURES} instead to restrict users from enabling
8878      * debugging features and this setting to turn adb on.</li>
8879      * <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
8880      * <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only
8881      * available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
8882      * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
8883      * <li>{@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This
8884      * setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
8885      * </ul>
8886      * <p>
8887      * The following settings used to be supported, but can be controlled in other ways:
8888      * <ul>
8889      * <li>{@link android.provider.Settings.Global#AUTO_TIME} : Use {@link #setAutoTimeEnabled} and
8890      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} instead.</li>
8891      * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE} : Use
8892      * {@link #setAutoTimeZoneEnabled} and {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
8893      * instead.</li>
8894      * <li>{@link android.provider.Settings.Global#DATA_ROAMING} : Use
8895      * {@link UserManager#DISALLOW_DATA_ROAMING} instead.</li>
8896      * </ul>
8897      * <p>
8898      * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
8899      * <ul>
8900      * <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use
8901      * {@link android.bluetooth.BluetoothAdapter#enable()} and
8902      * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
8903      * <li>{@link android.provider.Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
8904      * <li>{@link android.provider.Settings.Global#MODE_RINGER}. Use
8905      * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
8906      * <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li>
8907      * <li>{@link android.provider.Settings.Global#WIFI_ON}. Use
8908      * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
8909      * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}. No longer has effect.</li>
8910      * </ul>
8911      *
8912      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8913      * @param setting The name of the setting to update.
8914      * @param value The value to update the setting to.
8915      * @throws SecurityException if {@code admin} is not a device owner.
8916      */
setGlobalSetting(@onNull ComponentName admin, String setting, String value)8917     public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
8918         throwIfParentInstance("setGlobalSetting");
8919         if (mService != null) {
8920             try {
8921                 mService.setGlobalSetting(admin, setting, value);
8922             } catch (RemoteException e) {
8923                 throw e.rethrowFromSystemServer();
8924             }
8925         }
8926     }
8927 
8928     /** @hide */
8929     @StringDef({
8930             Settings.System.SCREEN_BRIGHTNESS_MODE,
8931             Settings.System.SCREEN_BRIGHTNESS,
8932             Settings.System.SCREEN_BRIGHTNESS_FLOAT,
8933             Settings.System.SCREEN_OFF_TIMEOUT
8934     })
8935     @Retention(RetentionPolicy.SOURCE)
8936     public @interface SystemSettingsWhitelist {}
8937 
8938     /**
8939      * Called by a device or profile owner to update {@link android.provider.Settings.System}
8940      * settings. Validation that the value of the setting is in the correct form for the setting
8941      * type should be performed by the caller.
8942      * <p>
8943      * The settings that can be updated by a device owner or profile owner of secondary user with
8944      * this method are:
8945      * <ul>
8946      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS}</li>
8947      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS_MODE}</li>
8948      * <li>{@link android.provider.Settings.System#SCREEN_OFF_TIMEOUT}</li>
8949      * </ul>
8950      * <p>
8951      *
8952      * @see android.provider.Settings.System#SCREEN_OFF_TIMEOUT
8953      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8954      * @param setting The name of the setting to update.
8955      * @param value The value to update the setting to.
8956      * @throws SecurityException if {@code admin} is not a device or profile owner.
8957      */
setSystemSetting(@onNull ComponentName admin, @NonNull @SystemSettingsWhitelist String setting, String value)8958     public void setSystemSetting(@NonNull ComponentName admin,
8959             @NonNull @SystemSettingsWhitelist String setting, String value) {
8960         throwIfParentInstance("setSystemSetting");
8961         if (mService != null) {
8962             try {
8963                 mService.setSystemSetting(admin, setting, value);
8964             } catch (RemoteException e) {
8965                 throw e.rethrowFromSystemServer();
8966             }
8967         }
8968     }
8969 
8970     /**
8971      * Called by a device owner or a profile owner of an organization-owned managed profile to
8972      * control whether the user can change networks configured by the admin.
8973      * <p>
8974      * WiFi network configuration lockdown is controlled by a global settings
8975      * {@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN} and calling
8976      * this API effectively modifies the global settings. Previously device owners can also
8977      * control this directly via {@link #setGlobalSetting} but they are recommended to switch
8978      * to this API.
8979      *
8980      * @param admin             admin Which {@link DeviceAdminReceiver} this request is associated
8981      *                          with.
8982      * @param lockdown Whether the admin configured networks should be unmodifiable by the
8983      *                          user.
8984      * @throws SecurityException if caller is not a device owner or a profile owner of an
8985      *                           organization-owned managed profile.
8986      */
setConfiguredNetworksLockdownState(@onNull ComponentName admin, boolean lockdown)8987     public void setConfiguredNetworksLockdownState(@NonNull ComponentName admin, boolean lockdown) {
8988         throwIfParentInstance("setConfiguredNetworksLockdownState");
8989         if (mService != null) {
8990             try {
8991                 mService.setConfiguredNetworksLockdownState(admin, lockdown);
8992             } catch (RemoteException e) {
8993                 throw e.rethrowFromSystemServer();
8994             }
8995         }
8996     }
8997 
8998     /**
8999      * Called by a device owner or a profile owner of an organization-owned managed profile to
9000      * determine whether the user is prevented from modifying networks configured by the admin.
9001      *
9002      * @param admin             admin Which {@link DeviceAdminReceiver} this request is associated
9003      *                          with.
9004      * @throws SecurityException if caller is not a device owner or a profile owner of an
9005      *                           organization-owned managed profile.
9006      */
hasLockdownAdminConfiguredNetworks(@onNull ComponentName admin)9007     public boolean hasLockdownAdminConfiguredNetworks(@NonNull ComponentName admin) {
9008         throwIfParentInstance("hasLockdownAdminConfiguredNetworks");
9009         if (mService != null) {
9010             try {
9011                 return mService.hasLockdownAdminConfiguredNetworks(admin);
9012             } catch (RemoteException e) {
9013                 throw e.rethrowFromSystemServer();
9014             }
9015         }
9016         return false;
9017     }
9018 
9019     /**
9020      * Called by a device owner or a profile owner of an organization-owned managed
9021      * profile to set the system wall clock time. This only takes effect if called when
9022      * {@link android.provider.Settings.Global#AUTO_TIME} is 0, otherwise {@code false}
9023      * will be returned.
9024      *
9025      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
9026      * @param millis time in milliseconds since the Epoch
9027      * @return {@code true} if set time succeeded, {@code false} otherwise.
9028      * @throws SecurityException if {@code admin} is not a device owner or a profile owner
9029      * of an organization-owned managed profile.
9030      */
setTime(@onNull ComponentName admin, long millis)9031     public boolean setTime(@NonNull ComponentName admin, long millis) {
9032         throwIfParentInstance("setTime");
9033         if (mService != null) {
9034             try {
9035                 return mService.setTime(admin, millis);
9036             } catch (RemoteException e) {
9037                 throw e.rethrowFromSystemServer();
9038             }
9039         }
9040         return false;
9041     }
9042 
9043     /**
9044      * Called by a device owner or a profile owner of an organization-owned managed
9045      * profile to set the system's persistent default time zone. This only takes
9046      * effect if called when {@link android.provider.Settings.Global#AUTO_TIME_ZONE}
9047      * is 0, otherwise {@code false} will be returned.
9048      *
9049      * @see android.app.AlarmManager#setTimeZone(String)
9050      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
9051      * @param timeZone one of the Olson ids from the list returned by
9052      *     {@link java.util.TimeZone#getAvailableIDs}
9053      * @return {@code true} if set timezone succeeded, {@code false} otherwise.
9054      * @throws SecurityException if {@code admin} is not a device owner or a profile owner
9055      * of an organization-owned managed profile.
9056      */
setTimeZone(@onNull ComponentName admin, String timeZone)9057     public boolean setTimeZone(@NonNull ComponentName admin, String timeZone) {
9058         throwIfParentInstance("setTimeZone");
9059         if (mService != null) {
9060             try {
9061                 return mService.setTimeZone(admin, timeZone);
9062             } catch (RemoteException e) {
9063                 throw e.rethrowFromSystemServer();
9064             }
9065         }
9066         return false;
9067     }
9068 
9069     /**
9070      * Called by device owners to set the user's master location setting.
9071      *
9072      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
9073      * @param locationEnabled whether location should be enabled or disabled
9074      * @throws SecurityException if {@code admin} is not a device owner.
9075      */
setLocationEnabled(@onNull ComponentName admin, boolean locationEnabled)9076     public void setLocationEnabled(@NonNull ComponentName admin, boolean locationEnabled) {
9077         throwIfParentInstance("setLocationEnabled");
9078         if (mService != null) {
9079             try {
9080                 mService.setLocationEnabled(admin, locationEnabled);
9081             } catch (RemoteException e) {
9082                 throw e.rethrowFromSystemServer();
9083             }
9084         }
9085     }
9086 
9087     /**
9088      * This method is mostly deprecated.
9089      * Most of the settings that still have an effect have dedicated setter methods
9090      * (e.g. {@link #setLocationEnabled}) or user restrictions.
9091      * <p>
9092      *
9093      * Called by profile or device owners to update {@link android.provider.Settings.Secure}
9094      * settings. Validation that the value of the setting is in the correct form for the setting
9095      * type should be performed by the caller.
9096      * <p>
9097      * The settings that can be updated by a profile or device owner with this method are:
9098      * <ul>
9099      * <li>{@link android.provider.Settings.Secure#DEFAULT_INPUT_METHOD}</li>
9100      * <li>{@link android.provider.Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
9101      * </ul>
9102      * <p>
9103      * A device owner can additionally update the following settings:
9104      * <ul>
9105      * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}, but see note below.</li>
9106      * </ul>
9107      *
9108      * <strong>Note: Starting from Android O, apps should no longer call this method with the
9109      * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is
9110      * deprecated. Instead, device owners or profile owners should use the restriction
9111      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}.
9112      * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method
9113      * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS},
9114      * an {@link UnsupportedOperationException} is thrown.
9115      *
9116      * Starting from Android Q, the device and profile owner can also call
9117      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY} to restrict unknown sources for
9118      * all users.
9119      * </strong>
9120      *
9121      * <strong>Note: Starting from Android R, apps should no longer call this method with the
9122      * setting {@link android.provider.Settings.Secure#LOCATION_MODE}, which is deprecated. Instead,
9123      * device owners should call {@link #setLocationEnabled(ComponentName, boolean)}. This will be
9124      * enforced for all apps targeting Android R or above.
9125      * </strong>
9126      *
9127      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9128      * @param setting The name of the setting to update.
9129      * @param value The value to update the setting to.
9130      * @throws SecurityException if {@code admin} is not a device or profile owner.
9131      */
setSecureSetting(@onNull ComponentName admin, String setting, String value)9132     public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
9133         throwIfParentInstance("setSecureSetting");
9134 
9135         if (mService != null) {
9136             try {
9137                 mService.setSecureSetting(admin, setting, value);
9138             } catch (RemoteException e) {
9139                 throw e.rethrowFromSystemServer();
9140             }
9141         }
9142     }
9143 
9144     /**
9145      * Designates a specific service component as the provider for making permission requests of a
9146      * local or remote administrator of the user.
9147      * <p/>
9148      * Only a profile owner can designate the restrictions provider.
9149      *
9150      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9151      * @param provider The component name of the service that implements
9152      *            {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
9153      *            provider previously assigned.
9154      * @throws SecurityException if {@code admin} is not a device or profile owner.
9155      */
setRestrictionsProvider(@onNull ComponentName admin, @Nullable ComponentName provider)9156     public void setRestrictionsProvider(@NonNull ComponentName admin,
9157             @Nullable ComponentName provider) {
9158         throwIfParentInstance("setRestrictionsProvider");
9159         if (mService != null) {
9160             try {
9161                 mService.setRestrictionsProvider(admin, provider);
9162             } catch (RemoteException re) {
9163                 throw re.rethrowFromSystemServer();
9164             }
9165         }
9166     }
9167 
9168     /**
9169      * Called by profile or device owners to set the master volume mute on or off.
9170      * This has no effect when set on a managed profile.
9171      *
9172      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9173      * @param on {@code true} to mute master volume, {@code false} to turn mute off.
9174      * @throws SecurityException if {@code admin} is not a device or profile owner.
9175      */
setMasterVolumeMuted(@onNull ComponentName admin, boolean on)9176     public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
9177         throwIfParentInstance("setMasterVolumeMuted");
9178         if (mService != null) {
9179             try {
9180                 mService.setMasterVolumeMuted(admin, on);
9181             } catch (RemoteException re) {
9182                 throw re.rethrowFromSystemServer();
9183             }
9184         }
9185     }
9186 
9187     /**
9188      * Called by profile or device owners to check whether the master volume mute is on or off.
9189      *
9190      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9191      * @return {@code true} if master volume is muted, {@code false} if it's not.
9192      * @throws SecurityException if {@code admin} is not a device or profile owner.
9193      */
isMasterVolumeMuted(@onNull ComponentName admin)9194     public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
9195         throwIfParentInstance("isMasterVolumeMuted");
9196         if (mService != null) {
9197             try {
9198                 return mService.isMasterVolumeMuted(admin);
9199             } catch (RemoteException re) {
9200                 throw re.rethrowFromSystemServer();
9201             }
9202         }
9203         return false;
9204     }
9205 
9206     /**
9207      * Change whether a user can uninstall a package. This function can be called by a device owner,
9208      * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via
9209      * {@link #setDelegatedScopes}.
9210      *
9211      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9212      *             {@code null} if the caller is a block uninstall delegate.
9213      * @param packageName package to change.
9214      * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
9215      * @throws SecurityException if {@code admin} is not a device or profile owner.
9216      * @see #setDelegatedScopes
9217      * @see #DELEGATION_BLOCK_UNINSTALL
9218      */
setUninstallBlocked(@ullable ComponentName admin, String packageName, boolean uninstallBlocked)9219     public void setUninstallBlocked(@Nullable ComponentName admin, String packageName,
9220             boolean uninstallBlocked) {
9221         throwIfParentInstance("setUninstallBlocked");
9222         if (mService != null) {
9223             try {
9224                 mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName,
9225                     uninstallBlocked);
9226             } catch (RemoteException re) {
9227                 throw re.rethrowFromSystemServer();
9228             }
9229         }
9230     }
9231 
9232     /**
9233      * Check whether the user has been blocked by device policy from uninstalling a package.
9234      * Requires the caller to be the profile owner if checking a specific admin's policy.
9235      * <p>
9236      * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
9237      * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
9238      * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
9239      * will cause a NullPointerException to be raised.
9240      *
9241      * @param admin The name of the admin component whose blocking policy will be checked, or
9242      *            {@code null} to check whether any admin has blocked the uninstallation.
9243      * @param packageName package to check.
9244      * @return true if uninstallation is blocked.
9245      * @throws SecurityException if {@code admin} is not a device or profile owner.
9246      */
isUninstallBlocked(@ullable ComponentName admin, String packageName)9247     public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
9248         throwIfParentInstance("isUninstallBlocked");
9249         if (mService != null) {
9250             try {
9251                 return mService.isUninstallBlocked(admin, packageName);
9252             } catch (RemoteException re) {
9253                 throw re.rethrowFromSystemServer();
9254             }
9255         }
9256         return false;
9257     }
9258 
9259     /**
9260      * Called by the profile owner of a managed profile to enable widget providers from a given
9261      * package to be available in the parent profile. As a result the user will be able to add
9262      * widgets from the white-listed package running under the profile to a widget host which runs
9263      * under the parent profile, for example the home screen. Note that a package may have zero or
9264      * more provider components, where each component provides a different widget type.
9265      * <p>
9266      * <strong>Note:</strong> By default no widget provider package is white-listed.
9267      *
9268      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9269      * @param packageName The package from which widget providers are white-listed.
9270      * @return Whether the package was added.
9271      * @throws SecurityException if {@code admin} is not a profile owner.
9272      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
9273      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
9274      */
addCrossProfileWidgetProvider(@onNull ComponentName admin, String packageName)9275     public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
9276         throwIfParentInstance("addCrossProfileWidgetProvider");
9277         if (mService != null) {
9278             try {
9279                 return mService.addCrossProfileWidgetProvider(admin, packageName);
9280             } catch (RemoteException re) {
9281                 throw re.rethrowFromSystemServer();
9282             }
9283         }
9284         return false;
9285     }
9286 
9287     /**
9288      * Called by the profile owner of a managed profile to disable widget providers from a given
9289      * package to be available in the parent profile. For this method to take effect the package
9290      * should have been added via
9291      * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
9292      * <p>
9293      * <strong>Note:</strong> By default no widget provider package is white-listed.
9294      *
9295      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9296      * @param packageName The package from which widget providers are no longer white-listed.
9297      * @return Whether the package was removed.
9298      * @throws SecurityException if {@code admin} is not a profile owner.
9299      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
9300      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
9301      */
removeCrossProfileWidgetProvider( @onNull ComponentName admin, String packageName)9302     public boolean removeCrossProfileWidgetProvider(
9303             @NonNull ComponentName admin, String packageName) {
9304         throwIfParentInstance("removeCrossProfileWidgetProvider");
9305         if (mService != null) {
9306             try {
9307                 return mService.removeCrossProfileWidgetProvider(admin, packageName);
9308             } catch (RemoteException re) {
9309                 throw re.rethrowFromSystemServer();
9310             }
9311         }
9312         return false;
9313     }
9314 
9315     /**
9316      * Called by the profile owner of a managed profile to query providers from which packages are
9317      * available in the parent profile.
9318      *
9319      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9320      * @return The white-listed package list.
9321      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
9322      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
9323      * @throws SecurityException if {@code admin} is not a profile owner.
9324      */
getCrossProfileWidgetProviders(@onNull ComponentName admin)9325     public @NonNull List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
9326         throwIfParentInstance("getCrossProfileWidgetProviders");
9327         if (mService != null) {
9328             try {
9329                 List<String> providers = mService.getCrossProfileWidgetProviders(admin);
9330                 if (providers != null) {
9331                     return providers;
9332                 }
9333             } catch (RemoteException re) {
9334                 throw re.rethrowFromSystemServer();
9335             }
9336         }
9337         return Collections.emptyList();
9338     }
9339 
9340     /**
9341      * Called by profile or device owners to set the user's photo.
9342      *
9343      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9344      * @param icon the bitmap to set as the photo.
9345      * @throws SecurityException if {@code admin} is not a device or profile owner.
9346      */
setUserIcon(@onNull ComponentName admin, Bitmap icon)9347     public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
9348         throwIfParentInstance("setUserIcon");
9349         try {
9350             mService.setUserIcon(admin, icon);
9351         } catch (RemoteException re) {
9352             throw re.rethrowFromSystemServer();
9353         }
9354     }
9355 
9356     /**
9357      * Called by device owners or profile owners of an organization-owned managed profile to to set
9358      * a local system update policy. When a new policy is set,
9359      * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
9360      * <p>
9361      * If the supplied system update policy has freeze periods set but the freeze periods do not
9362      * meet 90-day maximum length or 60-day minimum separation requirement set out in
9363      * {@link SystemUpdatePolicy#setFreezePeriods},
9364      * {@link SystemUpdatePolicy.ValidationFailedException} will the thrown. Note that the system
9365      * keeps a record of freeze periods the device experienced previously, and combines them with
9366      * the new freeze periods to be set when checking the maximum freeze length and minimum freeze
9367      * separation constraints. As a result, freeze periods that passed validation during
9368      * {@link SystemUpdatePolicy#setFreezePeriods} might fail the additional checks here due to
9369      * the freeze period history. If this is causing issues during development,
9370      * {@code adb shell dpm clear-freeze-period-record} can be used to clear the record.
9371      *
9372      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
9373      *            components in the device owner package can set system update policies and the most
9374      *            recent policy takes effect.
9375      * @param policy the new policy, or {@code null} to clear the current policy.
9376      * @throws SecurityException if {@code admin} is not a device owner or a profile owner of an
9377      *      organization-owned managed profile.
9378      * @throws IllegalArgumentException if the policy type or maintenance window is not valid.
9379      * @throws SystemUpdatePolicy.ValidationFailedException if the policy's freeze period does not
9380      *             meet the requirement.
9381      * @see SystemUpdatePolicy
9382      * @see SystemUpdatePolicy#setFreezePeriods(List)
9383      */
setSystemUpdatePolicy(@onNull ComponentName admin, SystemUpdatePolicy policy)9384     public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
9385         throwIfParentInstance("setSystemUpdatePolicy");
9386         if (mService != null) {
9387             try {
9388                 mService.setSystemUpdatePolicy(admin, policy);
9389             } catch (RemoteException re) {
9390                 throw re.rethrowFromSystemServer();
9391             }
9392         }
9393     }
9394 
9395     /**
9396      * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
9397      *
9398      * @return The current policy object, or {@code null} if no policy is set.
9399      */
getSystemUpdatePolicy()9400     public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
9401         throwIfParentInstance("getSystemUpdatePolicy");
9402         if (mService != null) {
9403             try {
9404                 return mService.getSystemUpdatePolicy();
9405             } catch (RemoteException re) {
9406                 throw re.rethrowFromSystemServer();
9407             }
9408         }
9409         return null;
9410     }
9411 
9412     /**
9413      * Reset record of previous system update freeze period the device went through.
9414      * Only callable by ADB.
9415      * @hide
9416      */
clearSystemUpdatePolicyFreezePeriodRecord()9417     public void clearSystemUpdatePolicyFreezePeriodRecord() {
9418         throwIfParentInstance("clearSystemUpdatePolicyFreezePeriodRecord");
9419         if (mService == null) {
9420             return;
9421         }
9422         try {
9423             mService.clearSystemUpdatePolicyFreezePeriodRecord();
9424         } catch (RemoteException re) {
9425             throw re.rethrowFromSystemServer();
9426         }
9427     }
9428 
9429     /**
9430      * Called by a device owner or profile owner of secondary users that is affiliated with the
9431      * device to disable the keyguard altogether.
9432      * <p>
9433      * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
9434      * type. However, this call has no effect if a password, pin or pattern is currently set. If a
9435      * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
9436      * disabled.
9437      *
9438      * <p>
9439      * As of {@link android.os.Build.VERSION_CODES#P}, this call also dismisses the
9440      * keyguard if it is currently shown.
9441      *
9442      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9443      * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
9444      * @return {@code false} if attempting to disable the keyguard while a lock password was in
9445      *         place. {@code true} otherwise.
9446      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
9447      * secondary user that is affiliated with the device.
9448      * @see #isAffiliatedUser
9449      * @see #getSecondaryUsers
9450      */
setKeyguardDisabled(@onNull ComponentName admin, boolean disabled)9451     public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
9452         throwIfParentInstance("setKeyguardDisabled");
9453         try {
9454             return mService.setKeyguardDisabled(admin, disabled);
9455         } catch (RemoteException re) {
9456             throw re.rethrowFromSystemServer();
9457         }
9458     }
9459 
9460     /**
9461      * Called by device owner or profile owner of secondary users that is affiliated with the
9462      * device to disable the status bar. Disabling the status bar blocks notifications and quick
9463      * settings.
9464      * <p>
9465      * <strong>Note:</strong> This method has no effect for LockTask mode. The behavior of the
9466      * status bar in LockTask mode can be configured with
9467      * {@link #setLockTaskFeatures(ComponentName, int)}. Calls to this method when the device is in
9468      * LockTask mode will be registered, but will only take effect when the device leaves LockTask
9469      * mode.
9470      *
9471      * <p>This policy does not have any effect while on the lock screen, where the status bar will
9472      * not be disabled. Using LockTask instead of this method is recommended.
9473      *
9474      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9475      * @param disabled {@code true} disables the status bar, {@code false} reenables it.
9476      * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
9477      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
9478      * secondary user that is affiliated with the device.
9479      * @see #isAffiliatedUser
9480      * @see #getSecondaryUsers
9481      */
setStatusBarDisabled(@onNull ComponentName admin, boolean disabled)9482     public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
9483         throwIfParentInstance("setStatusBarDisabled");
9484         try {
9485             return mService.setStatusBarDisabled(admin, disabled);
9486         } catch (RemoteException re) {
9487             throw re.rethrowFromSystemServer();
9488         }
9489     }
9490 
9491     /**
9492      * Called by the system update service to notify device and profile owners of pending system
9493      * updates.
9494      *
9495      * This method should only be used when it is unknown whether the pending system
9496      * update is a security patch. Otherwise, use
9497      * {@link #notifyPendingSystemUpdate(long, boolean)}.
9498      *
9499      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
9500      *         indicating when the current pending update was first available. {@code -1} if no
9501      *         update is available.
9502      * @see #notifyPendingSystemUpdate(long, boolean)
9503      * @hide
9504      */
9505     @SystemApi
9506     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime)9507     public void notifyPendingSystemUpdate(long updateReceivedTime) {
9508         throwIfParentInstance("notifyPendingSystemUpdate");
9509         if (mService != null) {
9510             try {
9511                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime));
9512             } catch (RemoteException re) {
9513                 throw re.rethrowFromSystemServer();
9514             }
9515         }
9516     }
9517 
9518     /**
9519      * Called by the system update service to notify device and profile owners of pending system
9520      * updates.
9521      *
9522      * This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
9523      * when it is known whether the pending system update is a security patch.
9524      *
9525      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
9526      *         indicating when the current pending update was first available. {@code -1} if no
9527      *         update is available.
9528      * @param isSecurityPatch {@code true} if this system update is purely a security patch;
9529      *         {@code false} if not.
9530      * @see #notifyPendingSystemUpdate(long)
9531      * @hide
9532      */
9533     @SystemApi
9534     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch)9535     public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) {
9536         throwIfParentInstance("notifyPendingSystemUpdate");
9537         if (mService != null) {
9538             try {
9539                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime,
9540                         isSecurityPatch));
9541             } catch (RemoteException re) {
9542                 throw re.rethrowFromSystemServer();
9543             }
9544         }
9545     }
9546 
9547     /**
9548      * Called by device or profile owners to get information about a pending system update.
9549      *
9550      * @param admin Which profile or device owner this request is associated with.
9551      * @return Information about a pending system update or {@code null} if no update pending.
9552      * @throws SecurityException if {@code admin} is not a device or profile owner.
9553      * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long)
9554      */
getPendingSystemUpdate(@onNull ComponentName admin)9555     public @Nullable SystemUpdateInfo getPendingSystemUpdate(@NonNull ComponentName admin) {
9556         throwIfParentInstance("getPendingSystemUpdate");
9557         try {
9558             return mService.getPendingSystemUpdate(admin);
9559         } catch (RemoteException re) {
9560             throw re.rethrowFromSystemServer();
9561         }
9562     }
9563 
9564     /**
9565      * Set the default response for future runtime permission requests by applications. This
9566      * function can be called by a device owner, profile owner, or by a delegate given the
9567      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
9568      * The policy can allow for normal operation which prompts the user to grant a permission, or
9569      * can allow automatic granting or denying of runtime permission requests by an application.
9570      * This also applies to new permissions declared by app updates. When a permission is denied or
9571      * granted this way, the effect is equivalent to setting the permission * grant state via
9572      * {@link #setPermissionGrantState}.
9573      * <p/>
9574      * As this policy only acts on runtime permission requests, it only applies to applications
9575      * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
9576      *
9577      * @param admin Which profile or device owner this request is associated with.
9578      * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
9579      *            {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
9580      * @throws SecurityException if {@code admin} is not a device or profile owner.
9581      * @see #setPermissionGrantState
9582      * @see #setDelegatedScopes
9583      * @see #DELEGATION_PERMISSION_GRANT
9584      */
setPermissionPolicy(@onNull ComponentName admin, int policy)9585     public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
9586         throwIfParentInstance("setPermissionPolicy");
9587         try {
9588             mService.setPermissionPolicy(admin, mContext.getPackageName(), policy);
9589         } catch (RemoteException re) {
9590             throw re.rethrowFromSystemServer();
9591         }
9592     }
9593 
9594     /**
9595      * Returns the current runtime permission policy set by the device or profile owner. The
9596      * default is {@link #PERMISSION_POLICY_PROMPT}.
9597      *
9598      * @param admin Which profile or device owner this request is associated with.
9599      * @return the current policy for future permission requests.
9600      */
getPermissionPolicy(ComponentName admin)9601     public int getPermissionPolicy(ComponentName admin) {
9602         throwIfParentInstance("getPermissionPolicy");
9603         try {
9604             return mService.getPermissionPolicy(admin);
9605         } catch (RemoteException re) {
9606             throw re.rethrowFromSystemServer();
9607         }
9608     }
9609 
9610     /**
9611      * Sets the grant state of a runtime permission for a specific application. The state can be
9612      * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
9613      * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
9614      * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
9615      * the permission is granted and the user cannot manage it through the UI. This method can only
9616      * be called by a profile owner, device owner, or a delegate given the
9617      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
9618      * <p/>
9619      * Note that user cannot manage other permissions in the affected group through the UI
9620      * either and their granted state will be kept as the current value. Thus, it's recommended that
9621      * you set the grant state of all the permissions in the affected group.
9622      * <p/>
9623      * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
9624      * the permission. It retains the previous grant, if any.
9625      * <p/>
9626      * Device admins with a {@code targetSdkVersion} &lt; {@link android.os.Build.VERSION_CODES#Q}
9627      * cannot grant and revoke permissions for applications built with a {@code targetSdkVersion}
9628      * &lt; {@link android.os.Build.VERSION_CODES#M}.
9629      * <p/>
9630      * Admins with a {@code targetSdkVersion} &ge; {@link android.os.Build.VERSION_CODES#Q} can
9631      * grant and revoke permissions of all apps. Similar to the user revoking a permission from a
9632      * application built with a {@code targetSdkVersion} &lt;
9633      * {@link android.os.Build.VERSION_CODES#M} the app-op matching the permission is set to
9634      * {@link android.app.AppOpsManager#MODE_IGNORED}, but the permission stays granted.
9635      *
9636      * @param admin Which profile or device owner this request is associated with.
9637      * @param packageName The application to grant or revoke a permission to.
9638      * @param permission The permission to grant or revoke.
9639      * @param grantState The permission grant state which is one of
9640      *            {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
9641      *            {@link #PERMISSION_GRANT_STATE_GRANTED},
9642      * @return whether the permission was successfully granted or revoked.
9643      * @throws SecurityException if {@code admin} is not a device or profile owner.
9644      * @see #PERMISSION_GRANT_STATE_DENIED
9645      * @see #PERMISSION_GRANT_STATE_DEFAULT
9646      * @see #PERMISSION_GRANT_STATE_GRANTED
9647      * @see #setDelegatedScopes
9648      * @see #DELEGATION_PERMISSION_GRANT
9649      */
setPermissionGrantState(@onNull ComponentName admin, @NonNull String packageName, @NonNull String permission, @PermissionGrantState int grantState)9650     public boolean setPermissionGrantState(@NonNull ComponentName admin,
9651             @NonNull String packageName, @NonNull String permission,
9652             @PermissionGrantState int grantState) {
9653         throwIfParentInstance("setPermissionGrantState");
9654         try {
9655             CompletableFuture<Boolean> result = new CompletableFuture<>();
9656 
9657             mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName,
9658                     permission, grantState, new RemoteCallback((b) -> result.complete(b != null)));
9659 
9660             // Timeout
9661             BackgroundThread.getHandler().sendMessageDelayed(
9662                     obtainMessage(CompletableFuture::complete, result, false),
9663                     20_000);
9664 
9665             return result.get();
9666         } catch (RemoteException re) {
9667             throw re.rethrowFromSystemServer();
9668         } catch (InterruptedException | ExecutionException e) {
9669             throw new RuntimeException(e);
9670         }
9671     }
9672 
9673     /**
9674      * Returns the current grant state of a runtime permission for a specific application. This
9675      * function can be called by a device owner, profile owner, or by a delegate given the
9676      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
9677      *
9678      * @param admin Which profile or device owner this request is associated with, or {@code null}
9679      *            if the caller is a permission grant delegate.
9680      * @param packageName The application to check the grant state for.
9681      * @param permission The permission to check for.
9682      * @return the current grant state specified by device policy. If the profile or device owner
9683      *         has not set a grant state, the return value is
9684      *         {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
9685      *         permission is currently granted for the package.
9686      *         <p/>
9687      *         If a grant state was set by the profile or device owner, then the return value will
9688      *         be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
9689      *         {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
9690      *         currently denied or granted.
9691      * @throws SecurityException if {@code admin} is not a device or profile owner.
9692      * @see #setPermissionGrantState(ComponentName, String, String, int)
9693      * @see PackageManager#checkPermission(String, String)
9694      * @see #setDelegatedScopes
9695      * @see #DELEGATION_PERMISSION_GRANT
9696      */
getPermissionGrantState(@ullable ComponentName admin, @NonNull String packageName, @NonNull String permission)9697     public @PermissionGrantState int getPermissionGrantState(@Nullable ComponentName admin,
9698             @NonNull String packageName, @NonNull String permission) {
9699         throwIfParentInstance("getPermissionGrantState");
9700         try {
9701             return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName,
9702                     permission);
9703         } catch (RemoteException re) {
9704             throw re.rethrowFromSystemServer();
9705         }
9706     }
9707 
9708     /**
9709      * Returns whether it is possible for the caller to initiate provisioning of a managed profile
9710      * or device, setting itself as the device or profile owner.
9711      *
9712      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
9713      * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
9714      * @return whether provisioning a managed profile or device is possible.
9715      * @throws IllegalArgumentException if the supplied action is not valid.
9716      */
isProvisioningAllowed(@onNull String action)9717     public boolean isProvisioningAllowed(@NonNull String action) {
9718         throwIfParentInstance("isProvisioningAllowed");
9719         try {
9720             return mService.isProvisioningAllowed(action, mContext.getPackageName());
9721         } catch (RemoteException re) {
9722             throw re.rethrowFromSystemServer();
9723         }
9724     }
9725 
9726     /**
9727      * Checks whether it is possible to initiate provisioning a managed device,
9728      * profile or user, setting the given package as owner.
9729      *
9730      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
9731      *        {@link #ACTION_PROVISION_MANAGED_PROFILE},
9732      *        {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE},
9733      *        {@link #ACTION_PROVISION_MANAGED_USER}
9734      * @param packageName The package of the component that would be set as device, user, or profile
9735      *        owner.
9736      * @return A {@link ProvisioningPreCondition} value indicating whether provisioning is allowed.
9737      * @hide
9738      */
checkProvisioningPreCondition( String action, @NonNull String packageName)9739     public @ProvisioningPreCondition int checkProvisioningPreCondition(
9740             String action, @NonNull String packageName) {
9741         try {
9742             return mService.checkProvisioningPreCondition(action, packageName);
9743         } catch (RemoteException re) {
9744             throw re.rethrowFromSystemServer();
9745         }
9746     }
9747 
9748     /**
9749      * Return if this user is a managed profile of another user. An admin can become the profile
9750      * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
9751      * user with {@link #createAndManageUser}
9752      * @param admin Which profile owner this request is associated with.
9753      * @return if this user is a managed profile of another user.
9754      */
isManagedProfile(@onNull ComponentName admin)9755     public boolean isManagedProfile(@NonNull ComponentName admin) {
9756         throwIfParentInstance("isManagedProfile");
9757         try {
9758             return mService.isManagedProfile(admin);
9759         } catch (RemoteException re) {
9760             throw re.rethrowFromSystemServer();
9761         }
9762     }
9763 
9764     /**
9765      * @hide
9766      * Return if this user is a system-only user. An admin can manage a device from a system only
9767      * user by calling {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE}.
9768      * @param admin Which device owner this request is associated with.
9769      * @return if this user is a system-only user.
9770      */
isSystemOnlyUser(@onNull ComponentName admin)9771     public boolean isSystemOnlyUser(@NonNull ComponentName admin) {
9772         try {
9773             return mService.isSystemOnlyUser(admin);
9774         } catch (RemoteException re) {
9775             throw re.rethrowFromSystemServer();
9776         }
9777     }
9778 
9779     /**
9780      * Called by device owner, or profile owner on organization-owned device, to get the MAC
9781      * address of the Wi-Fi device.
9782      *
9783      * NOTE: The MAC address returned here should only be used for inventory management and is
9784      * not likely to be the MAC address used by the device to connect to Wi-Fi networks: MAC
9785      * addresses used for scanning and connecting to Wi-Fi networks are randomized by default.
9786      * To get the randomized MAC address used, call
9787      * {@link android.net.wifi.WifiConfiguration#getRandomizedMacAddress}.
9788      *
9789      * @param admin Which device owner this request is associated with.
9790      * @return the MAC address of the Wi-Fi device, or null when the information is not available.
9791      *         (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
9792      *         <p>
9793      *         The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
9794      * @throws SecurityException if {@code admin} is not a device owner.
9795      */
getWifiMacAddress(@onNull ComponentName admin)9796     public @Nullable String getWifiMacAddress(@NonNull ComponentName admin) {
9797         throwIfParentInstance("getWifiMacAddress");
9798         try {
9799             return mService.getWifiMacAddress(admin);
9800         } catch (RemoteException re) {
9801             throw re.rethrowFromSystemServer();
9802         }
9803     }
9804 
9805     /**
9806      * Called by device owner to reboot the device. If there is an ongoing call on the device,
9807      * throws an {@link IllegalStateException}.
9808      * @param admin Which device owner the request is associated with.
9809      * @throws IllegalStateException if device has an ongoing call.
9810      * @throws SecurityException if {@code admin} is not a device owner.
9811      * @see TelephonyManager#CALL_STATE_IDLE
9812      */
reboot(@onNull ComponentName admin)9813     public void reboot(@NonNull ComponentName admin) {
9814         throwIfParentInstance("reboot");
9815         try {
9816             mService.reboot(admin);
9817         } catch (RemoteException re) {
9818             throw re.rethrowFromSystemServer();
9819         }
9820     }
9821 
9822     /**
9823      * Called by a device admin to set the short support message. This will be displayed to the user
9824      * in settings screens where funtionality has been disabled by the admin. The message should be
9825      * limited to a short statement such as "This setting is disabled by your administrator. Contact
9826      * someone@example.com for support." If the message is longer than 200 characters it may be
9827      * truncated.
9828      * <p>
9829      * If the short support message needs to be localized, it is the responsibility of the
9830      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9831      * and set a new version of this string accordingly.
9832      *
9833      * @see #setLongSupportMessage
9834      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9835      * @param message Short message to be displayed to the user in settings or null to clear the
9836      *            existing message.
9837      * @throws SecurityException if {@code admin} is not an active administrator.
9838      */
setShortSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)9839     public void setShortSupportMessage(@NonNull ComponentName admin,
9840             @Nullable CharSequence message) {
9841         throwIfParentInstance("setShortSupportMessage");
9842         if (mService != null) {
9843             try {
9844                 mService.setShortSupportMessage(admin, message);
9845             } catch (RemoteException e) {
9846                 throw e.rethrowFromSystemServer();
9847             }
9848         }
9849     }
9850 
9851     /**
9852      * Called by a device admin to get the short support message.
9853      *
9854      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9855      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
9856      *         null if no message has been set.
9857      * @throws SecurityException if {@code admin} is not an active administrator.
9858      */
getShortSupportMessage(@onNull ComponentName admin)9859     public CharSequence getShortSupportMessage(@NonNull ComponentName admin) {
9860         throwIfParentInstance("getShortSupportMessage");
9861         if (mService != null) {
9862             try {
9863                 return mService.getShortSupportMessage(admin);
9864             } catch (RemoteException e) {
9865                 throw e.rethrowFromSystemServer();
9866             }
9867         }
9868         return null;
9869     }
9870 
9871     /**
9872      * Called by a device admin to set the long support message. This will be displayed to the user
9873      * in the device administators settings screen.
9874      * <p>
9875      * If the long support message needs to be localized, it is the responsibility of the
9876      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9877      * and set a new version of this string accordingly.
9878      *
9879      * @see #setShortSupportMessage
9880      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9881      * @param message Long message to be displayed to the user in settings or null to clear the
9882      *            existing message.
9883      * @throws SecurityException if {@code admin} is not an active administrator.
9884      */
setLongSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)9885     public void setLongSupportMessage(@NonNull ComponentName admin,
9886             @Nullable CharSequence message) {
9887         throwIfParentInstance("setLongSupportMessage");
9888         if (mService != null) {
9889             try {
9890                 mService.setLongSupportMessage(admin, message);
9891             } catch (RemoteException e) {
9892                 throw e.rethrowFromSystemServer();
9893             }
9894         }
9895     }
9896 
9897     /**
9898      * Called by a device admin to get the long support message.
9899      *
9900      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9901      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
9902      *         null if no message has been set.
9903      * @throws SecurityException if {@code admin} is not an active administrator.
9904      */
getLongSupportMessage(@onNull ComponentName admin)9905     public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
9906         throwIfParentInstance("getLongSupportMessage");
9907         if (mService != null) {
9908             try {
9909                 return mService.getLongSupportMessage(admin);
9910             } catch (RemoteException e) {
9911                 throw e.rethrowFromSystemServer();
9912             }
9913         }
9914         return null;
9915     }
9916 
9917     /**
9918      * Called by the system to get the short support message.
9919      *
9920      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9921      * @param userHandle user id the admin is running as.
9922      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
9923      *
9924      * @hide
9925      */
getShortSupportMessageForUser(@onNull ComponentName admin, int userHandle)9926     public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
9927             int userHandle) {
9928         if (mService != null) {
9929             try {
9930                 return mService.getShortSupportMessageForUser(admin, userHandle);
9931             } catch (RemoteException e) {
9932                 throw e.rethrowFromSystemServer();
9933             }
9934         }
9935         return null;
9936     }
9937 
9938 
9939     /**
9940      * Called by the system to get the long support message.
9941      *
9942      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9943      * @param userHandle user id the admin is running as.
9944      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
9945      *
9946      * @hide
9947      */
getLongSupportMessageForUser( @onNull ComponentName admin, int userHandle)9948     public @Nullable CharSequence getLongSupportMessageForUser(
9949             @NonNull ComponentName admin, int userHandle) {
9950         if (mService != null) {
9951             try {
9952                 return mService.getLongSupportMessageForUser(admin, userHandle);
9953             } catch (RemoteException e) {
9954                 throw e.rethrowFromSystemServer();
9955             }
9956         }
9957         return null;
9958     }
9959 
9960     /**
9961      * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
9962      * whose calls act on the parent profile.
9963      *
9964      * <p>The following methods are supported for the parent instance, all other methods will
9965      * throw a SecurityException when called on the parent instance:
9966      * <ul>
9967      * <li>{@link #getPasswordQuality}</li>
9968      * <li>{@link #setPasswordQuality}</li>
9969      * <li>{@link #getPasswordMinimumLength}</li>
9970      * <li>{@link #setPasswordMinimumLength}</li>
9971      * <li>{@link #getPasswordMinimumUpperCase}</li>
9972      * <li>{@link #setPasswordMinimumUpperCase}</li>
9973      * <li>{@link #getPasswordMinimumLowerCase}</li>
9974      * <li>{@link #setPasswordMinimumLowerCase}</li>
9975      * <li>{@link #getPasswordMinimumLetters}</li>
9976      * <li>{@link #setPasswordMinimumLetters}</li>
9977      * <li>{@link #getPasswordMinimumNumeric}</li>
9978      * <li>{@link #setPasswordMinimumNumeric}</li>
9979      * <li>{@link #getPasswordMinimumSymbols}</li>
9980      * <li>{@link #setPasswordMinimumSymbols}</li>
9981      * <li>{@link #getPasswordMinimumNonLetter}</li>
9982      * <li>{@link #setPasswordMinimumNonLetter}</li>
9983      * <li>{@link #getPasswordHistoryLength}</li>
9984      * <li>{@link #setPasswordHistoryLength}</li>
9985      * <li>{@link #getPasswordExpirationTimeout}</li>
9986      * <li>{@link #setPasswordExpirationTimeout}</li>
9987      * <li>{@link #getPasswordExpiration}</li>
9988      * <li>{@link #getPasswordMaximumLength}</li>
9989      * <li>{@link #isActivePasswordSufficient}</li>
9990      * <li>{@link #getCurrentFailedPasswordAttempts}</li>
9991      * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
9992      * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
9993      * <li>{@link #getMaximumTimeToLock}</li>
9994      * <li>{@link #setMaximumTimeToLock}</li>
9995      * <li>{@link #lockNow}</li>
9996      * <li>{@link #getKeyguardDisabledFeatures}</li>
9997      * <li>{@link #setKeyguardDisabledFeatures}</li>
9998      * <li>{@link #getTrustAgentConfiguration}</li>
9999      * <li>{@link #setTrustAgentConfiguration}</li>
10000      * <li>{@link #getRequiredStrongAuthTimeout}</li>
10001      * <li>{@link #setRequiredStrongAuthTimeout}</li>
10002      * <li>{@link #getAccountTypesWithManagementDisabled}</li>
10003      * </ul>
10004      * <p>
10005      * The following methods are supported for the parent instance but can only be called by the
10006      * profile owner of a managed profile that was created during the device provisioning flow:
10007      * <ul>
10008      * <li>{@link #getPasswordComplexity}</li>
10009      * <li>{@link #setCameraDisabled}</li>
10010      * <li>{@link #getCameraDisabled}</li>
10011      * <li>{@link #setAccountManagementDisabled(ComponentName, String, boolean)}</li>
10012      * </ul>
10013      *
10014      * <p>The following methods can be called by the profile owner of a managed profile
10015      * on an organization-owned device:
10016      * <ul>
10017      * <li>{@link #wipeData}</li>
10018      * </ul>
10019      *
10020      * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
10021      * @throws SecurityException if {@code admin} is not a profile owner.
10022      */
getParentProfileInstance(@onNull ComponentName admin)10023     public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
10024         throwIfParentInstance("getParentProfileInstance");
10025         try {
10026             if (!mService.isManagedProfile(admin)) {
10027                 throw new SecurityException("The current user does not have a parent profile.");
10028             }
10029             return new DevicePolicyManager(mContext, mService, true);
10030         } catch (RemoteException e) {
10031             throw e.rethrowFromSystemServer();
10032         }
10033     }
10034 
10035     /**
10036      * Called by device owner or a profile owner of an organization-owned managed profile to
10037      * control the security logging feature.
10038      *
10039      * <p> Security logs contain various information intended for security auditing purposes.
10040      * When security logging is enabled by a profile owner of
10041      * an organization-owned managed profile, certain security logs are not visible (for example
10042      * personal app launch events) or they will be redacted (for example, details of the physical
10043      * volume mount events). Please see {@link SecurityEvent} for details.
10044      *
10045      * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there
10046      * are unaffiliated secondary users or profiles on the device, regardless of whether the
10047      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
10048      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
10049      * new users as soon as possible after provisioning via {@link #setAffiliationIds}. Profile
10050      * owner of organization-owned managed profile is not subject to this restriction since all
10051      * privacy-sensitive events happening outside the managed profile would have been redacted
10052      * already.
10053      *
10054      * @param admin Which device admin this request is associated with.
10055      * @param enabled whether security logging should be enabled or not.
10056      * @throws SecurityException if {@code admin} is not allowed to control security logging.
10057      * @see #setAffiliationIds
10058      * @see #retrieveSecurityLogs
10059      */
setSecurityLoggingEnabled(@onNull ComponentName admin, boolean enabled)10060     public void setSecurityLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
10061         throwIfParentInstance("setSecurityLoggingEnabled");
10062         try {
10063             mService.setSecurityLoggingEnabled(admin, enabled);
10064         } catch (RemoteException re) {
10065             throw re.rethrowFromSystemServer();
10066         }
10067     }
10068 
10069     /**
10070      * Return whether security logging is enabled or not by the admin.
10071      *
10072      * <p>Can only be called by the device owner or a profile owner of an organization-owned
10073      * managed profile, otherwise a {@link SecurityException} will be thrown.
10074      *
10075      * @param admin Which device admin this request is associated with.
10076      * @return {@code true} if security logging is enabled by device owner, {@code false} otherwise.
10077      * @throws SecurityException if {@code admin} is not allowed to control security logging.
10078      */
isSecurityLoggingEnabled(@ullable ComponentName admin)10079     public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) {
10080         throwIfParentInstance("isSecurityLoggingEnabled");
10081         try {
10082             return mService.isSecurityLoggingEnabled(admin);
10083         } catch (RemoteException re) {
10084             throw re.rethrowFromSystemServer();
10085         }
10086     }
10087 
10088     /**
10089      * Called by device owner or profile owner of an organization-owned managed profile to retrieve
10090      * all new security logging entries since the last call to this API after device boots.
10091      *
10092      * <p> Access to the logs is rate limited and it will only return new logs after the device
10093      * owner has been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
10094      *
10095      * <p> When called by a device owner, if there is any other user or profile on the device,
10096      * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown.
10097      * See {@link #isAffiliatedUser}.
10098      *
10099      * @param admin Which device admin this request is associated with.
10100      * @return the new batch of security logs which is a list of {@link SecurityEvent},
10101      * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
10102      * @throws SecurityException if {@code admin} is not allowed to access security logging,
10103      * or there is at least one profile or secondary user that is not affiliated with the device.
10104      * @see #isAffiliatedUser
10105      * @see DeviceAdminReceiver#onSecurityLogsAvailable
10106      */
retrieveSecurityLogs(@onNull ComponentName admin)10107     public @Nullable List<SecurityEvent> retrieveSecurityLogs(@NonNull ComponentName admin) {
10108         throwIfParentInstance("retrieveSecurityLogs");
10109         try {
10110             ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(admin);
10111             if (list != null) {
10112                 return list.getList();
10113             } else {
10114                 // Rate limit exceeded.
10115                 return null;
10116             }
10117         } catch (RemoteException re) {
10118             throw re.rethrowFromSystemServer();
10119         }
10120     }
10121 
10122     /**
10123      * Makes all accumulated network logs available to DPC in a new batch.
10124      * Only callable by ADB. If throttled, returns time to wait in milliseconds, otherwise 0.
10125      * @hide
10126      */
forceNetworkLogs()10127     public long forceNetworkLogs() {
10128         if (mService == null) {
10129             return -1;
10130         }
10131         try {
10132             return mService.forceNetworkLogs();
10133         } catch (RemoteException re) {
10134             throw re.rethrowFromSystemServer();
10135         }
10136     }
10137 
10138     /**
10139      * Forces a batch of security logs to be fetched from logd and makes it available for DPC.
10140      * Only callable by ADB. If throttled, returns time to wait in milliseconds, otherwise 0.
10141      * @hide
10142      */
forceSecurityLogs()10143     public long forceSecurityLogs() {
10144         if (mService == null) {
10145             return 0;
10146         }
10147         try {
10148             return mService.forceSecurityLogs();
10149         } catch (RemoteException re) {
10150             throw re.rethrowFromSystemServer();
10151         }
10152     }
10153 
10154     /**
10155      * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
10156      * profile.
10157      *
10158      * @hide
10159      */
getParentProfileInstance(UserInfo uInfo)10160     public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
10161         mContext.checkSelfPermission(
10162                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
10163         if (!uInfo.isManagedProfile()) {
10164             throw new SecurityException("The user " + uInfo.id
10165                     + " does not have a parent profile.");
10166         }
10167         return new DevicePolicyManager(mContext, mService, true);
10168     }
10169 
10170     /**
10171      * Called by a device or profile owner to restrict packages from using metered data.
10172      *
10173      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10174      * @param packageNames the list of package names to be restricted.
10175      * @return a list of package names which could not be restricted.
10176      * @throws SecurityException if {@code admin} is not a device or profile owner.
10177      */
setMeteredDataDisabledPackages(@onNull ComponentName admin, @NonNull List<String> packageNames)10178     public @NonNull List<String> setMeteredDataDisabledPackages(@NonNull ComponentName admin,
10179             @NonNull List<String> packageNames) {
10180         throwIfParentInstance("setMeteredDataDisabled");
10181         if (mService != null) {
10182             try {
10183                 return mService.setMeteredDataDisabledPackages(admin, packageNames);
10184             } catch (RemoteException re) {
10185                 throw re.rethrowFromSystemServer();
10186             }
10187         }
10188         return packageNames;
10189     }
10190 
10191     /**
10192      * Called by a device or profile owner to retrieve the list of packages which are restricted
10193      * by the admin from using metered data.
10194      *
10195      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10196      * @return the list of restricted package names.
10197      * @throws SecurityException if {@code admin} is not a device or profile owner.
10198      */
getMeteredDataDisabledPackages(@onNull ComponentName admin)10199     public @NonNull List<String> getMeteredDataDisabledPackages(@NonNull ComponentName admin) {
10200         throwIfParentInstance("getMeteredDataDisabled");
10201         if (mService != null) {
10202             try {
10203                 return mService.getMeteredDataDisabledPackages(admin);
10204             } catch (RemoteException re) {
10205                 throw re.rethrowFromSystemServer();
10206             }
10207         }
10208         return new ArrayList<>();
10209     }
10210 
10211     /**
10212      * Called by the system to check if a package is restricted from using metered data
10213      * by {@param admin}.
10214      *
10215      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10216      * @param packageName the package whose restricted status is needed.
10217      * @param userId the user to which {@param packageName} belongs.
10218      * @return {@code true} if the package is restricted by admin, otherwise {@code false}
10219      * @throws SecurityException if the caller doesn't run with {@link Process#SYSTEM_UID}
10220      * @hide
10221      */
isMeteredDataDisabledPackageForUser(@onNull ComponentName admin, String packageName, @UserIdInt int userId)10222     public boolean isMeteredDataDisabledPackageForUser(@NonNull ComponentName admin,
10223             String packageName, @UserIdInt int userId) {
10224         throwIfParentInstance("getMeteredDataDisabledForUser");
10225         if (mService != null) {
10226             try {
10227                 return mService.isMeteredDataDisabledPackageForUser(admin, packageName, userId);
10228             } catch (RemoteException re) {
10229                 throw re.rethrowFromSystemServer();
10230             }
10231         }
10232         return false;
10233     }
10234 
10235     /**
10236      * Called by device owner or profile owner of an organization-owned managed profile to retrieve
10237      * device logs from before the device's last reboot.
10238      * <p>
10239      * <strong> This API is not supported on all devices. Calling this API on unsupported devices
10240      * will result in {@code null} being returned. The device logs are retrieved from a RAM region
10241      * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
10242      * about data corruption when parsing. </strong>
10243      *
10244      * <p> When called by a device owner, if there is any other user or profile on the device,
10245      * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown.
10246      * See {@link #isAffiliatedUser}.
10247      *
10248      * @param admin Which device admin this request is associated with.
10249      * @return Device logs from before the latest reboot of the system, or {@code null} if this API
10250      *         is not supported on the device.
10251      * @throws SecurityException if {@code admin} is not allowed to access security logging, or
10252      * there is at least one profile or secondary user that is not affiliated with the device.
10253      * @see #isAffiliatedUser
10254      * @see #retrieveSecurityLogs
10255      */
retrievePreRebootSecurityLogs( @onNull ComponentName admin)10256     public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
10257             @NonNull ComponentName admin) {
10258         throwIfParentInstance("retrievePreRebootSecurityLogs");
10259         try {
10260             ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(admin);
10261             if (list != null) {
10262                 return list.getList();
10263             } else {
10264                 return null;
10265             }
10266         } catch (RemoteException re) {
10267             throw re.rethrowFromSystemServer();
10268         }
10269     }
10270 
10271     /**
10272      * Called by a profile owner of a managed profile to set the color used for customization. This
10273      * color is used as background color of the confirm credentials screen for that user. The
10274      * default color is teal (#00796B).
10275      * <p>
10276      * The confirm credentials screen can be created using
10277      * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
10278      * <p>
10279      * Starting from Android R, the organization color will no longer be used as the background
10280      * color of the confirm credentials screen.
10281      *
10282      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10283      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
10284      * @throws SecurityException if {@code admin} is not a profile owner.
10285      */
setOrganizationColor(@onNull ComponentName admin, int color)10286     public void setOrganizationColor(@NonNull ComponentName admin, int color) {
10287         throwIfParentInstance("setOrganizationColor");
10288         try {
10289             // always enforce alpha channel to have 100% opacity
10290             color |= 0xFF000000;
10291             mService.setOrganizationColor(admin, color);
10292         } catch (RemoteException re) {
10293             throw re.rethrowFromSystemServer();
10294         }
10295     }
10296 
10297     /**
10298      * @hide
10299      *
10300      * Sets the color used for customization.
10301      *
10302      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
10303      * @param userId which user to set the color to.
10304      * @RequiresPermission(allOf = {
10305      *       Manifest.permission.MANAGE_USERS,
10306      *       Manifest.permission.INTERACT_ACROSS_USERS_FULL})
10307      */
setOrganizationColorForUser(@olorInt int color, @UserIdInt int userId)10308     public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
10309         try {
10310             // always enforce alpha channel to have 100% opacity
10311             color |= 0xFF000000;
10312             mService.setOrganizationColorForUser(color, userId);
10313         } catch (RemoteException re) {
10314             throw re.rethrowFromSystemServer();
10315         }
10316     }
10317 
10318     /**
10319      * Called by a profile owner of a managed profile to retrieve the color used for customization.
10320      * This color is used as background color of the confirm credentials screen for that user.
10321      *
10322      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10323      * @return The 24bit (0xRRGGBB) representation of the color to be used.
10324      * @throws SecurityException if {@code admin} is not a profile owner.
10325      */
getOrganizationColor(@onNull ComponentName admin)10326     public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
10327         throwIfParentInstance("getOrganizationColor");
10328         try {
10329             return mService.getOrganizationColor(admin);
10330         } catch (RemoteException re) {
10331             throw re.rethrowFromSystemServer();
10332         }
10333     }
10334 
10335     /**
10336      * @hide
10337      * Retrieve the customization color for a given user.
10338      *
10339      * @param userHandle The user id of the user we're interested in.
10340      * @return The 24bit (0xRRGGBB) representation of the color to be used.
10341      */
getOrganizationColorForUser(int userHandle)10342     public @ColorInt int getOrganizationColorForUser(int userHandle) {
10343         try {
10344             return mService.getOrganizationColorForUser(userHandle);
10345         } catch (RemoteException re) {
10346             throw re.rethrowFromSystemServer();
10347         }
10348     }
10349 
10350     /**
10351      * Called by the device owner (since API 26) or profile owner (since API 24) to set the name of
10352      * the organization under management.
10353      *
10354      * <p>If the organization name needs to be localized, it is the responsibility of the {@link
10355      * DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast and set
10356      * a new version of this string accordingly.
10357      *
10358      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10359      * @param title The organization name or {@code null} to clear a previously set name.
10360      * @throws SecurityException if {@code admin} is not a device or profile owner.
10361      */
setOrganizationName(@onNull ComponentName admin, @Nullable CharSequence title)10362     public void setOrganizationName(@NonNull ComponentName admin, @Nullable CharSequence title) {
10363         throwIfParentInstance("setOrganizationName");
10364         try {
10365             mService.setOrganizationName(admin, title);
10366         } catch (RemoteException re) {
10367             throw re.rethrowFromSystemServer();
10368         }
10369     }
10370 
10371     /**
10372      * Called by a profile owner of a managed profile to retrieve the name of the organization under
10373      * management.
10374      *
10375      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10376      * @return The organization name or {@code null} if none is set.
10377      * @throws SecurityException if {@code admin} is not a profile owner.
10378      */
getOrganizationName(@onNull ComponentName admin)10379     public @Nullable CharSequence getOrganizationName(@NonNull ComponentName admin) {
10380         throwIfParentInstance("getOrganizationName");
10381         try {
10382             return mService.getOrganizationName(admin);
10383         } catch (RemoteException re) {
10384             throw re.rethrowFromSystemServer();
10385         }
10386     }
10387 
10388     /**
10389      * Called by the system to retrieve the name of the organization managing the device.
10390      *
10391      * @return The organization name or {@code null} if none is set.
10392      * @throws SecurityException if the caller is not the device owner, does not hold the
10393      *         MANAGE_USERS permission and is not the system.
10394      *
10395      * @hide
10396      */
10397     @SystemApi
10398     @TestApi
10399     @SuppressLint("Doclava125")
getDeviceOwnerOrganizationName()10400     public @Nullable CharSequence getDeviceOwnerOrganizationName() {
10401         try {
10402             return mService.getDeviceOwnerOrganizationName();
10403         } catch (RemoteException re) {
10404             throw re.rethrowFromSystemServer();
10405         }
10406     }
10407 
10408     /**
10409      * Retrieve the default title message used in the confirm credentials screen for a given user.
10410      *
10411      * @param userHandle The user id of the user we're interested in.
10412      * @return The organization name or {@code null} if none is set.
10413      *
10414      * @hide
10415      */
getOrganizationNameForUser(int userHandle)10416     public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
10417         try {
10418             return mService.getOrganizationNameForUser(userHandle);
10419         } catch (RemoteException re) {
10420             throw re.rethrowFromSystemServer();
10421         }
10422     }
10423 
10424     /**
10425      * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
10426      *         return {@link #STATE_USER_UNMANAGED}
10427      * @hide
10428      */
10429     @SystemApi
10430     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
10431     @UserProvisioningState
getUserProvisioningState()10432     public int getUserProvisioningState() {
10433         throwIfParentInstance("getUserProvisioningState");
10434         if (mService != null) {
10435             try {
10436                 return mService.getUserProvisioningState();
10437             } catch (RemoteException e) {
10438                 throw e.rethrowFromSystemServer();
10439             }
10440         }
10441         return STATE_USER_UNMANAGED;
10442     }
10443 
10444     /**
10445      * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
10446      *
10447      * @param state to store
10448      * @param userHandle for user
10449      * @hide
10450      */
setUserProvisioningState(@serProvisioningState int state, int userHandle)10451     public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
10452         if (mService != null) {
10453             try {
10454                 mService.setUserProvisioningState(state, userHandle);
10455             } catch (RemoteException e) {
10456                 throw e.rethrowFromSystemServer();
10457             }
10458         }
10459     }
10460 
10461     /**
10462      * Indicates the entity that controls the device. Two users are
10463      * affiliated if the set of ids set by the device owner and the admin of the secondary user.
10464      *
10465      * <p>A user that is affiliated with the device owner user is considered to be
10466      * affiliated with the device.
10467      *
10468      * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
10469      * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user
10470      * is created, until it becomes affiliated. Therefore it is recommended that the appropriate
10471      * affiliation ids are set by its owner as soon as possible after the user is
10472      * created.
10473      * <p>
10474      * Note: This method used to be available for affiliating device owner and profile
10475      * owner. However, since Android 11, this combination is not possible. This method is now
10476      * only useful for affiliating the primary user with managed secondary users.
10477      *
10478      * @param admin Which device owner, or owner of secondary user, this request is associated with.
10479      * @param ids A set of opaque non-empty affiliation ids.
10480      *
10481      * @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
10482      * @see #isAffiliatedUser
10483      */
setAffiliationIds(@onNull ComponentName admin, @NonNull Set<String> ids)10484     public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) {
10485         throwIfParentInstance("setAffiliationIds");
10486         if (ids == null) {
10487             throw new IllegalArgumentException("ids must not be null");
10488         }
10489         try {
10490             mService.setAffiliationIds(admin, new ArrayList<>(ids));
10491         } catch (RemoteException e) {
10492             throw e.rethrowFromSystemServer();
10493         }
10494     }
10495 
10496     /**
10497      * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
10498      * empty set if none have been set.
10499      */
getAffiliationIds(@onNull ComponentName admin)10500     public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
10501         throwIfParentInstance("getAffiliationIds");
10502         try {
10503             return new ArraySet<>(mService.getAffiliationIds(admin));
10504         } catch (RemoteException e) {
10505             throw e.rethrowFromSystemServer();
10506         }
10507     }
10508 
10509     /**
10510      * Returns whether this user is affiliated with the device.
10511      * <p>
10512      * By definition, the user that the device owner runs on is always affiliated with the device.
10513      * Any other user is considered affiliated with the device if the set specified by its
10514      * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
10515      * @see #setAffiliationIds
10516      */
isAffiliatedUser()10517     public boolean isAffiliatedUser() {
10518         throwIfParentInstance("isAffiliatedUser");
10519         try {
10520             return mService.isAffiliatedUser();
10521         } catch (RemoteException e) {
10522             throw e.rethrowFromSystemServer();
10523         }
10524     }
10525 
10526     /**
10527      * @hide
10528      * Returns whether the uninstall for {@code packageName} for the current user is in queue
10529      * to be started
10530      * @param packageName the package to check for
10531      * @return whether the uninstall intent for {@code packageName} is pending
10532      */
isUninstallInQueue(String packageName)10533     public boolean isUninstallInQueue(String packageName) {
10534         try {
10535             return mService.isUninstallInQueue(packageName);
10536         } catch (RemoteException re) {
10537             throw re.rethrowFromSystemServer();
10538         }
10539     }
10540 
10541     /**
10542      * @hide
10543      * @param packageName the package containing active DAs to be uninstalled
10544      */
uninstallPackageWithActiveAdmins(String packageName)10545     public void uninstallPackageWithActiveAdmins(String packageName) {
10546         try {
10547             mService.uninstallPackageWithActiveAdmins(packageName);
10548         } catch (RemoteException re) {
10549             throw re.rethrowFromSystemServer();
10550         }
10551     }
10552 
10553     /**
10554      * @hide
10555      * Remove a test admin synchronously without sending it a broadcast about being removed.
10556      * If the admin is a profile owner or device owner it will still be removed.
10557      *
10558      * @param userHandle user id to remove the admin for.
10559      * @param admin The administration compononent to remove.
10560      * @throws SecurityException if the caller is not shell / root or the admin package
10561      *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
10562      */
forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle)10563     public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
10564         try {
10565             mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
10566         } catch (RemoteException re) {
10567             throw re.rethrowFromSystemServer();
10568         }
10569     }
10570 
10571     /**
10572      * Returns whether the device has been provisioned.
10573      *
10574      * <p>Not for use by third-party applications.
10575      *
10576      * @hide
10577      */
10578     @SystemApi
10579     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioned()10580     public boolean isDeviceProvisioned() {
10581         try {
10582             return mService.isDeviceProvisioned();
10583         } catch (RemoteException re) {
10584             throw re.rethrowFromSystemServer();
10585         }
10586     }
10587 
10588     /**
10589       * Writes that the provisioning configuration has been applied.
10590       *
10591       * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
10592       * permission.
10593       *
10594       * <p>Not for use by third-party applications.
10595       *
10596       * @hide
10597       */
10598     @SystemApi
10599     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
setDeviceProvisioningConfigApplied()10600     public void setDeviceProvisioningConfigApplied() {
10601         try {
10602             mService.setDeviceProvisioningConfigApplied();
10603         } catch (RemoteException re) {
10604             throw re.rethrowFromSystemServer();
10605         }
10606     }
10607 
10608     /**
10609      * Returns whether the provisioning configuration has been applied.
10610      *
10611      * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
10612      *
10613      * <p>Not for use by third-party applications.
10614      *
10615      * @return whether the provisioning configuration has been applied.
10616      *
10617      * @hide
10618      */
10619     @SystemApi
10620     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioningConfigApplied()10621     public boolean isDeviceProvisioningConfigApplied() {
10622         try {
10623             return mService.isDeviceProvisioningConfigApplied();
10624         } catch (RemoteException re) {
10625             throw re.rethrowFromSystemServer();
10626         }
10627     }
10628 
10629     /**
10630      * @hide
10631      * Force update user setup completed status. This API has no effect on user build.
10632      * @throws {@link SecurityException} if the caller has no
10633      *         {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS} or the caller is
10634      *         not {@link UserHandle#SYSTEM_USER}
10635      */
forceUpdateUserSetupComplete()10636     public void forceUpdateUserSetupComplete() {
10637         try {
10638             mService.forceUpdateUserSetupComplete();
10639         } catch (RemoteException re) {
10640             throw re.rethrowFromSystemServer();
10641         }
10642     }
10643 
10644     @UnsupportedAppUsage
throwIfParentInstance(String functionName)10645     private void throwIfParentInstance(String functionName) {
10646         if (mParentInstance) {
10647             throw new SecurityException(functionName + " cannot be called on the parent instance");
10648         }
10649     }
10650 
10651     /**
10652      * Allows the device owner or profile owner to enable or disable the backup service.
10653      *
10654      * <p> Each user has its own backup service which manages the backup and restore mechanisms in
10655      * that user. Disabling the backup service will prevent data from being backed up or restored.
10656      *
10657      * <p> Device owner calls this API to control backup services across all users on the device.
10658      * Profile owner can use this API to enable or disable the profile's backup service. However,
10659      * for a managed profile its backup functionality is only enabled if both the device owner
10660      * and the profile owner have enabled the backup service.
10661      *
10662      * <p> By default, backup service is disabled on a device with device owner, and within a
10663      * managed profile.
10664      *
10665      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10666      * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
10667      * @throws SecurityException if {@code admin} is not a device owner or a profile owner.
10668      */
setBackupServiceEnabled(@onNull ComponentName admin, boolean enabled)10669     public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
10670         throwIfParentInstance("setBackupServiceEnabled");
10671         try {
10672             mService.setBackupServiceEnabled(admin, enabled);
10673         } catch (RemoteException re) {
10674             throw re.rethrowFromSystemServer();
10675         }
10676     }
10677 
10678     /**
10679      * Return whether the backup service is enabled by the device owner or profile owner for the
10680      * current user, as previously set by {@link #setBackupServiceEnabled(ComponentName, boolean)}.
10681      *
10682      * <p> Whether the backup functionality is actually enabled or not depends on settings from both
10683      * the current user and the device owner, please see
10684      * {@link #setBackupServiceEnabled(ComponentName, boolean)} for details.
10685      *
10686      * <p> Backup service manages all backup and restore mechanisms on the device.
10687      *
10688      * @return {@code true} if backup service is enabled, {@code false} otherwise.
10689      * @see #setBackupServiceEnabled
10690      */
isBackupServiceEnabled(@onNull ComponentName admin)10691     public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
10692         throwIfParentInstance("isBackupServiceEnabled");
10693         try {
10694             return mService.isBackupServiceEnabled(admin);
10695         } catch (RemoteException re) {
10696             throw re.rethrowFromSystemServer();
10697         }
10698     }
10699 
10700     /**
10701      * Called by a device owner or delegated app with {@link #DELEGATION_NETWORK_LOGGING} to
10702      * control the network logging feature.
10703      *
10704      * <p> Network logs contain DNS lookup and connect() library call events. The following library
10705      *     functions are recorded while network logging is active:
10706      *     <ul>
10707      *       <li>{@code getaddrinfo()}</li>
10708      *       <li>{@code gethostbyname()}</li>
10709      *       <li>{@code connect()}</li>
10710      *     </ul>
10711      *
10712      * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
10713      *     full system call logging; event reporting is enabled by default for all processes but not
10714      *     strongly enforced.
10715      *     Events from applications using alternative implementations of libc, making direct kernel
10716      *     calls, or deliberately obfuscating traffic may not be recorded.
10717      *
10718      * <p> Some common network events may not be reported. For example:
10719      *     <ul>
10720      *       <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
10721      *           an alternative system for name resolution, and so avoid calling
10722      *           {@code getaddrinfo()} or {@code gethostbyname}.</li>
10723      *       <li>Applications may use datagram sockets for performance reasons, for example
10724      *           for a game client. Calling {@code connect()} is unnecessary for this kind of
10725      *           socket, so it will not trigger a network event.</li>
10726      *     </ul>
10727      *
10728      * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
10729      *     always-on VPN service.
10730      *     See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
10731      *     and {@link android.net.VpnService} for details.
10732      *
10733      * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
10734      * are unaffiliated secondary users or profiles on the device, regardless of whether the
10735      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
10736      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
10737      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
10738      *
10739      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10740      *        {@code null} if called by a delegated app.
10741      * @param enabled whether network logging should be enabled or not.
10742      * @throws SecurityException if {@code admin} is not a device owner.
10743      * @see #setAffiliationIds
10744      * @see #retrieveNetworkLogs
10745      */
setNetworkLoggingEnabled(@ullable ComponentName admin, boolean enabled)10746     public void setNetworkLoggingEnabled(@Nullable ComponentName admin, boolean enabled) {
10747         throwIfParentInstance("setNetworkLoggingEnabled");
10748         try {
10749             mService.setNetworkLoggingEnabled(admin, mContext.getPackageName(), enabled);
10750         } catch (RemoteException re) {
10751             throw re.rethrowFromSystemServer();
10752         }
10753     }
10754 
10755     /**
10756      * Return whether network logging is enabled by a device owner.
10757      *
10758      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
10759      * be {@code null} if the caller is a delegated app with {@link #DELEGATION_NETWORK_LOGGING}
10760      * or has MANAGE_USERS permission.
10761      * @return {@code true} if network logging is enabled by device owner, {@code false} otherwise.
10762      * @throws SecurityException if {@code admin} is not a device owner and caller has
10763      * no MANAGE_USERS permission
10764      */
isNetworkLoggingEnabled(@ullable ComponentName admin)10765     public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
10766         throwIfParentInstance("isNetworkLoggingEnabled");
10767         try {
10768             return mService.isNetworkLoggingEnabled(admin, mContext.getPackageName());
10769         } catch (RemoteException re) {
10770             throw re.rethrowFromSystemServer();
10771         }
10772     }
10773 
10774     /**
10775      * Called by device owner or delegated app with {@link #DELEGATION_NETWORK_LOGGING} to retrieve
10776      * the most recent batch of network logging events.
10777      * A device owner has to provide a batchToken provided as part of
10778      * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
10779      * token of the most recent available batch of logs, {@code null} will be returned.
10780      *
10781      * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
10782      *
10783      * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
10784      *
10785      * <p> Access to the logs is rate limited and this method will only return a new batch of logs
10786      * after the device device owner has been notified via
10787      * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
10788      *
10789      * <p>If a secondary user or profile is created, calling this method will throw a
10790      * {@link SecurityException} until all users become affiliated again. It will also no longer be
10791      * possible to retrieve the network logs batch with the most recent batchToken provided
10792      * by {@link DeviceAdminReceiver#onNetworkLogsAvailable}. See
10793      * {@link DevicePolicyManager#setAffiliationIds}.
10794      *
10795      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10796      *        {@code null} if called by a delegated app.
10797      * @param batchToken A token of the batch to retrieve
10798      * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
10799      *        {@code null} if the batch represented by batchToken is no longer available or if
10800      *        logging is disabled.
10801      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
10802      * profile or secondary user that is not affiliated with the device.
10803      * @see #setAffiliationIds
10804      * @see DeviceAdminReceiver#onNetworkLogsAvailable
10805      */
retrieveNetworkLogs(@ullable ComponentName admin, long batchToken)10806     public @Nullable List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin,
10807             long batchToken) {
10808         throwIfParentInstance("retrieveNetworkLogs");
10809         try {
10810             return mService.retrieveNetworkLogs(admin, mContext.getPackageName(), batchToken);
10811         } catch (RemoteException re) {
10812             throw re.rethrowFromSystemServer();
10813         }
10814     }
10815 
10816     /**
10817      * Called by a device owner to bind to a service from a secondary managed user or vice versa.
10818      * See {@link #getBindDeviceAdminTargetUsers} for the pre-requirements of a
10819      * device owner to bind to services of another managed user.
10820      * <p>
10821      * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
10822      * Note that the {@link Context} used to obtain this
10823      * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
10824      * to bind to the {@link android.app.Service}.
10825      * <p>
10826      * Note: This method used to be available for communication between device owner and profile
10827      * owner. However, since Android 11, this combination is not possible. This method is now
10828      * only useful for communication between device owner and managed secondary users.
10829      *
10830      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10831      * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
10832      *        explicit component name or a package name to match an
10833      *        {@link IntentFilter} published by a service.
10834      * @param conn Receives information as the service is started and stopped in main thread. This
10835      *        must be a valid {@link ServiceConnection} object; it must not be {@code null}.
10836      * @param flags Operation options for the binding operation. See
10837      *        {@link Context#bindService(Intent, ServiceConnection, int)}.
10838      * @param targetUser Which user to bind to. Must be one of the users returned by
10839      *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
10840      *        be thrown.
10841      * @return If you have successfully bound to the service, {@code true} is returned;
10842      *         {@code false} is returned if the connection is not made and you will not
10843      *         receive the service object.
10844      *
10845      * @see Context#bindService(Intent, ServiceConnection, int)
10846      * @see #getBindDeviceAdminTargetUsers(ComponentName)
10847      */
bindDeviceAdminServiceAsUser( @onNull ComponentName admin, Intent serviceIntent, @NonNull ServiceConnection conn, @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser)10848     public boolean bindDeviceAdminServiceAsUser(
10849             @NonNull ComponentName admin,  Intent serviceIntent, @NonNull ServiceConnection conn,
10850             @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser) {
10851         throwIfParentInstance("bindDeviceAdminServiceAsUser");
10852         // Keep this in sync with ContextImpl.bindServiceCommon.
10853         try {
10854             final IServiceConnection sd = mContext.getServiceDispatcher(
10855                     conn, mContext.getMainThreadHandler(), flags);
10856             serviceIntent.prepareToLeaveProcess(mContext);
10857             return mService.bindDeviceAdminServiceAsUser(admin,
10858                     mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
10859                     sd, flags, targetUser.getIdentifier());
10860         } catch (RemoteException re) {
10861             throw re.rethrowFromSystemServer();
10862         }
10863     }
10864 
10865     /**
10866      * Returns the list of target users that the calling device owner or owner of secondary user
10867      * can use when calling {@link #bindDeviceAdminServiceAsUser}.
10868      * <p>
10869      * A device owner can bind to a service from a secondary managed user and vice versa, provided
10870      * that both users are affiliated. See {@link #setAffiliationIds}.
10871      */
getBindDeviceAdminTargetUsers(@onNull ComponentName admin)10872     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
10873         throwIfParentInstance("getBindDeviceAdminTargetUsers");
10874         try {
10875             return mService.getBindDeviceAdminTargetUsers(admin);
10876         } catch (RemoteException re) {
10877             throw re.rethrowFromSystemServer();
10878         }
10879     }
10880 
10881     /**
10882      * Called by the system to get the time at which the device owner last retrieved security
10883      * logging entries.
10884      *
10885      * @return the time at which the device owner most recently retrieved security logging entries,
10886      *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
10887      * @throws SecurityException if the caller is not the device owner, does not hold the
10888      *         MANAGE_USERS permission and is not the system.
10889      *
10890      * @hide
10891      */
10892     @TestApi
getLastSecurityLogRetrievalTime()10893     public long getLastSecurityLogRetrievalTime() {
10894         try {
10895             return mService.getLastSecurityLogRetrievalTime();
10896         } catch (RemoteException re) {
10897             throw re.rethrowFromSystemServer();
10898         }
10899     }
10900 
10901     /**
10902      * Called by the system to get the time at which the device owner last requested a bug report.
10903      *
10904      * @return the time at which the device owner most recently requested a bug report, in
10905      *         milliseconds since epoch; -1 if a bug report was never requested.
10906      * @throws SecurityException if the caller is not the device owner, does not hold the
10907      *         MANAGE_USERS permission and is not the system.
10908      *
10909      * @hide
10910      */
10911     @TestApi
getLastBugReportRequestTime()10912     public long getLastBugReportRequestTime() {
10913         try {
10914             return mService.getLastBugReportRequestTime();
10915         } catch (RemoteException re) {
10916             throw re.rethrowFromSystemServer();
10917         }
10918     }
10919 
10920     /**
10921      * Called by the system to get the time at which the device owner last retrieved network logging
10922      * events.
10923      *
10924      * @return the time at which the device owner most recently retrieved network logging events, in
10925      *         milliseconds since epoch; -1 if network logging events were never retrieved.
10926      * @throws SecurityException if the caller is not the device owner, does not hold the
10927      *         MANAGE_USERS permission and is not the system.
10928      *
10929      * @hide
10930      */
10931     @TestApi
getLastNetworkLogRetrievalTime()10932     public long getLastNetworkLogRetrievalTime() {
10933         try {
10934             return mService.getLastNetworkLogRetrievalTime();
10935         } catch (RemoteException re) {
10936             throw re.rethrowFromSystemServer();
10937         }
10938     }
10939 
10940     /**
10941      * Called by the system to find out whether the current user's IME was set by the device/profile
10942      * owner or the user.
10943      *
10944      * @return {@code true} if the user's IME was set by the device or profile owner, {@code false}
10945      *         otherwise.
10946      * @throws SecurityException if the caller is not the device owner/profile owner.
10947      *
10948      * @hide
10949      */
10950     @TestApi
isCurrentInputMethodSetByOwner()10951     public boolean isCurrentInputMethodSetByOwner() {
10952         try {
10953             return mService.isCurrentInputMethodSetByOwner();
10954         } catch (RemoteException re) {
10955             throw re.rethrowFromSystemServer();
10956         }
10957     }
10958 
10959     /**
10960      * Called by the system to get a list of CA certificates that were installed by the device or
10961      * profile owner.
10962      *
10963      * <p> The caller must be the target user's device owner/profile Owner or hold the
10964      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
10965      *
10966      * @param user The user for whom to retrieve information.
10967      * @return list of aliases identifying CA certificates installed by the device or profile owner
10968      * @throws SecurityException if the caller does not have permission to retrieve information
10969      *         about the given user's CA certificates.
10970      *
10971      * @hide
10972      */
10973     @TestApi
getOwnerInstalledCaCerts(@onNull UserHandle user)10974     public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
10975         try {
10976             return mService.getOwnerInstalledCaCerts(user).getList();
10977         } catch (RemoteException re) {
10978             throw re.rethrowFromSystemServer();
10979         }
10980     }
10981 
10982     /**
10983      * Returns whether factory reset protection policy is supported on the device.
10984      *
10985      * @return {@code true} if the device support factory reset protection policy.
10986      *
10987      * @hide
10988      */
10989     @TestApi
isFactoryResetProtectionPolicySupported()10990     public boolean isFactoryResetProtectionPolicySupported() {
10991         try {
10992             return mService.isFactoryResetProtectionPolicySupported();
10993         } catch (RemoteException re) {
10994             throw re.rethrowFromSystemServer();
10995         }
10996     }
10997 
10998     /**
10999      * Called by the device owner or profile owner to clear application user data of a given
11000      * package. The behaviour of this is equivalent to the target application calling
11001      * {@link android.app.ActivityManager#clearApplicationUserData()}.
11002      *
11003      * <p><strong>Note:</strong> an application can store data outside of its application data, e.g.
11004      * external storage or user dictionary. This data will not be wiped by calling this API.
11005      *
11006      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11007      * @param packageName The name of the package which will have its user data wiped.
11008      * @param executor The executor through which the listener should be invoked.
11009      * @param listener A callback object that will inform the caller when the clearing is done.
11010      * @throws SecurityException if the caller is not the device owner/profile owner.
11011      */
clearApplicationUserData(@onNull ComponentName admin, @NonNull String packageName, @NonNull @CallbackExecutor Executor executor, @NonNull OnClearApplicationUserDataListener listener)11012     public void clearApplicationUserData(@NonNull ComponentName admin,
11013             @NonNull String packageName, @NonNull @CallbackExecutor Executor executor,
11014             @NonNull OnClearApplicationUserDataListener listener) {
11015         throwIfParentInstance("clearAppData");
11016         Objects.requireNonNull(executor);
11017         Objects.requireNonNull(listener);
11018         try {
11019             mService.clearApplicationUserData(admin, packageName,
11020                     new IPackageDataObserver.Stub() {
11021                         public void onRemoveCompleted(String pkg, boolean succeeded) {
11022                             executor.execute(() ->
11023                                     listener.onApplicationUserDataCleared(pkg, succeeded));
11024                         }
11025                     });
11026         } catch (RemoteException re) {
11027             throw re.rethrowFromSystemServer();
11028         }
11029     }
11030 
11031     /**
11032      * Called by a device owner to specify whether logout is enabled for all secondary users. The
11033      * system may show a logout button that stops the user and switches back to the primary user.
11034      *
11035      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11036      * @param enabled whether logout should be enabled or not.
11037      * @throws SecurityException if {@code admin} is not a device owner.
11038      */
setLogoutEnabled(@onNull ComponentName admin, boolean enabled)11039     public void setLogoutEnabled(@NonNull ComponentName admin, boolean enabled) {
11040         throwIfParentInstance("setLogoutEnabled");
11041         try {
11042             mService.setLogoutEnabled(admin, enabled);
11043         } catch (RemoteException re) {
11044             throw re.rethrowFromSystemServer();
11045         }
11046     }
11047 
11048     /**
11049      * Returns whether logout is enabled by a device owner.
11050      *
11051      * @return {@code true} if logout is enabled by device owner, {@code false} otherwise.
11052      */
isLogoutEnabled()11053     public boolean isLogoutEnabled() {
11054         throwIfParentInstance("isLogoutEnabled");
11055         try {
11056             return mService.isLogoutEnabled();
11057         } catch (RemoteException re) {
11058             throw re.rethrowFromSystemServer();
11059         }
11060     }
11061 
11062     /**
11063      * Callback used in {@link #clearApplicationUserData}
11064      * to indicate that the clearing of an application's user data is done.
11065      */
11066     public interface OnClearApplicationUserDataListener {
11067         /**
11068          * Method invoked when clearing the application user data has completed.
11069          *
11070          * @param packageName The name of the package which had its user data cleared.
11071          * @param succeeded Whether the clearing succeeded. Clearing fails for device administrator
11072          *                  apps and protected system packages.
11073          */
onApplicationUserDataCleared(String packageName, boolean succeeded)11074         void onApplicationUserDataCleared(String packageName, boolean succeeded);
11075     }
11076 
11077     /**
11078      * Returns set of system apps that should be removed during provisioning.
11079      *
11080      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11081      * @param userId ID of the user to be provisioned.
11082      * @param provisioningAction action indicating type of provisioning, should be one of
11083      * {@link #ACTION_PROVISION_MANAGED_DEVICE}, {@link #ACTION_PROVISION_MANAGED_PROFILE} or
11084      * {@link #ACTION_PROVISION_MANAGED_USER}.
11085      *
11086      * @hide
11087      */
getDisallowedSystemApps(ComponentName admin, int userId, String provisioningAction)11088     public Set<String> getDisallowedSystemApps(ComponentName admin, int userId,
11089             String provisioningAction) {
11090         try {
11091             return new ArraySet<>(
11092                     mService.getDisallowedSystemApps(admin, userId, provisioningAction));
11093         } catch (RemoteException re) {
11094             throw re.rethrowFromSystemServer();
11095         }
11096     }
11097 
11098     /**
11099      * Changes the current administrator to another one. All policies from the current
11100      * administrator are migrated to the new administrator. The whole operation is atomic -
11101      * the transfer is either complete or not done at all.
11102      *
11103      * <p>Depending on the current administrator (device owner, profile owner), you have the
11104      * following expected behaviour:
11105      * <ul>
11106      *     <li>A device owner can only be transferred to a new device owner</li>
11107      *     <li>A profile owner can only be transferred to a new profile owner</li>
11108      * </ul>
11109      *
11110      * <p>Use the {@code bundle} parameter to pass data to the new administrator. The data
11111      * will be received in the
11112      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}
11113      * callback of the new administrator.
11114      *
11115      * <p>The transfer has failed if the original administrator is still the corresponding owner
11116      * after calling this method.
11117      *
11118      * <p>The incoming target administrator must have the
11119      * <code>&lt;support-transfer-ownership /&gt;</code> tag inside the
11120      * <code>&lt;device-admin&gt;&lt;/device-admin&gt;</code> tags in the xml file referenced by
11121      * {@link DeviceAdminReceiver#DEVICE_ADMIN_META_DATA}. Otherwise an
11122      * {@link IllegalArgumentException} will be thrown.
11123      *
11124      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11125      * @param target which {@link DeviceAdminReceiver} we want the new administrator to be
11126      * @param bundle data to be sent to the new administrator
11127      * @throws SecurityException if {@code admin} is not a device owner nor a profile owner
11128      * @throws IllegalArgumentException if {@code admin} or {@code target} is {@code null}, they
11129      * are components in the same package or {@code target} is not an active admin
11130      */
transferOwnership(@onNull ComponentName admin, @NonNull ComponentName target, @Nullable PersistableBundle bundle)11131     public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
11132             @Nullable PersistableBundle bundle) {
11133         throwIfParentInstance("transferOwnership");
11134         try {
11135             mService.transferOwnership(admin, target, bundle);
11136         } catch (RemoteException re) {
11137             throw re.rethrowFromSystemServer();
11138         }
11139     }
11140 
11141     /**
11142      * Called by a device owner to specify the user session start message. This may be displayed
11143      * during a user switch.
11144      * <p>
11145      * The message should be limited to a short statement or it may be truncated.
11146      * <p>
11147      * If the message needs to be localized, it is the responsibility of the
11148      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
11149      * and set a new version of this message accordingly.
11150      *
11151      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11152      * @param startUserSessionMessage message for starting user session, or {@code null} to use
11153      * system default message.
11154      * @throws SecurityException if {@code admin} is not a device owner.
11155      */
setStartUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence startUserSessionMessage)11156     public void setStartUserSessionMessage(
11157             @NonNull ComponentName admin, @Nullable CharSequence startUserSessionMessage) {
11158         throwIfParentInstance("setStartUserSessionMessage");
11159         try {
11160             mService.setStartUserSessionMessage(admin, startUserSessionMessage);
11161         } catch (RemoteException re) {
11162             throw re.rethrowFromSystemServer();
11163         }
11164     }
11165 
11166     /**
11167      * Called by a device owner to specify the user session end message. This may be displayed
11168      * during a user switch.
11169      * <p>
11170      * The message should be limited to a short statement or it may be truncated.
11171      * <p>
11172      * If the message needs to be localized, it is the responsibility of the
11173      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
11174      * and set a new version of this message accordingly.
11175      *
11176      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11177      * @param endUserSessionMessage message for ending user session, or {@code null} to use system
11178      * default message.
11179      * @throws SecurityException if {@code admin} is not a device owner.
11180      */
setEndUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence endUserSessionMessage)11181     public void setEndUserSessionMessage(
11182             @NonNull ComponentName admin, @Nullable CharSequence endUserSessionMessage) {
11183         throwIfParentInstance("setEndUserSessionMessage");
11184         try {
11185             mService.setEndUserSessionMessage(admin, endUserSessionMessage);
11186         } catch (RemoteException re) {
11187             throw re.rethrowFromSystemServer();
11188         }
11189     }
11190 
11191     /**
11192      * Returns the user session start message.
11193      *
11194      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11195      * @throws SecurityException if {@code admin} is not a device owner.
11196      */
getStartUserSessionMessage(@onNull ComponentName admin)11197     public CharSequence getStartUserSessionMessage(@NonNull ComponentName admin) {
11198         throwIfParentInstance("getStartUserSessionMessage");
11199         try {
11200             return mService.getStartUserSessionMessage(admin);
11201         } catch (RemoteException re) {
11202             throw re.rethrowFromSystemServer();
11203         }
11204     }
11205 
11206     /**
11207      * Returns the user session end message.
11208      *
11209      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11210      * @throws SecurityException if {@code admin} is not a device owner.
11211      */
getEndUserSessionMessage(@onNull ComponentName admin)11212     public CharSequence getEndUserSessionMessage(@NonNull ComponentName admin) {
11213         throwIfParentInstance("getEndUserSessionMessage");
11214         try {
11215             return mService.getEndUserSessionMessage(admin);
11216         } catch (RemoteException re) {
11217             throw re.rethrowFromSystemServer();
11218         }
11219     }
11220 
11221     /**
11222      * Called by device owner to add an override APN.
11223      *
11224      * <p>This method may returns {@code -1} if {@code apnSetting} conflicts with an existing
11225      * override APN. Update the existing conflicted APN with
11226      * {@link #updateOverrideApn(ComponentName, int, ApnSetting)} instead of adding a new entry.
11227      * <p>Two override APNs are considered to conflict when all the following APIs return
11228      * the same values on both override APNs:
11229      * <ul>
11230      *   <li>{@link ApnSetting#getOperatorNumeric()}</li>
11231      *   <li>{@link ApnSetting#getApnName()}</li>
11232      *   <li>{@link ApnSetting#getProxyAddressAsString()}</li>
11233      *   <li>{@link ApnSetting#getProxyPort()}</li>
11234      *   <li>{@link ApnSetting#getMmsProxyAddressAsString()}</li>
11235      *   <li>{@link ApnSetting#getMmsProxyPort()}</li>
11236      *   <li>{@link ApnSetting#getMmsc()}</li>
11237      *   <li>{@link ApnSetting#isEnabled()}</li>
11238      *   <li>{@link ApnSetting#getMvnoType()}</li>
11239      *   <li>{@link ApnSetting#getProtocol()}</li>
11240      *   <li>{@link ApnSetting#getRoamingProtocol()}</li>
11241      * </ul>
11242      *
11243      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11244      * @param apnSetting the override APN to insert
11245      * @return The {@code id} of inserted override APN. Or {@code -1} when failed to insert into
11246      *         the database.
11247      * @throws SecurityException if {@code admin} is not a device owner.
11248      *
11249      * @see #setOverrideApnsEnabled(ComponentName, boolean)
11250      */
addOverrideApn(@onNull ComponentName admin, @NonNull ApnSetting apnSetting)11251     public int addOverrideApn(@NonNull ComponentName admin, @NonNull ApnSetting apnSetting) {
11252         throwIfParentInstance("addOverrideApn");
11253         if (mService != null) {
11254             try {
11255                 return mService.addOverrideApn(admin, apnSetting);
11256             } catch (RemoteException e) {
11257                 throw e.rethrowFromSystemServer();
11258             }
11259         }
11260         return -1;
11261     }
11262 
11263     /**
11264      * Called by device owner to update an override APN.
11265      *
11266      * <p>This method may returns {@code false} if there is no override APN with the given
11267      * {@code apnId}.
11268      * <p>This method may also returns {@code false} if {@code apnSetting} conflicts with an
11269      * existing override APN. Update the existing conflicted APN instead.
11270      * <p>See {@link #addOverrideApn} for the definition of conflict.
11271      *
11272      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11273      * @param apnId the {@code id} of the override APN to update
11274      * @param apnSetting the override APN to update
11275      * @return {@code true} if the required override APN is successfully updated,
11276      *         {@code false} otherwise.
11277      * @throws SecurityException if {@code admin} is not a device owner.
11278      *
11279      * @see #setOverrideApnsEnabled(ComponentName, boolean)
11280      */
updateOverrideApn(@onNull ComponentName admin, int apnId, @NonNull ApnSetting apnSetting)11281     public boolean updateOverrideApn(@NonNull ComponentName admin, int apnId,
11282             @NonNull ApnSetting apnSetting) {
11283         throwIfParentInstance("updateOverrideApn");
11284         if (mService != null) {
11285             try {
11286                 return mService.updateOverrideApn(admin, apnId, apnSetting);
11287             } catch (RemoteException e) {
11288                 throw e.rethrowFromSystemServer();
11289             }
11290         }
11291         return false;
11292     }
11293 
11294     /**
11295      * Called by device owner to remove an override APN.
11296      *
11297      * <p>This method may returns {@code false} if there is no override APN with the given
11298      * {@code apnId}.
11299      *
11300      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11301      * @param apnId the {@code id} of the override APN to remove
11302      * @return {@code true} if the required override APN is successfully removed, {@code false}
11303      *         otherwise.
11304      * @throws SecurityException if {@code admin} is not a device owner.
11305      *
11306      * @see #setOverrideApnsEnabled(ComponentName, boolean)
11307      */
removeOverrideApn(@onNull ComponentName admin, int apnId)11308     public boolean removeOverrideApn(@NonNull ComponentName admin, int apnId) {
11309         throwIfParentInstance("removeOverrideApn");
11310         if (mService != null) {
11311             try {
11312                 return mService.removeOverrideApn(admin, apnId);
11313             } catch (RemoteException e) {
11314                 throw e.rethrowFromSystemServer();
11315             }
11316         }
11317         return false;
11318     }
11319 
11320     /**
11321      * Called by device owner to get all override APNs inserted by device owner.
11322      *
11323      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11324      * @return A list of override APNs inserted by device owner.
11325      * @throws SecurityException if {@code admin} is not a device owner.
11326      *
11327      * @see #setOverrideApnsEnabled(ComponentName, boolean)
11328      */
getOverrideApns(@onNull ComponentName admin)11329     public List<ApnSetting> getOverrideApns(@NonNull ComponentName admin) {
11330         throwIfParentInstance("getOverrideApns");
11331         if (mService != null) {
11332             try {
11333                 return mService.getOverrideApns(admin);
11334             } catch (RemoteException e) {
11335                 throw e.rethrowFromSystemServer();
11336             }
11337         }
11338         return Collections.emptyList();
11339     }
11340 
11341     /**
11342      * Called by device owner to set if override APNs should be enabled.
11343      * <p> Override APNs are separated from other APNs on the device, and can only be inserted or
11344      * modified by the device owner. When enabled, only override APNs are in use, any other APNs
11345      * are ignored.
11346      *
11347      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11348      * @param enabled {@code true} if override APNs should be enabled, {@code false} otherwise
11349      * @throws SecurityException if {@code admin} is not a device owner.
11350      */
setOverrideApnsEnabled(@onNull ComponentName admin, boolean enabled)11351     public void setOverrideApnsEnabled(@NonNull ComponentName admin, boolean enabled) {
11352         throwIfParentInstance("setOverrideApnEnabled");
11353         if (mService != null) {
11354             try {
11355                 mService.setOverrideApnsEnabled(admin, enabled);
11356             } catch (RemoteException e) {
11357                 throw e.rethrowFromSystemServer();
11358             }
11359         }
11360     }
11361 
11362     /**
11363      * Called by device owner to check if override APNs are currently enabled.
11364      *
11365      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11366      * @return {@code true} if override APNs are currently enabled, {@code false} otherwise.
11367      * @throws SecurityException if {@code admin} is not a device owner.
11368      *
11369      * @see #setOverrideApnsEnabled(ComponentName, boolean)
11370      */
isOverrideApnEnabled(@onNull ComponentName admin)11371     public boolean isOverrideApnEnabled(@NonNull ComponentName admin) {
11372         throwIfParentInstance("isOverrideApnEnabled");
11373         if (mService != null) {
11374             try {
11375                 return mService.isOverrideApnEnabled(admin);
11376             } catch (RemoteException e) {
11377                 throw e.rethrowFromSystemServer();
11378             }
11379         }
11380         return false;
11381     }
11382 
11383     /**
11384      * Returns the data passed from the current administrator to the new administrator during an
11385      * ownership transfer. This is the same {@code bundle} passed in
11386      * {@link #transferOwnership(ComponentName, ComponentName, PersistableBundle)}. The bundle is
11387      * persisted until the profile owner or device owner is removed.
11388      *
11389      * <p>This is the same <code>bundle</code> received in the
11390      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}.
11391      * Use this method to retrieve it after the transfer as long as the new administrator is the
11392      * active device or profile owner.
11393      *
11394      * <p>Returns <code>null</code> if no ownership transfer was started for the calling user.
11395      *
11396      * @see #transferOwnership
11397      * @see DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)
11398      * @throws SecurityException if the caller is not a device or profile owner.
11399      */
11400     @Nullable
getTransferOwnershipBundle()11401     public PersistableBundle getTransferOwnershipBundle() {
11402         throwIfParentInstance("getTransferOwnershipBundle");
11403         try {
11404             return mService.getTransferOwnershipBundle();
11405         } catch (RemoteException re) {
11406             throw re.rethrowFromSystemServer();
11407         }
11408     }
11409 
11410     /**
11411      * Sets the global Private DNS mode to opportunistic.
11412      * May only be called by the device owner.
11413      *
11414      * <p>In this mode, the DNS subsystem will attempt a TLS handshake to the network-supplied
11415      * resolver prior to attempting name resolution in cleartext.
11416      *
11417      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11418      *
11419      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully, or
11420      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set.
11421      *
11422      * @throws SecurityException if the caller is not the device owner.
11423      */
setGlobalPrivateDnsModeOpportunistic( @onNull ComponentName admin)11424     public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeOpportunistic(
11425             @NonNull ComponentName admin) {
11426         throwIfParentInstance("setGlobalPrivateDnsModeOpportunistic");
11427 
11428         if (mService == null) {
11429             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
11430         }
11431 
11432         try {
11433             return mService.setGlobalPrivateDns(admin, PRIVATE_DNS_MODE_OPPORTUNISTIC, null);
11434         } catch (RemoteException re) {
11435             throw re.rethrowFromSystemServer();
11436         }
11437     }
11438 
11439     /**
11440      * Sets the global Private DNS host to be used.
11441      * May only be called by the device owner.
11442      *
11443      * <p>Note that the method is blocking as it will perform a connectivity check to the resolver,
11444      * to ensure it is valid. Because of that, the method should not be called on any thread that
11445      * relates to user interaction, such as the UI thread.
11446      *
11447      * <p>In case a VPN is used in conjunction with Private DNS resolver, the Private DNS resolver
11448      * must be reachable both from within and outside the VPN. Otherwise, the device may lose
11449      * the ability to resolve hostnames as system traffic to the resolver may not go through the
11450      * VPN.
11451      *
11452      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11453      * @param privateDnsHost The hostname of a server that implements DNS over TLS (RFC7858).
11454      *
11455      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully,
11456      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set or
11457      *         {@code PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING} if the specified host does not
11458      *         implement RFC7858.
11459      *
11460      * @throws IllegalArgumentException if the {@code privateDnsHost} is not a valid hostname.
11461      *
11462      * @throws SecurityException if the caller is not the device owner.
11463      */
setGlobalPrivateDnsModeSpecifiedHost( @onNull ComponentName admin, @NonNull String privateDnsHost)11464     @WorkerThread public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeSpecifiedHost(
11465             @NonNull ComponentName admin, @NonNull String privateDnsHost) {
11466         throwIfParentInstance("setGlobalPrivateDnsModeSpecifiedHost");
11467         Objects.requireNonNull(privateDnsHost, "dns resolver is null");
11468 
11469         if (mService == null) {
11470             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
11471         }
11472 
11473         if (NetworkUtils.isWeaklyValidatedHostname(privateDnsHost)) {
11474             if (!PrivateDnsConnectivityChecker.canConnectToPrivateDnsServer(privateDnsHost)) {
11475                 return PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING;
11476             }
11477         }
11478 
11479         try {
11480             return mService.setGlobalPrivateDns(
11481                     admin, PRIVATE_DNS_MODE_PROVIDER_HOSTNAME, privateDnsHost);
11482         } catch (RemoteException re) {
11483             throw re.rethrowFromSystemServer();
11484         }
11485     }
11486 
11487     /**
11488      * Called by device owner or profile owner of an organization-owned managed profile to install
11489      * a system update from the given file. The device will be
11490      * rebooted in order to finish installing the update. Note that if the device is rebooted, this
11491      * doesn't necessarily mean that the update has been applied successfully. The caller should
11492      * additionally check the system version with {@link android.os.Build#FINGERPRINT} or {@link
11493      * android.os.Build.VERSION}. If an error occurs during processing the OTA before the reboot,
11494      * the caller will be notified by {@link InstallSystemUpdateCallback}. If device does not have
11495      * sufficient battery level, the installation will fail with error {@link
11496      * InstallSystemUpdateCallback#UPDATE_ERROR_BATTERY_LOW}.
11497      *
11498      * @param admin The {@link DeviceAdminReceiver} that this request is associated with.
11499      * @param updateFilePath An Uri of the file that contains the update. The file should be
11500      * readable by the calling app.
11501      * @param executor The executor through which the callback should be invoked.
11502      * @param callback A callback object that will inform the caller when installing an update
11503      * fails.
11504      */
installSystemUpdate( @onNull ComponentName admin, @NonNull Uri updateFilePath, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)11505     public void installSystemUpdate(
11506             @NonNull ComponentName admin, @NonNull Uri updateFilePath,
11507             @NonNull @CallbackExecutor Executor executor,
11508             @NonNull InstallSystemUpdateCallback callback) {
11509         throwIfParentInstance("installUpdate");
11510         if (mService == null) {
11511             return;
11512         }
11513         try (ParcelFileDescriptor fileDescriptor = mContext.getContentResolver()
11514                     .openFileDescriptor(updateFilePath, "r")) {
11515             mService.installUpdateFromFile(
11516                     admin, fileDescriptor, new StartInstallingUpdateCallback.Stub() {
11517                         @Override
11518                         public void onStartInstallingUpdateError(
11519                                 int errorCode, String errorMessage) {
11520                             executeCallback(errorCode, errorMessage, executor, callback);
11521                         }
11522                     });
11523         } catch (RemoteException e) {
11524             throw e.rethrowFromSystemServer();
11525         } catch (FileNotFoundException e) {
11526             Log.w(TAG, e);
11527             executeCallback(
11528                     InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
11529                     Log.getStackTraceString(e),
11530                     executor, callback);
11531         } catch (IOException e) {
11532             Log.w(TAG, e);
11533             executeCallback(
11534                     InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN, Log.getStackTraceString(e),
11535                     executor, callback);
11536         }
11537     }
11538 
executeCallback(int errorCode, String errorMessage, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)11539     private void executeCallback(int errorCode, String errorMessage,
11540             @NonNull @CallbackExecutor Executor executor,
11541             @NonNull InstallSystemUpdateCallback callback) {
11542         executor.execute(() -> callback.onInstallUpdateError(errorCode, errorMessage));
11543     }
11544 
11545     /**
11546      * Returns the system-wide Private DNS mode.
11547      *
11548      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11549      * @return one of {@code PRIVATE_DNS_MODE_OFF}, {@code PRIVATE_DNS_MODE_OPPORTUNISTIC},
11550      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} or {@code PRIVATE_DNS_MODE_UNKNOWN}.
11551      * @throws SecurityException if the caller is not the device owner.
11552      */
getGlobalPrivateDnsMode(@onNull ComponentName admin)11553     public int getGlobalPrivateDnsMode(@NonNull ComponentName admin) {
11554         throwIfParentInstance("setGlobalPrivateDns");
11555         if (mService == null) {
11556             return PRIVATE_DNS_MODE_UNKNOWN;
11557         }
11558 
11559         try {
11560             return mService.getGlobalPrivateDnsMode(admin);
11561         } catch (RemoteException re) {
11562             throw re.rethrowFromSystemServer();
11563         }
11564     }
11565 
11566     /**
11567      * Returns the system-wide Private DNS host.
11568      *
11569      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11570      * @return The hostname used for Private DNS queries, null if none is set.
11571      * @throws SecurityException if the caller is not the device owner.
11572      */
getGlobalPrivateDnsHost(@onNull ComponentName admin)11573     public @Nullable String getGlobalPrivateDnsHost(@NonNull ComponentName admin) {
11574         throwIfParentInstance("setGlobalPrivateDns");
11575         if (mService == null) {
11576             return null;
11577         }
11578 
11579         try {
11580             return mService.getGlobalPrivateDnsHost(admin);
11581         } catch (RemoteException re) {
11582             throw re.rethrowFromSystemServer();
11583         }
11584     }
11585 
11586     /**
11587      * Deprecated. Use {@code markProfileOwnerOnOrganizationOwnedDevice} instead.
11588      * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#Q} or
11589      * below, will behave the same as {@link #markProfileOwnerOnOrganizationOwnedDevice}.
11590      *
11591      * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#R}
11592      * or above, will throw an UnsupportedOperationException when called.
11593      *
11594      * @deprecated Use {@link #markProfileOwnerOnOrganizationOwnedDevice} instead.
11595      *
11596      * @hide
11597      */
11598     @Deprecated
11599     @SystemApi
11600     @RequiresPermission(value = android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS,
11601             conditional = true)
setProfileOwnerCanAccessDeviceIds(@onNull ComponentName who)11602     public void setProfileOwnerCanAccessDeviceIds(@NonNull ComponentName who) {
11603         ApplicationInfo ai = mContext.getApplicationInfo();
11604         if (ai.targetSdkVersion > Build.VERSION_CODES.Q) {
11605             throw new UnsupportedOperationException(
11606                     "This method is deprecated. use markProfileOwnerOnOrganizationOwnedDevice"
11607                     + " instead.");
11608         } else {
11609             markProfileOwnerOnOrganizationOwnedDevice(who);
11610         }
11611     }
11612 
11613     /**
11614      * Marks the profile owner of the given user as managing an organization-owned device.
11615      * That will give it access to device identifiers (such as serial number, IMEI and MEID)
11616      * as well as other privileges.
11617      *
11618      * @hide
11619      */
11620     @RequiresPermission(value = android.Manifest.permission.MARK_DEVICE_ORGANIZATION_OWNED,
11621             conditional = true)
markProfileOwnerOnOrganizationOwnedDevice(@onNull ComponentName who)11622     public void markProfileOwnerOnOrganizationOwnedDevice(@NonNull ComponentName who) {
11623         if (mService == null) {
11624             return;
11625         }
11626         try {
11627             mService.markProfileOwnerOnOrganizationOwnedDevice(who, myUserId());
11628         } catch (RemoteException re) {
11629             throw re.rethrowFromSystemServer();
11630         }
11631     }
11632 
11633     /**
11634      * Allows a set of packages to access cross-profile calendar APIs.
11635      *
11636      * <p>Called by a profile owner of a managed profile.
11637      *
11638      * <p>Calling with a {@code null} value for the set disables the restriction so that all
11639      * packages are allowed to access cross-profile calendar APIs. Calling with an empty set
11640      * disallows all packages from accessing cross-profile calendar APIs. If this method isn't
11641      * called, no package is allowed to access cross-profile calendar APIs by default.
11642      *
11643      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11644      * @param packageNames set of packages to be whitelisted
11645      * @throws SecurityException if {@code admin} is not a profile owner
11646      *
11647      * @see #getCrossProfileCalendarPackages(ComponentName)
11648      */
setCrossProfileCalendarPackages(@onNull ComponentName admin, @Nullable Set<String> packageNames)11649     public void setCrossProfileCalendarPackages(@NonNull ComponentName admin,
11650             @Nullable Set<String> packageNames) {
11651         throwIfParentInstance("setCrossProfileCalendarPackages");
11652         if (mService != null) {
11653             try {
11654                 mService.setCrossProfileCalendarPackages(admin, packageNames == null ? null
11655                         : new ArrayList<>(packageNames));
11656             } catch (RemoteException e) {
11657                 throw e.rethrowFromSystemServer();
11658             }
11659         }
11660     }
11661 
11662     /**
11663      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
11664      *
11665      * <p>Called by a profile owner of a managed profile.
11666      *
11667      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11668      * @return the set of names of packages that were previously allowed via
11669      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
11670      * empty set if none have been allowed
11671      * @throws SecurityException if {@code admin} is not a profile owner
11672      *
11673      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
11674      */
getCrossProfileCalendarPackages(@onNull ComponentName admin)11675     public @Nullable Set<String> getCrossProfileCalendarPackages(@NonNull ComponentName admin) {
11676         throwIfParentInstance("getCrossProfileCalendarPackages");
11677         if (mService != null) {
11678             try {
11679                 final List<String> packageNames = mService.getCrossProfileCalendarPackages(admin);
11680                 return packageNames == null ? null : new ArraySet<>(packageNames);
11681             } catch (RemoteException e) {
11682                 throw e.rethrowFromSystemServer();
11683             }
11684         }
11685         return Collections.emptySet();
11686     }
11687 
11688     /**
11689      * Returns if a package is allowed to access cross-profile calendar APIs.
11690      *
11691      * <p>A package is allowed to access cross-profile calendar APIs if it's allowed by
11692      * admins via {@link #setCrossProfileCalendarPackages(ComponentName, Set)} and
11693      * {@link android.provider.Settings.Secure#CROSS_PROFILE_CALENDAR_ENABLED}
11694      * is turned on in the managed profile.
11695      *
11696      * <p>To query for a specific user, use
11697      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
11698      * that user, and get a {@link DevicePolicyManager} from this context.
11699      *
11700      * @param packageName the name of the package
11701      * @return {@code true} if the package is allowed to access cross-profile calendar APIs,
11702      * {@code false} otherwise
11703      *
11704      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
11705      * @see #getCrossProfileCalendarPackages(ComponentName)
11706      * @hide
11707      */
isPackageAllowedToAccessCalendar(@onNull String packageName)11708     public boolean isPackageAllowedToAccessCalendar(@NonNull  String packageName) {
11709         throwIfParentInstance("isPackageAllowedToAccessCalendar");
11710         if (mService != null) {
11711             try {
11712                 return mService.isPackageAllowedToAccessCalendarForUser(packageName,
11713                         myUserId());
11714             } catch (RemoteException e) {
11715                 throw e.rethrowFromSystemServer();
11716             }
11717         }
11718         return false;
11719     }
11720 
11721     /**
11722      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
11723      *
11724      * <p>To query for a specific user, use
11725      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
11726      * that user, and get a {@link DevicePolicyManager} from this context.
11727      *
11728      * @return the set of names of packages that were previously allowed via
11729      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
11730      * empty set if none have been allowed
11731      *
11732      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
11733      * @see #getCrossProfileCalendarPackages(ComponentName)
11734      * @hide
11735      */
getCrossProfileCalendarPackages()11736     public @Nullable Set<String> getCrossProfileCalendarPackages() {
11737         throwIfParentInstance("getCrossProfileCalendarPackages");
11738         if (mService != null) {
11739             try {
11740                 final List<String> packageNames = mService.getCrossProfileCalendarPackagesForUser(
11741                         myUserId());
11742                 return packageNames == null ? null : new ArraySet<>(packageNames);
11743             } catch (RemoteException e) {
11744                 throw e.rethrowFromSystemServer();
11745             }
11746         }
11747         return Collections.emptySet();
11748     }
11749 
11750     /**
11751      * Sets the set of admin-whitelisted package names that are allowed to request user consent for
11752      * cross-profile communication.
11753      *
11754      * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
11755      *
11756      * <p>Previous calls are overridden by each subsequent call to this method.
11757      *
11758      * <p>Note that other apps may be able to request user consent for cross-profile communication
11759      * if they have been explicitly whitelisted by the OEM.
11760      *
11761      * <p>When previously-set cross-profile packages are missing from {@code packageNames}, the
11762      * app-op for {@code INTERACT_ACROSS_PROFILES} will be reset for those packages. This will not
11763      * occur for packages that are whitelisted by the OEM.
11764      *
11765      * @param admin the {@link DeviceAdminReceiver} this request is associated with
11766      * @param packageNames the new cross-profile package names
11767      */
setCrossProfilePackages( @onNull ComponentName admin, @NonNull Set<String> packageNames)11768     public void setCrossProfilePackages(
11769             @NonNull ComponentName admin, @NonNull Set<String> packageNames) {
11770         throwIfParentInstance("setCrossProfilePackages");
11771         if (mService != null) {
11772             try {
11773                 mService.setCrossProfilePackages(admin, new ArrayList<>(packageNames));
11774             } catch (RemoteException e) {
11775                 throw e.rethrowFromSystemServer();
11776             }
11777         }
11778     }
11779 
11780     /**
11781      * Returns the set of package names that the admin has previously set as allowed to request user
11782      * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
11783      * Set)}.
11784      *
11785      * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
11786      *
11787      * <p>Note that other apps not included in the returned set may be able to request user consent
11788      * for cross-profile communication if they have been explicitly whitelisted by the OEM.
11789      *
11790      * @param admin the {@link DeviceAdminReceiver} this request is associated with
11791      * @return the set of package names the admin has previously set as allowed to request user
11792      * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
11793      * Set)}
11794      */
getCrossProfilePackages(@onNull ComponentName admin)11795     public @NonNull Set<String> getCrossProfilePackages(@NonNull ComponentName admin) {
11796         throwIfParentInstance("getCrossProfilePackages");
11797         if (mService != null) {
11798             try {
11799                 return new ArraySet<>(mService.getCrossProfilePackages(admin));
11800             } catch (RemoteException e) {
11801                 throw e.rethrowFromSystemServer();
11802             }
11803         }
11804         return Collections.emptySet();
11805     }
11806 
11807     /**
11808      * Returns the combined set of the following:
11809      * <ul>
11810      * <li>The package names that the admin has previously set as allowed to request user consent
11811      * for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
11812      * Set)}.</li>
11813      * <li>The default package names set by the OEM that are allowed to request user consent for
11814      * cross-profile communication without being explicitly enabled by the admin, via {@link
11815      * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array
11816      * #vendor_cross_profile_apps}.</li>
11817      * </ul>
11818      *
11819      * @return the combined set of whitelisted package names set via
11820      * {@link #setCrossProfilePackages(ComponentName, Set)}, {@link com.android.internal.R.array
11821      * #cross_profile_apps}, and {@link com.android.internal.R.array#vendor_cross_profile_apps}.
11822      *
11823      * @hide
11824      */
11825     @RequiresPermission(anyOf = {
11826             permission.INTERACT_ACROSS_USERS_FULL,
11827             permission.INTERACT_ACROSS_USERS,
11828             permission.INTERACT_ACROSS_PROFILES
11829     })
getAllCrossProfilePackages()11830     public @NonNull Set<String> getAllCrossProfilePackages() {
11831         throwIfParentInstance("getAllCrossProfilePackages");
11832         if (mService != null) {
11833             try {
11834                 return new ArraySet<>(mService.getAllCrossProfilePackages());
11835             } catch (RemoteException e) {
11836                 throw e.rethrowFromSystemServer();
11837             }
11838         }
11839         return Collections.emptySet();
11840     }
11841 
11842     /**
11843      * Returns the default package names set by the OEM that are allowed to request user consent for
11844      * cross-profile communication without being explicitly enabled by the admin, via {@link
11845      * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array
11846      * #vendor_cross_profile_apps}.
11847      *
11848      * @hide
11849      */
getDefaultCrossProfilePackages()11850     public @NonNull Set<String> getDefaultCrossProfilePackages() {
11851         throwIfParentInstance("getDefaultCrossProfilePackages");
11852         if (mService != null) {
11853             try {
11854                 return new ArraySet<>(mService.getDefaultCrossProfilePackages());
11855             } catch (RemoteException e) {
11856                 throw e.rethrowFromSystemServer();
11857             }
11858         }
11859         return Collections.emptySet();
11860     }
11861 
11862     /**
11863      * Returns whether the device is being used as a managed kiosk. These requirements are as
11864      * follows:
11865      * <ul>
11866      *     <li>The device is in Lock Task (therefore there is also a Device Owner app on the
11867      *     device)</li>
11868      *     <li>The Lock Task feature {@link DevicePolicyManager#LOCK_TASK_FEATURE_SYSTEM_INFO} is
11869      *     not enabled, so the system info in the status bar is not visible</li>
11870      *     <li>The device does not have a secure lock screen (e.g. it has no lock screen or has
11871      *     swipe-to-unlock)</li>
11872      *     <li>The device is not in the middle of an ephemeral user session</li>
11873      * </ul>
11874      *
11875      * <p>Publicly-accessible dedicated devices don't have the same privacy model as
11876      * personally-used devices. In particular, user consent popups don't make sense as a barrier to
11877      * accessing persistent data on these devices since the user giving consent and the user whose
11878      * data is on the device are unlikely to be the same. These consent popups prevent the true
11879      * remote management of these devices.
11880      *
11881      * <p>This condition is not sufficient to cover APIs that would access data that only lives for
11882      * the duration of the user's session, since the user has an expectation of privacy in these
11883      * conditions that more closely resembles use of a personal device. In those cases, see {@link
11884      * #isUnattendedManagedKiosk()}.
11885      *
11886      * @hide
11887      */
11888     @SystemApi
11889     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isManagedKiosk()11890     public boolean isManagedKiosk() {
11891         throwIfParentInstance("isManagedKiosk");
11892         if (mService != null) {
11893             try {
11894                 return mService.isManagedKiosk();
11895             } catch (RemoteException e) {
11896                 throw e.rethrowFromSystemServer();
11897             }
11898         }
11899         return false;
11900     }
11901 
11902     /**
11903      * Returns whether the device is being used as an unattended managed kiosk. These requirements
11904      * are as follows:
11905      * <ul>
11906      *     <li>The device is being used as a managed kiosk, as defined at {@link
11907      *     #isManagedKiosk()}</li>
11908      *     <li>The device has not received user input for at least 30 minutes</li>
11909      * </ul>
11910      *
11911      * <p>See {@link #isManagedKiosk()} for context. This is a stronger requirement that also
11912      * ensures that the device hasn't been interacted with recently, making it an appropriate check
11913      * for privacy-sensitive APIs that wouldn't be appropriate during an active user session.
11914      *
11915      * @hide
11916      */
11917     @SystemApi
11918     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isUnattendedManagedKiosk()11919     public boolean isUnattendedManagedKiosk() {
11920         throwIfParentInstance("isUnattendedManagedKiosk");
11921         if (mService != null) {
11922             try {
11923                 return mService.isUnattendedManagedKiosk();
11924             } catch (RemoteException e) {
11925                 throw e.rethrowFromSystemServer();
11926             }
11927         }
11928         return false;
11929     }
11930 
11931     /**
11932      * Starts an activity to view calendar events in the managed profile.
11933      *
11934      * @param eventId the id of the event to be viewed
11935      * @param start the start time of the event
11936      * @param end the end time of the event
11937      * @param allDay if the event is an all-day event
11938      * @param flags flags to be set for the intent
11939      * @return {@code true} if the activity is started successfully, {@code false} otherwise
11940      *
11941      * @see CalendarContract#startViewCalendarEventInManagedProfile(Context, String, long, long,
11942      * long, boolean, int)
11943      *
11944      * @hide
11945      */
startViewCalendarEventInManagedProfile(long eventId, long start, long end, boolean allDay, int flags)11946     public boolean startViewCalendarEventInManagedProfile(long eventId, long start, long end,
11947             boolean allDay, int flags) {
11948         throwIfParentInstance("startViewCalendarEventInManagedProfile");
11949         if (mService != null) {
11950             try {
11951                 return mService.startViewCalendarEventInManagedProfile(mContext.getPackageName(),
11952                         eventId, start, end, allDay, flags);
11953             } catch (RemoteException e) {
11954                 throw e.rethrowFromSystemServer();
11955             }
11956         }
11957         return false;
11958     }
11959 
11960     /**
11961      * Called by Device owner to disable user control over apps. User will not be able to clear
11962      * app data or force-stop packages.
11963      *
11964      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11965      * @param packages The package names for the apps.
11966      * @throws SecurityException if {@code admin} is not a device owner.
11967      */
setUserControlDisabledPackages(@onNull ComponentName admin, @NonNull List<String> packages)11968     public void setUserControlDisabledPackages(@NonNull ComponentName admin,
11969             @NonNull List<String> packages) {
11970         throwIfParentInstance("setUserControlDisabledPackages");
11971         if (mService != null) {
11972             try {
11973                 mService.setUserControlDisabledPackages(admin, packages);
11974             } catch (RemoteException re) {
11975                 throw re.rethrowFromSystemServer();
11976             }
11977         }
11978     }
11979 
11980     /**
11981      * Returns the list of packages over which user control is disabled by the device owner.
11982      *
11983      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11984      * @throws SecurityException if {@code admin} is not a device owner.
11985      */
getUserControlDisabledPackages(@onNull ComponentName admin)11986     public @NonNull List<String> getUserControlDisabledPackages(@NonNull ComponentName admin) {
11987         throwIfParentInstance("getUserControlDisabledPackages");
11988         if (mService != null) {
11989             try {
11990                 return mService.getUserControlDisabledPackages(admin);
11991             } catch (RemoteException re) {
11992                 throw re.rethrowFromSystemServer();
11993             }
11994         }
11995         return Collections.emptyList();
11996     }
11997 
11998     /**
11999      * Called by device owner or profile owner of an organization-owned managed profile to toggle
12000      * Common Criteria mode for the device. When the device is in Common Criteria mode,
12001      * certain device functionalities are tuned to meet the higher
12002      * security level required by Common Criteria certification. For example:
12003      * <ul>
12004      * <li> Bluetooth long term key material is additionally integrity-protected with AES-GCM. </li>
12005      * <li> WiFi configuration store is additionally integrity-protected with AES-GCM. </li>
12006      * </ul>
12007      * Common Criteria mode is disabled by default.
12008      *
12009      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12010      * @param enabled whether Common Criteria mode should be enabled or not.
12011      */
setCommonCriteriaModeEnabled(@onNull ComponentName admin, boolean enabled)12012     public void setCommonCriteriaModeEnabled(@NonNull ComponentName admin, boolean enabled) {
12013         throwIfParentInstance("setCommonCriteriaModeEnabled");
12014         if (mService != null) {
12015             try {
12016                 mService.setCommonCriteriaModeEnabled(admin, enabled);
12017             } catch (RemoteException e) {
12018                 throw e.rethrowFromSystemServer();
12019             }
12020         }
12021     }
12022 
12023     /**
12024      * Returns whether Common Criteria mode is currently enabled. Device owner and profile owner of
12025      * an organization-owned managed profile can query its own Common Criteria mode setting by
12026      * calling this method with its admin {@link ComponentName}. Any caller can obtain the
12027      * aggregated device-wide Common Criteria mode state by passing {@code null} as the
12028      * {@code admin} argument.
12029      *
12030      * @param admin which {@link DeviceAdminReceiver} this request is associated with, or
12031      *     {@code null} if the caller is not a device admin.
12032      * @return {@code true} if Common Criteria mode is enabled, {@code false} otherwise.
12033      */
isCommonCriteriaModeEnabled(@ullable ComponentName admin)12034     public boolean isCommonCriteriaModeEnabled(@Nullable ComponentName admin) {
12035         throwIfParentInstance("isCommonCriteriaModeEnabled");
12036         if (mService != null) {
12037             try {
12038                 return mService.isCommonCriteriaModeEnabled(admin);
12039             } catch (RemoteException e) {
12040                 throw e.rethrowFromSystemServer();
12041             }
12042         }
12043         return false;
12044     }
12045 
12046     /**
12047      * Called by profile owner of an organization-owned managed profile to check whether
12048      * personal apps are suspended.
12049      *
12050      * @return a bitmask of reasons for personal apps suspension or
12051      *     {@link #PERSONAL_APPS_NOT_SUSPENDED} if apps are not suspended.
12052      * @see #setPersonalAppsSuspended
12053      */
getPersonalAppsSuspendedReasons( @onNull ComponentName admin)12054     public @PersonalAppsSuspensionReason int getPersonalAppsSuspendedReasons(
12055             @NonNull ComponentName admin) {
12056         throwIfParentInstance("getPersonalAppsSuspendedReasons");
12057         if (mService != null) {
12058             try {
12059                 return mService.getPersonalAppsSuspendedReasons(admin);
12060             } catch (RemoteException re) {
12061                 throw re.rethrowFromSystemServer();
12062             }
12063         }
12064         return 0;
12065     }
12066 
12067     /**
12068      * Called by a profile owner of an organization-owned managed profile to suspend personal
12069      * apps on the device. When personal apps are suspended the device can only be used for calls.
12070      *
12071      * <p>When personal apps are suspended, an ongoing notification about that is shown to the user.
12072      * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE}
12073      * in the profile owner package. Profile owner implementation that uses personal apps suspension
12074      * must handle this intent.
12075      *
12076      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
12077      * @param suspended Whether personal apps should be suspended.
12078      * @throws IllegalStateException if the profile owner doesn't have an activity that handles
12079      *        {@link #ACTION_CHECK_POLICY_COMPLIANCE}
12080      */
setPersonalAppsSuspended(@onNull ComponentName admin, boolean suspended)12081     public void setPersonalAppsSuspended(@NonNull ComponentName admin, boolean suspended) {
12082         throwIfParentInstance("setPersonalAppsSuspended");
12083         if (mService != null) {
12084             try {
12085                 mService.setPersonalAppsSuspended(admin, suspended);
12086             } catch (RemoteException re) {
12087                 throw re.rethrowFromSystemServer();
12088             }
12089         }
12090     }
12091 
12092     /**
12093      * Called by a profile owner of an organization-owned managed profile to set maximum time
12094      * the profile is allowed to be turned off. If the profile is turned off for longer, personal
12095      * apps are suspended on the device.
12096      *
12097      * <p>When personal apps are suspended, an ongoing notification about that is shown to the user.
12098      * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE}
12099      * in the profile owner package. Profile owner implementation that uses personal apps suspension
12100      * must handle this intent.
12101      *
12102      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
12103      * @param timeoutMillis Maximum time the profile is allowed to be off in milliseconds or 0 if
12104      *        not limited. The minimum non-zero value corresponds to 72 hours. If an admin sets a
12105      *        smaller non-zero vaulue, 72 hours will be set instead.
12106      * @throws IllegalStateException if the profile owner doesn't have an activity that handles
12107      *        {@link #ACTION_CHECK_POLICY_COMPLIANCE}
12108      * @see #setPersonalAppsSuspended
12109      */
setManagedProfileMaximumTimeOff(@onNull ComponentName admin, long timeoutMillis)12110     public void setManagedProfileMaximumTimeOff(@NonNull ComponentName admin, long timeoutMillis) {
12111         throwIfParentInstance("setManagedProfileMaximumTimeOff");
12112         if (mService != null) {
12113             try {
12114                 mService.setManagedProfileMaximumTimeOff(admin, timeoutMillis);
12115             } catch (RemoteException re) {
12116                 throw re.rethrowFromSystemServer();
12117             }
12118         }
12119     }
12120 
12121      /**
12122      * Called by a profile owner of an organization-owned managed profile to get maximum time
12123      * the profile is allowed to be turned off.
12124      *
12125      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
12126      * @return Maximum time the profile is allowed to be off in milliseconds or 0 if not limited.
12127      * @see #setPersonalAppsSuspended
12128      */
getManagedProfileMaximumTimeOff(@onNull ComponentName admin)12129     public long getManagedProfileMaximumTimeOff(@NonNull ComponentName admin) {
12130         throwIfParentInstance("getManagedProfileMaximumTimeOff");
12131         if (mService != null) {
12132             try {
12133                 return mService.getManagedProfileMaximumTimeOff(admin);
12134             } catch (RemoteException re) {
12135                 throw re.rethrowFromSystemServer();
12136             }
12137         }
12138         return 0;
12139     }
12140 
12141     /**
12142      * Returns {@code true} when {@code userId} has a profile owner that is capable of resetting
12143      * password in RUNNING_LOCKED state. For that it should have at least one direct boot aware
12144      * component and have an active password reset token. Can only be called by the system.
12145      * @hide
12146      */
canProfileOwnerResetPasswordWhenLocked(int userId)12147     public boolean canProfileOwnerResetPasswordWhenLocked(int userId) {
12148         if (mService != null) {
12149             try {
12150                 return mService.canProfileOwnerResetPasswordWhenLocked(userId);
12151             } catch (RemoteException re) {
12152                 throw re.rethrowFromSystemServer();
12153             }
12154         }
12155         return false;
12156     }
12157 }
12158