• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.app.admin;
18 
19 import static 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      * NOTE: on {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, this
4267      * method doesn't turn off the screen as it would be a driving safety distraction.
4268      * <p>
4269      * Equivalent to calling {@link #lockNow(int)} with no flags.
4270      *
4271      * @throws SecurityException if the calling application does not own an active administrator
4272      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
4273      */
lockNow()4274     public void lockNow() {
4275         lockNow(0);
4276     }
4277 
4278     /**
4279      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
4280      * this call.
4281      * <p>
4282      * This method secures the device in response to an urgent situation, such as a lost or stolen
4283      * device. After this method is called, the device must be unlocked using strong authentication
4284      * (PIN, pattern, or password). This API is intended for use only by device admins.
4285      * <p>
4286      * From version {@link android.os.Build.VERSION_CODES#R} onwards, the caller must either have
4287      * the LOCK_DEVICE permission or the device must have the device admin feature; if neither is
4288      * true, then the method will return without completing any action. Before version
4289      * {@link android.os.Build.VERSION_CODES#R}, the device needed the device admin feature,
4290      * regardless of the caller's permissions.
4291      * <p>
4292      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
4293      * to be able to call this method; if it has not, a security exception will be thrown.
4294      * <p>
4295      * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
4296      * the device. Device admins who find the device in this state can lock an otherwise-insecure
4297      * device by first calling {@link #resetPassword} to set the password and then lock the device.
4298      * <p>
4299      * This method can be called on the {@link DevicePolicyManager} instance returned by
4300      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile as
4301      * well as the managed profile.
4302      * <p>
4303      * NOTE: In order to lock the parent profile and evict the encryption key of the managed
4304      * profile, {@link #lockNow()} must be called twice: First, {@link #lockNow()} should be called
4305      * on the {@link DevicePolicyManager} instance returned by
4306      * {@link #getParentProfileInstance(ComponentName)}, then {@link #lockNow(int)} should be
4307      * called on the {@link DevicePolicyManager} instance associated with the managed profile,
4308      * with the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag.
4309      * Calling the method twice in this order ensures that all users are locked and does not
4310      * stop the device admin on the managed profile from issuing a second call to lock its own
4311      * profile.
4312      * <p>
4313      * NOTE: on {@link android.content.pm.PackageManager#FEATURE_AUTOMOTIVE automotive builds}, this
4314      * method doesn't turn off the screen as it would be a driving safety distraction.
4315      *
4316      * @param flags May be 0 or {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}.
4317      * @throws SecurityException if the calling application does not own an active administrator
4318      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} or the
4319      *             {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is passed by an application
4320      *             that is not a profile
4321      *             owner of a managed profile.
4322      * @throws IllegalArgumentException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is
4323      *             passed when locking the parent profile.
4324      * @throws UnsupportedOperationException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}
4325      *             flag is passed when {@link #getStorageEncryptionStatus} does not return
4326      *             {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
4327      */
lockNow(@ockNowFlag int flags)4328     public void lockNow(@LockNowFlag int flags) {
4329         if (mService != null) {
4330             try {
4331                 mService.lockNow(flags, mParentInstance);
4332             } catch (RemoteException e) {
4333                 throw e.rethrowFromSystemServer();
4334             }
4335         }
4336     }
4337 
4338     /**
4339      * Flag for {@link #wipeData(int)}: also erase the device's external
4340      * storage (such as SD cards).
4341      */
4342     public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
4343 
4344     /**
4345      * Flag for {@link #wipeData(int)}: also erase the factory reset protection
4346      * data.
4347      *
4348      * <p>This flag may only be set by device owner admins; if it is set by
4349      * other admins a {@link SecurityException} will be thrown.
4350      */
4351     public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
4352 
4353     /**
4354      * Flag for {@link #wipeData(int)}: also erase the device's eUICC data.
4355      */
4356     public static final int WIPE_EUICC = 0x0004;
4357 
4358     /**
4359      * Flag for {@link #wipeData(int)}: won't show reason for wiping to the user.
4360      */
4361     public static final int WIPE_SILENTLY = 0x0008;
4362 
4363     /**
4364      * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
4365      * other users will remain unaffected. Calling from the primary user will cause the device to
4366      * reboot, erasing all device data - including all the secondary users and their data - while
4367      * booting up.
4368      * <p>
4369      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
4370      * be able to call this method; if it has not, a security exception will be thrown.
4371      *
4372      * If the caller is a profile owner of an organization-owned managed profile, it may
4373      * additionally call this method on the parent instance.
4374      * Calling this method on the parent {@link DevicePolicyManager} instance would wipe the
4375      * entire device, while calling it on the current profile instance would relinquish the device
4376      * for personal use, removing the managed profile and all policies set by the profile owner.
4377      *
4378      * @param flags Bit mask of additional options: currently supported flags are
4379      *            {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA},
4380      *            {@link #WIPE_EUICC} and {@link #WIPE_SILENTLY}.
4381      * @throws SecurityException if the calling application does not own an active administrator
4382      *            that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
4383      */
wipeData(int flags)4384     public void wipeData(int flags) {
4385         wipeDataInternal(flags, "");
4386     }
4387 
4388     /**
4389      * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
4390      * other users will remain unaffected, the provided reason for wiping data can be shown to
4391      * user. Calling from the primary user will cause the device to reboot, erasing all device data
4392      * - including all the secondary users and their data - while booting up. In this case, we don't
4393      * show the reason to the user since the device would be factory reset.
4394      * <p>
4395      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
4396      * be able to call this method; if it has not, a security exception will be thrown.
4397      *
4398      * If the caller is a profile owner of an organization-owned managed profile, it may
4399      * additionally call this method on the parent instance.
4400      * Calling this method on the parent {@link DevicePolicyManager} instance would wipe the
4401      * entire device, while calling it on the current profile instance would relinquish the device
4402      * for personal use, removing the managed profile and all policies set by the profile owner.
4403      *
4404      * @param flags Bit mask of additional options: currently supported flags are
4405      *            {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA} and
4406      *            {@link #WIPE_EUICC}.
4407      * @param reason a string that contains the reason for wiping data, which can be
4408      *            presented to the user.
4409      * @throws SecurityException if the calling application does not own an active administrator
4410      *            that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
4411      * @throws IllegalArgumentException if the input reason string is null or empty, or if
4412      *            {@link #WIPE_SILENTLY} is set.
4413      */
wipeData(int flags, @NonNull CharSequence reason)4414     public void wipeData(int flags, @NonNull CharSequence reason) {
4415         Objects.requireNonNull(reason, "reason string is null");
4416         Preconditions.checkStringNotEmpty(reason, "reason string is empty");
4417         Preconditions.checkArgument((flags & WIPE_SILENTLY) == 0, "WIPE_SILENTLY cannot be set");
4418         wipeDataInternal(flags, reason.toString());
4419     }
4420 
4421     /**
4422      * Internal function for both {@link #wipeData(int)} and
4423      * {@link #wipeData(int, CharSequence)} to call.
4424      *
4425      * @see #wipeData(int)
4426      * @see #wipeData(int, CharSequence)
4427      * @hide
4428      */
wipeDataInternal(int flags, @NonNull String wipeReasonForUser)4429     private void wipeDataInternal(int flags, @NonNull String wipeReasonForUser) {
4430         if (mService != null) {
4431             try {
4432                 mService.wipeDataWithReason(flags, wipeReasonForUser, mParentInstance);
4433             } catch (RemoteException e) {
4434                 throw e.rethrowFromSystemServer();
4435             }
4436         }
4437     }
4438 
4439     /**
4440      * Callable by device owner or profile owner of an organization-owned device, to set a
4441      * factory reset protection (FRP) policy. When a new policy is set, the system
4442      * notifies the FRP management agent of a policy change by broadcasting
4443      * {@code ACTION_RESET_PROTECTION_POLICY_CHANGED}.
4444      *
4445      * @param admin  Which {@link DeviceAdminReceiver} this request is associated with.
4446      * @param policy the new FRP policy, or {@code null} to clear the current policy.
4447      * @throws SecurityException if {@code admin} is not a device owner or a profile owner of
4448      *                           an organization-owned device.
4449      * @throws UnsupportedOperationException if factory reset protection is not
4450      *                           supported on the device.
4451      */
setFactoryResetProtectionPolicy(@onNull ComponentName admin, @Nullable FactoryResetProtectionPolicy policy)4452     public void setFactoryResetProtectionPolicy(@NonNull ComponentName admin,
4453             @Nullable FactoryResetProtectionPolicy policy) {
4454         throwIfParentInstance("setFactoryResetProtectionPolicy");
4455         if (mService != null) {
4456             try {
4457                 mService.setFactoryResetProtectionPolicy(admin, policy);
4458             } catch (RemoteException e) {
4459                 throw e.rethrowFromSystemServer();
4460             }
4461         }
4462     }
4463 
4464     /**
4465      * Callable by device owner or profile owner of an organization-owned device, to retrieve
4466      * the current factory reset protection (FRP) policy set previously by
4467      * {@link #setFactoryResetProtectionPolicy}.
4468      * <p>
4469      * This method can also be called by the FRP management agent on device or with the permission
4470      * {@link android.Manifest.permission#MASTER_CLEAR}, in which case, it can pass {@code null}
4471      * as the ComponentName.
4472      *
4473      * @param admin Which {@link DeviceAdminReceiver} this request is associated with or
4474      *              {@code null} if called by the FRP management agent on device or with the
4475      *              permission {@link android.Manifest.permission#MASTER_CLEAR}.
4476      * @return The current FRP policy object or {@code null} if no policy is set.
4477      * @throws SecurityException if {@code admin} is not a device owner, a profile owner of
4478      *                           an organization-owned device or the FRP management agent.
4479      * @throws UnsupportedOperationException if factory reset protection is not
4480      *                           supported on the device.
4481      */
getFactoryResetProtectionPolicy( @ullable ComponentName admin)4482     public @Nullable FactoryResetProtectionPolicy getFactoryResetProtectionPolicy(
4483             @Nullable ComponentName admin) {
4484         throwIfParentInstance("getFactoryResetProtectionPolicy");
4485         if (mService != null) {
4486             try {
4487                 return mService.getFactoryResetProtectionPolicy(admin);
4488             } catch (RemoteException e) {
4489                 throw e.rethrowFromSystemServer();
4490             }
4491         }
4492         return null;
4493     }
4494 
4495     /**
4496      * Called by an application that is administering the device to set the
4497      * global proxy and exclusion list.
4498      * <p>
4499      * The calling device admin must have requested
4500      * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
4501      * this method; if it has not, a security exception will be thrown.
4502      * Only the first device admin can set the proxy. If a second admin attempts
4503      * to set the proxy, the {@link ComponentName} of the admin originally setting the
4504      * proxy will be returned. If successful in setting the proxy, {@code null} will
4505      * be returned.
4506      * The method can be called repeatedly by the device admin alrady setting the
4507      * proxy to update the proxy and exclusion list.
4508      *
4509      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4510      * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
4511      *            Pass Proxy.NO_PROXY to reset the proxy.
4512      * @param exclusionList a list of domains to be excluded from the global proxy.
4513      * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
4514      *            of the device admin that sets the proxy.
4515      * @hide
4516      */
4517     @UnsupportedAppUsage
setGlobalProxy(@onNull ComponentName admin, Proxy proxySpec, List<String> exclusionList )4518     public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
4519             List<String> exclusionList ) {
4520         throwIfParentInstance("setGlobalProxy");
4521         if (proxySpec == null) {
4522             throw new NullPointerException();
4523         }
4524         if (mService != null) {
4525             try {
4526                 String hostSpec;
4527                 String exclSpec;
4528                 if (proxySpec.equals(Proxy.NO_PROXY)) {
4529                     hostSpec = null;
4530                     exclSpec = null;
4531                 } else {
4532                     if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
4533                         throw new IllegalArgumentException();
4534                     }
4535                     InetSocketAddress sa = (InetSocketAddress)proxySpec.address();
4536                     String hostName = sa.getHostName();
4537                     int port = sa.getPort();
4538                     StringBuilder hostBuilder = new StringBuilder();
4539                     hostSpec = hostBuilder.append(hostName)
4540                         .append(":").append(Integer.toString(port)).toString();
4541                     if (exclusionList == null) {
4542                         exclSpec = "";
4543                     } else {
4544                         StringBuilder listBuilder = new StringBuilder();
4545                         boolean firstDomain = true;
4546                         for (String exclDomain : exclusionList) {
4547                             if (!firstDomain) {
4548                                 listBuilder = listBuilder.append(",");
4549                             } else {
4550                                 firstDomain = false;
4551                             }
4552                             listBuilder = listBuilder.append(exclDomain.trim());
4553                         }
4554                         exclSpec = listBuilder.toString();
4555                     }
4556                     if (android.net.Proxy.validate(hostName, Integer.toString(port), exclSpec)
4557                             != android.net.Proxy.PROXY_VALID)
4558                         throw new IllegalArgumentException();
4559                 }
4560                 return mService.setGlobalProxy(admin, hostSpec, exclSpec);
4561             } catch (RemoteException e) {
4562                 throw e.rethrowFromSystemServer();
4563             }
4564         }
4565         return null;
4566     }
4567 
4568     /**
4569      * Set a network-independent global HTTP proxy. This is not normally what you want for typical
4570      * HTTP proxies - they are generally network dependent. However if you're doing something
4571      * unusual like general internal filtering this may be useful. On a private network where the
4572      * proxy is not accessible, you may break HTTP using this.
4573      * <p>
4574      * This method requires the caller to be the device owner.
4575      * <p>
4576      * This proxy is only a recommendation and it is possible that some apps will ignore it.
4577      *
4578      * @see ProxyInfo
4579      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4580      * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A
4581      *            {@code null} value will clear the global HTTP proxy.
4582      * @throws SecurityException if {@code admin} is not the device owner.
4583      */
setRecommendedGlobalProxy(@onNull ComponentName admin, @Nullable ProxyInfo proxyInfo)4584     public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
4585             proxyInfo) {
4586         throwIfParentInstance("setRecommendedGlobalProxy");
4587         if (mService != null) {
4588             try {
4589                 mService.setRecommendedGlobalProxy(admin, proxyInfo);
4590             } catch (RemoteException e) {
4591                 throw e.rethrowFromSystemServer();
4592             }
4593         }
4594     }
4595 
4596     /**
4597      * Returns the component name setting the global proxy.
4598      * @return ComponentName object of the device admin that set the global proxy, or {@code null}
4599      *         if no admin has set the proxy.
4600      * @hide
4601      */
getGlobalProxyAdmin()4602     public @Nullable ComponentName getGlobalProxyAdmin() {
4603         if (mService != null) {
4604             try {
4605                 return mService.getGlobalProxyAdmin(myUserId());
4606             } catch (RemoteException e) {
4607                 throw e.rethrowFromSystemServer();
4608             }
4609         }
4610         return null;
4611     }
4612 
4613     /**
4614      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
4615      * indicating that encryption is not supported.
4616      */
4617     public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
4618 
4619     /**
4620      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
4621      * indicating that encryption is supported, but is not currently active.
4622      */
4623     public static final int ENCRYPTION_STATUS_INACTIVE = 1;
4624 
4625     /**
4626      * Result code for {@link #getStorageEncryptionStatus}:
4627      * indicating that encryption is not currently active, but is currently
4628      * being activated.  This is only reported by devices that support
4629      * encryption of data and only when the storage is currently
4630      * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
4631      * to become encrypted will never return this value.
4632      */
4633     public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
4634 
4635     /**
4636      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
4637      * indicating that encryption is active.
4638      * <p>
4639      * Also see {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
4640      */
4641     public static final int ENCRYPTION_STATUS_ACTIVE = 3;
4642 
4643     /**
4644      * Result code for {@link #getStorageEncryptionStatus}:
4645      * indicating that encryption is active, but an encryption key has not
4646      * been set by the user.
4647      */
4648     public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
4649 
4650     /**
4651      * Result code for {@link #getStorageEncryptionStatus}:
4652      * indicating that encryption is active and the encryption key is tied to the user or profile.
4653      * <p>
4654      * This value is only returned to apps targeting API level 24 and above. For apps targeting
4655      * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the
4656      * encryption key is specific to the user or profile.
4657      */
4658     public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5;
4659 
4660     /**
4661      * Activity action: begin the process of encrypting data on the device.  This activity should
4662      * be launched after using {@link #setStorageEncryption} to request encryption be activated.
4663      * After resuming from this activity, use {@link #getStorageEncryption}
4664      * to check encryption status.  However, on some devices this activity may never return, as
4665      * it may trigger a reboot and in some cases a complete data wipe of the device.
4666      */
4667     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
4668     public static final String ACTION_START_ENCRYPTION
4669             = "android.app.action.START_ENCRYPTION";
4670 
4671     /**
4672      * Activity action: launch the DPC to check policy compliance. This intent is launched when
4673      * the user taps on the notification about personal apps suspension. When handling this intent
4674      * the DPC must check if personal apps should still be suspended and either unsuspend them or
4675      * instruct the user on how to resolve the noncompliance causing the suspension.
4676      *
4677      * @see #setPersonalAppsSuspended
4678      */
4679     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
4680     public static final String ACTION_CHECK_POLICY_COMPLIANCE =
4681             "android.app.action.CHECK_POLICY_COMPLIANCE";
4682 
4683     /**
4684      * Broadcast action: notify managed provisioning that new managed user is created.
4685      *
4686      * @hide
4687      */
4688     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4689     public static final String ACTION_MANAGED_USER_CREATED =
4690             "android.app.action.MANAGED_USER_CREATED";
4691 
4692     /**
4693      * Widgets are enabled in keyguard
4694      */
4695     public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
4696 
4697     /**
4698      * Disable all keyguard widgets. Has no effect starting from
4699      * {@link android.os.Build.VERSION_CODES#LOLLIPOP} since keyguard widget is only supported
4700      * on Android versions lower than 5.0.
4701      */
4702     public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
4703 
4704     /**
4705      * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
4706      */
4707     public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
4708 
4709     /**
4710      * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
4711      */
4712     public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
4713 
4714     /**
4715      * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
4716      */
4717     public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
4718 
4719     /**
4720      * Disable trust agents on secure keyguard screens (e.g. PIN/Pattern/Password).
4721      * By setting this flag alone, all trust agents are disabled. If the admin then wants to
4722      * whitelist specific features of some trust agent, {@link #setTrustAgentConfiguration} can be
4723      * used in conjuction to set trust-agent-specific configurations.
4724      */
4725     public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
4726 
4727     /**
4728      * Disable fingerprint authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
4729      */
4730     public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
4731 
4732     /**
4733      * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
4734      * This flag has no effect starting from version {@link android.os.Build.VERSION_CODES#N}
4735      */
4736     public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
4737 
4738     /**
4739      * Disable face authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
4740      */
4741     public static final int KEYGUARD_DISABLE_FACE = 1 << 7;
4742 
4743     /**
4744      * Disable iris authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
4745      */
4746     public static final int KEYGUARD_DISABLE_IRIS = 1 << 8;
4747 
4748     /**
4749      * NOTE: Please remember to update the DevicePolicyManagerTest's testKeyguardDisabledFeatures
4750      * CTS test when adding to the list above.
4751      */
4752 
4753     /**
4754      * Disable all biometric authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
4755      */
4756     public static final int KEYGUARD_DISABLE_BIOMETRICS =
4757             DevicePolicyManager.KEYGUARD_DISABLE_FACE
4758             | DevicePolicyManager.KEYGUARD_DISABLE_IRIS
4759             | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
4760 
4761     /**
4762      * Disable all current and future keyguard customizations.
4763      */
4764     public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
4765 
4766     /**
4767      * Keyguard features that when set on a non-organization-owned managed profile that doesn't
4768      * have its own challenge will affect the profile's parent user. These can also be set on the
4769      * managed profile's parent {@link DevicePolicyManager} instance to explicitly control the
4770      * parent user.
4771      *
4772      * <p>
4773      * Organization-owned managed profile supports disabling additional keyguard features on the
4774      * parent user as defined in {@link #ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY}.
4775      *
4776      * @hide
4777      */
4778     public static final int NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
4779             DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
4780             | DevicePolicyManager.KEYGUARD_DISABLE_BIOMETRICS;
4781 
4782     /**
4783      * Keyguard features that when set by the profile owner of an organization-owned managed
4784      * profile will affect the profile's parent user if set on the managed profile's parent
4785      * {@link DevicePolicyManager} instance.
4786      *
4787      * @hide
4788      */
4789     public static final int ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY =
4790             DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA
4791                     | DevicePolicyManager.KEYGUARD_DISABLE_SECURE_NOTIFICATIONS;
4792 
4793     /**
4794      * Keyguard features that when set on a normal or organization-owned managed profile, have
4795      * the potential to affect the profile's parent user.
4796      *
4797      * @hide
4798      */
4799     public static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
4800             DevicePolicyManager.NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER
4801                     | DevicePolicyManager.ORG_OWNED_PROFILE_KEYGUARD_FEATURES_PARENT_ONLY;
4802 
4803     /**
4804      * @deprecated This method does not actually modify the storage encryption of the device.
4805      * It has never affected the encryption status of a device.
4806      *
4807      * Called by an application that is administering the device to request that the storage system
4808      * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
4809      * <p>
4810      * When multiple device administrators attempt to control device encryption, the most secure,
4811      * supported setting will always be used. If any device administrator requests device
4812      * encryption, it will be enabled; Conversely, if a device administrator attempts to disable
4813      * device encryption while another device administrator has enabled it, the call to disable will
4814      * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
4815      * <p>
4816      * This policy controls encryption of the secure (application data) storage area. Data written
4817      * to other storage areas may or may not be encrypted, and this policy does not require or
4818      * control the encryption of any other storage areas. There is one exception: If
4819      * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the
4820      * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be
4821      * written to disk within the encrypted storage area.
4822      * <p>
4823      * Important Note: On some devices, it is possible to encrypt storage without requiring the user
4824      * to create a device PIN or Password. In this case, the storage is encrypted, but the
4825      * encryption key may not be fully secured. For maximum security, the administrator should also
4826      * require (and check for) a pattern, PIN, or password.
4827      *
4828      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4829      * @param encrypt true to request encryption, false to release any previous request
4830      * @return the new total request status (for all active admins), or {@link
4831      *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user.
4832      *         Will be one of {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link
4833      *         #ENCRYPTION_STATUS_INACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value
4834      *         of the requests; use {@link #getStorageEncryptionStatus()} to query the actual device
4835      *         state.
4836      *
4837      * @throws SecurityException if {@code admin} is not an active administrator or does not use
4838      *             {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE}
4839      */
4840     @Deprecated
setStorageEncryption(@onNull ComponentName admin, boolean encrypt)4841     public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
4842         throwIfParentInstance("setStorageEncryption");
4843         if (mService != null) {
4844             try {
4845                 return mService.setStorageEncryption(admin, encrypt);
4846             } catch (RemoteException e) {
4847                 throw e.rethrowFromSystemServer();
4848             }
4849         }
4850         return ENCRYPTION_STATUS_UNSUPPORTED;
4851     }
4852 
4853     /**
4854      * @deprecated This method only returns the value set by {@link #setStorageEncryption}.
4855      * It does not actually reflect the storage encryption status.
4856      * Use {@link #getStorageEncryptionStatus} for that.
4857      *
4858      * Called by an application that is administering the device to
4859      * determine the requested setting for secure storage.
4860      *
4861      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
4862      * this will return the requested encryption setting as an aggregate of all active
4863      * administrators.
4864      * @return true if the admin(s) are requesting encryption, false if not.
4865      */
4866     @Deprecated
getStorageEncryption(@ullable ComponentName admin)4867     public boolean getStorageEncryption(@Nullable ComponentName admin) {
4868         throwIfParentInstance("getStorageEncryption");
4869         if (mService != null) {
4870             try {
4871                 return mService.getStorageEncryption(admin, myUserId());
4872             } catch (RemoteException e) {
4873                 throw e.rethrowFromSystemServer();
4874             }
4875         }
4876         return false;
4877     }
4878 
4879     /**
4880      * Called by an application that is administering the device to
4881      * determine the current encryption status of the device.
4882      * <p>
4883      * Depending on the returned status code, the caller may proceed in different
4884      * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
4885      * storage system does not support encryption.  If the
4886      * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
4887      * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
4888      * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
4889      * storage system has enabled encryption but no password is set so further action
4890      * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING},
4891      * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER},
4892      * no further action is required.
4893      *
4894      * @return current status of encryption. The value will be one of
4895      * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
4896      * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
4897      * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
4898      */
getStorageEncryptionStatus()4899     public int getStorageEncryptionStatus() {
4900         throwIfParentInstance("getStorageEncryptionStatus");
4901         return getStorageEncryptionStatus(myUserId());
4902     }
4903 
4904     /** @hide per-user version */
4905     @UnsupportedAppUsage
getStorageEncryptionStatus(int userHandle)4906     public int getStorageEncryptionStatus(int userHandle) {
4907         if (mService != null) {
4908             try {
4909                 return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle);
4910             } catch (RemoteException e) {
4911                 throw e.rethrowFromSystemServer();
4912             }
4913         }
4914         return ENCRYPTION_STATUS_UNSUPPORTED;
4915     }
4916 
4917     /**
4918      * Mark a CA certificate as approved by the device user. This means that they have been notified
4919      * of the installation, were made aware of the risks, viewed the certificate and still wanted to
4920      * keep the certificate on the device.
4921      *
4922      * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to
4923      * this certificate.
4924      *
4925      * @hide
4926      */
approveCaCert(String alias, int userHandle, boolean approval)4927     public boolean approveCaCert(String alias, int userHandle, boolean approval) {
4928         if (mService != null) {
4929             try {
4930                 return mService.approveCaCert(alias, userHandle, approval);
4931             } catch (RemoteException e) {
4932                 throw e.rethrowFromSystemServer();
4933             }
4934         }
4935         return false;
4936     }
4937 
4938     /**
4939      * Check whether a CA certificate has been approved by the device user.
4940      *
4941      * @hide
4942      */
isCaCertApproved(String alias, int userHandle)4943     public boolean isCaCertApproved(String alias, int userHandle) {
4944         if (mService != null) {
4945             try {
4946                 return mService.isCaCertApproved(alias, userHandle);
4947             } catch (RemoteException e) {
4948                 throw e.rethrowFromSystemServer();
4949             }
4950         }
4951         return false;
4952     }
4953 
4954     /**
4955      * Installs the given certificate as a user CA.
4956      * <p>
4957      * Inserted user CAs aren't automatically trusted by apps in Android 7.0 (API level 24) and
4958      * higher. App developers can change the default behavior for an app by adding a
4959      * <a href="{@docRoot}training/articles/security-config.html">Security Configuration
4960      * File</a> to the app manifest file.
4961      *
4962      * The caller must be a profile or device owner on that user, or a delegate package given the
4963      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
4964      * security exception will be thrown.
4965      *
4966      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4967      *              {@code null} if calling from a delegated certificate installer.
4968      * @param certBuffer encoded form of the certificate to install.
4969      *
4970      * @return false if the certBuffer cannot be parsed or installation is
4971      *         interrupted, true otherwise.
4972      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4973      *         owner.
4974      * @see #setDelegatedScopes
4975      * @see #DELEGATION_CERT_INSTALL
4976      */
installCaCert(@ullable ComponentName admin, byte[] certBuffer)4977     public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
4978         throwIfParentInstance("installCaCert");
4979         if (mService != null) {
4980             try {
4981                 return mService.installCaCert(admin, mContext.getPackageName(), certBuffer);
4982             } catch (RemoteException e) {
4983                 throw e.rethrowFromSystemServer();
4984             }
4985         }
4986         return false;
4987     }
4988 
4989     /**
4990      * Uninstalls the given certificate from trusted user CAs, if present.
4991      *
4992      * The caller must be a profile or device owner on that user, or a delegate package given the
4993      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
4994      * security exception will be thrown.
4995      *
4996      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4997      *              {@code null} if calling from a delegated certificate installer.
4998      * @param certBuffer encoded form of the certificate to remove.
4999      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5000      *         owner.
5001      * @see #setDelegatedScopes
5002      * @see #DELEGATION_CERT_INSTALL
5003      */
uninstallCaCert(@ullable ComponentName admin, byte[] certBuffer)5004     public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
5005         throwIfParentInstance("uninstallCaCert");
5006         if (mService != null) {
5007             try {
5008                 final String alias = getCaCertAlias(certBuffer);
5009                 mService.uninstallCaCerts(admin, mContext.getPackageName(), new String[] {alias});
5010             } catch (CertificateException e) {
5011                 Log.w(TAG, "Unable to parse certificate", e);
5012             } catch (RemoteException e) {
5013                 throw e.rethrowFromSystemServer();
5014             }
5015         }
5016     }
5017 
5018     /**
5019      * Returns all CA certificates that are currently trusted, excluding system CA certificates.
5020      * If a user has installed any certificates by other means than device policy these will be
5021      * included too.
5022      *
5023      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5024      *              {@code null} if calling from a delegated certificate installer.
5025      * @return a List of byte[] arrays, each encoding one user CA certificate.
5026      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5027      *         owner.
5028      */
getInstalledCaCerts(@ullable ComponentName admin)5029     public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
5030         final List<byte[]> certs = new ArrayList<byte[]>();
5031         throwIfParentInstance("getInstalledCaCerts");
5032         if (mService != null) {
5033             try {
5034                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
5035                 final TrustedCertificateStore certStore = new TrustedCertificateStore();
5036                 for (String alias : certStore.userAliases()) {
5037                     try {
5038                         certs.add(certStore.getCertificate(alias).getEncoded());
5039                     } catch (CertificateException ce) {
5040                         Log.w(TAG, "Could not encode certificate: " + alias, ce);
5041                     }
5042                 }
5043             } catch (RemoteException re) {
5044                 throw re.rethrowFromSystemServer();
5045             }
5046         }
5047         return certs;
5048     }
5049 
5050     /**
5051      * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
5052      * means other than device policy will also be removed, except for system CA certificates.
5053      *
5054      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5055      *              {@code null} if calling from a delegated certificate installer.
5056      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5057      *         owner.
5058      */
uninstallAllUserCaCerts(@ullable ComponentName admin)5059     public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
5060         throwIfParentInstance("uninstallAllUserCaCerts");
5061         if (mService != null) {
5062             try {
5063                 mService.uninstallCaCerts(admin, mContext.getPackageName(),
5064                         new TrustedCertificateStore().userAliases() .toArray(new String[0]));
5065             } catch (RemoteException re) {
5066                 throw re.rethrowFromSystemServer();
5067             }
5068         }
5069     }
5070 
5071     /**
5072      * Returns whether this certificate is installed as a trusted CA.
5073      *
5074      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5075      *              {@code null} if calling from a delegated certificate installer.
5076      * @param certBuffer encoded form of the certificate to look up.
5077      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5078      *         owner.
5079      */
hasCaCertInstalled(@ullable ComponentName admin, byte[] certBuffer)5080     public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
5081         throwIfParentInstance("hasCaCertInstalled");
5082         if (mService != null) {
5083             try {
5084                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
5085                 return getCaCertAlias(certBuffer) != null;
5086             } catch (RemoteException re) {
5087                 throw re.rethrowFromSystemServer();
5088             } catch (CertificateException ce) {
5089                 Log.w(TAG, "Could not parse certificate", ce);
5090             }
5091         }
5092         return false;
5093     }
5094 
5095     /**
5096      * Called by a device or profile owner, or delegated certificate installer, to install a
5097      * certificate and corresponding private key. All apps within the profile will be able to access
5098      * the certificate and use the private key, given direct user approval.
5099      *
5100      * <p>Access to the installed credentials will not be granted to the caller of this API without
5101      * direct user approval. This is for security - should a certificate installer become
5102      * compromised, certificates it had already installed will be protected.
5103      *
5104      * <p>If the installer must have access to the credentials, call
5105      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead.
5106      *
5107      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
5108      * have been given to access the key and certificates associated with this alias will be
5109      * revoked.
5110      *
5111      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5112      *            {@code null} if calling from a delegated certificate installer.
5113      * @param privKey The private key to install.
5114      * @param cert The certificate to install.
5115      * @param alias The private key alias under which to install the certificate. If a certificate
5116      * with that alias already exists, it will be overwritten.
5117      * @return {@code true} if the keys were installed, {@code false} otherwise.
5118      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5119      *         owner.
5120      * @see #setDelegatedScopes
5121      * @see #DELEGATION_CERT_INSTALL
5122      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate cert, @NonNull String alias)5123     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
5124             @NonNull Certificate cert, @NonNull String alias) {
5125         return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false);
5126     }
5127 
5128     /**
5129      * Called by a device or profile owner, or delegated certificate installer, to install a
5130      * certificate chain and corresponding private key for the leaf certificate. All apps within the
5131      * profile will be able to access the certificate chain and use the private key, given direct
5132      * user approval.
5133      *
5134      * <p>The caller of this API may grant itself access to the certificate and private key
5135      * immediately, without user approval. It is a best practice not to request this unless strictly
5136      * necessary since it opens up additional security vulnerabilities.
5137      *
5138      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
5139      * have been given to access the key and certificates associated with this alias will be
5140      * revoked.
5141      *
5142      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5143      *        {@code null} if calling from a delegated certificate installer.
5144      * @param privKey The private key to install.
5145      * @param certs The certificate chain to install. The chain should start with the leaf
5146      *        certificate and include the chain of trust in order. This will be returned by
5147      *        {@link android.security.KeyChain#getCertificateChain}.
5148      * @param alias The private key alias under which to install the certificate. If a certificate
5149      *        with that alias already exists, it will be overwritten.
5150      * @param requestAccess {@code true} to request that the calling app be granted access to the
5151      *        credentials immediately. Otherwise, access to the credentials will be gated by user
5152      *        approval.
5153      * @return {@code true} if the keys were installed, {@code false} otherwise.
5154      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5155      *         owner.
5156      * @see android.security.KeyChain#getCertificateChain
5157      * @see #setDelegatedScopes
5158      * @see #DELEGATION_CERT_INSTALL
5159      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess)5160     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
5161             @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) {
5162         int flags = INSTALLKEY_SET_USER_SELECTABLE;
5163         if (requestAccess) {
5164             flags |= INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
5165         }
5166         return installKeyPair(admin, privKey, certs, alias, flags);
5167     }
5168 
5169     /**
5170      * Called by a device or profile owner, or delegated certificate installer, to install a
5171      * certificate chain and corresponding private key for the leaf certificate. All apps within the
5172      * profile will be able to access the certificate chain and use the private key, given direct
5173      * user approval (if the user is allowed to select the private key).
5174      *
5175      * <p>The caller of this API may grant itself access to the certificate and private key
5176      * immediately, without user approval. It is a best practice not to request this unless strictly
5177      * necessary since it opens up additional security vulnerabilities.
5178      *
5179      * <p>Include {@link #INSTALLKEY_SET_USER_SELECTABLE} in the {@code flags} argument to allow
5180      * the user to select the key from a dialog.
5181      *
5182      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
5183      * have been given to access the key and certificates associated with this alias will be
5184      * revoked.
5185      *
5186      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5187      *        {@code null} if calling from a delegated certificate installer.
5188      * @param privKey The private key to install.
5189      * @param certs The certificate chain to install. The chain should start with the leaf
5190      *        certificate and include the chain of trust in order. This will be returned by
5191      *        {@link android.security.KeyChain#getCertificateChain}.
5192      * @param alias The private key alias under which to install the certificate. If a certificate
5193      *        with that alias already exists, it will be overwritten.
5194      * @param flags Flags to request that the calling app be granted access to the credentials
5195      *        and set the key to be user-selectable. See {@link #INSTALLKEY_SET_USER_SELECTABLE} and
5196      *        {@link #INSTALLKEY_REQUEST_CREDENTIALS_ACCESS}.
5197      * @return {@code true} if the keys were installed, {@code false} otherwise.
5198      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5199      *         owner.
5200      * @see android.security.KeyChain#getCertificateChain
5201      * @see #setDelegatedScopes
5202      * @see #DELEGATION_CERT_INSTALL
5203      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, int flags)5204     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
5205             @NonNull Certificate[] certs, @NonNull String alias, int flags) {
5206         throwIfParentInstance("installKeyPair");
5207         boolean requestAccess = (flags & INSTALLKEY_REQUEST_CREDENTIALS_ACCESS)
5208                 == INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
5209         boolean isUserSelectable = (flags & INSTALLKEY_SET_USER_SELECTABLE)
5210                 == INSTALLKEY_SET_USER_SELECTABLE;
5211         try {
5212             final byte[] pemCert = Credentials.convertToPem(certs[0]);
5213             byte[] pemChain = null;
5214             if (certs.length > 1) {
5215                 pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length));
5216             }
5217             final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
5218                     .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
5219             return mService.installKeyPair(admin, mContext.getPackageName(), pkcs8Key, pemCert,
5220                     pemChain, alias, requestAccess, isUserSelectable);
5221         } catch (RemoteException e) {
5222             throw e.rethrowFromSystemServer();
5223         } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
5224             Log.w(TAG, "Failed to obtain private key material", e);
5225         } catch (CertificateException | IOException e) {
5226             Log.w(TAG, "Could not pem-encode certificate", e);
5227         }
5228         return false;
5229     }
5230 
5231     /**
5232      * Called by a device or profile owner, or delegated certificate installer, to remove a
5233      * certificate and private key pair installed under a given alias.
5234      *
5235      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5236      *        {@code null} if calling from a delegated certificate installer.
5237      * @param alias The private key alias under which the certificate is installed.
5238      * @return {@code true} if the private key alias no longer exists, {@code false} otherwise.
5239      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5240      *         owner.
5241      * @see #setDelegatedScopes
5242      * @see #DELEGATION_CERT_INSTALL
5243      */
removeKeyPair(@ullable ComponentName admin, @NonNull String alias)5244     public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
5245         throwIfParentInstance("removeKeyPair");
5246         try {
5247             return mService.removeKeyPair(admin, mContext.getPackageName(), alias);
5248         } catch (RemoteException e) {
5249             throw e.rethrowFromSystemServer();
5250         }
5251     }
5252 
5253     /**
5254      * Called by a device or profile owner, or delegated certificate installer, to generate a
5255      * new private/public key pair. If the device supports key generation via secure hardware,
5256      * this method is useful for creating a key in KeyChain that never left the secure hardware.
5257      * Access to the key is controlled the same way as in {@link #installKeyPair}.
5258      *
5259      * <p>Because this method might take several seconds to complete, it should only be called from
5260      * a worker thread. This method returns {@code null} when called from the main thread.
5261      *
5262      * <p>This method is not thread-safe, calling it from multiple threads at the same time will
5263      * result in undefined behavior. If the calling thread is interrupted while the invocation is
5264      * in-flight, it will eventually terminate and return {@code null}.
5265      *
5266      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
5267      * have been given to access the key and certificates associated with this alias will be
5268      * revoked.
5269      *
5270      * <p>Attestation: to enable attestation, set an attestation challenge in {@code keySpec} via
5271      * {@link KeyGenParameterSpec.Builder#setAttestationChallenge}. By specifying flags to the
5272      * {@code idAttestationFlags} parameter, it is possible to request the device's unique
5273      * identity to be included in the attestation record.
5274      *
5275      * <p>Specific identifiers can be included in the attestation record, and an individual
5276      * attestation certificate can be used to sign the attestation record. To find out if the device
5277      * supports these features, refer to {@link #isDeviceIdAttestationSupported()} and
5278      * {@link #isUniqueDeviceAttestationSupported()}.
5279      *
5280      * <p>Device owner, profile owner and their delegated certificate installer can use
5281      * {@link #ID_TYPE_BASE_INFO} to request inclusion of the general device information
5282      * including manufacturer, model, brand, device and product in the attestation record.
5283      * Only device owner, profile owner on an organization-owned device and their delegated
5284      * certificate installers can use {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and
5285      * {@link #ID_TYPE_MEID} to request unique device identifiers to be attested (the serial number,
5286      * IMEI and MEID correspondingly), if supported by the device
5287      * (see {@link #isDeviceIdAttestationSupported()}).
5288      * Additionally, device owner, profile owner on an organization-owned device and their delegated
5289      * certificate installers can also request the attestation record to be signed using an
5290      * individual attestation certificate by specifying the {@link #ID_TYPE_INDIVIDUAL_ATTESTATION}
5291      * flag (if supported by the device, see {@link #isUniqueDeviceAttestationSupported()}).
5292      * <p>
5293      * If any of {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID}
5294      * is set, it is implicitly assumed that {@link #ID_TYPE_BASE_INFO} is also set.
5295      * <p>
5296      * Attestation using {@link #ID_TYPE_INDIVIDUAL_ATTESTATION} can only be requested if
5297      * key generation is done in StrongBox.
5298      *
5299      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5300      *            {@code null} if calling from a delegated certificate installer.
5301      * @param algorithm The key generation algorithm, see {@link java.security.KeyPairGenerator}.
5302      * @param keySpec Specification of the key to generate, see
5303      * {@link java.security.KeyPairGenerator}.
5304      * @param idAttestationFlags A bitmask of the identifiers that should be included in the
5305      *        attestation record ({@code ID_TYPE_BASE_INFO}, {@code ID_TYPE_SERIAL},
5306      *        {@code ID_TYPE_IMEI} and {@code ID_TYPE_MEID}), and
5307      *        {@code ID_TYPE_INDIVIDUAL_ATTESTATION} if the attestation record should be signed
5308      *        using an individual attestation certificate.
5309      *        <p>
5310      *        {@code 0} should be passed in if no device identification is required in the
5311      *        attestation record and the batch attestation certificate should be used.
5312      *        <p>
5313      *        If any flag is specified, then an attestation challenge must be included in the
5314      *        {@code keySpec}.
5315      * @return A non-null {@code AttestedKeyPair} if the key generation succeeded, null otherwise.
5316      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5317      *         owner. If Device ID attestation is requested (using {@link #ID_TYPE_SERIAL},
5318      *         {@link #ID_TYPE_IMEI} or {@link #ID_TYPE_MEID}), the caller must be the Device Owner
5319      *         or the Certificate Installer delegate.
5320      * @throws IllegalArgumentException in the following cases:
5321      *         <p>
5322      *         <ul>
5323      *         <li>The alias in {@code keySpec} is empty.</li>
5324      *         <li>The algorithm specification in {@code keySpec} is not
5325      *         {@code RSAKeyGenParameterSpec} or {@code ECGenParameterSpec}.</li>
5326      *         <li>Device ID attestation was requested but the {@code keySpec} does not contain an
5327      *         attestation challenge.</li>
5328      *         </ul>
5329      * @throws UnsupportedOperationException if Device ID attestation or individual attestation
5330      *         was requested but the underlying hardware does not support it.
5331      * @throws StrongBoxUnavailableException if the use of StrongBox for key generation was
5332      *         specified in {@code keySpec} but the device does not have one.
5333      * @see KeyGenParameterSpec.Builder#setAttestationChallenge(byte[])
5334      */
generateKeyPair(@ullable ComponentName admin, @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec, @AttestationIdType int idAttestationFlags)5335     public AttestedKeyPair generateKeyPair(@Nullable ComponentName admin,
5336             @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec,
5337             @AttestationIdType int idAttestationFlags) {
5338         throwIfParentInstance("generateKeyPair");
5339         try {
5340             final ParcelableKeyGenParameterSpec parcelableSpec =
5341                     new ParcelableKeyGenParameterSpec(keySpec);
5342             KeymasterCertificateChain attestationChain = new KeymasterCertificateChain();
5343 
5344             // Translate ID attestation flags to values used by AttestationUtils
5345             final boolean success = mService.generateKeyPair(
5346                     admin, mContext.getPackageName(), algorithm, parcelableSpec,
5347                     idAttestationFlags, attestationChain);
5348             if (!success) {
5349                 Log.e(TAG, "Error generating key via DevicePolicyManagerService.");
5350                 return null;
5351             }
5352 
5353             final String alias = keySpec.getKeystoreAlias();
5354             final KeyPair keyPair = KeyChain.getKeyPair(mContext, alias);
5355             Certificate[] outputChain = null;
5356             try {
5357                 if (AttestationUtils.isChainValid(attestationChain)) {
5358                     outputChain = AttestationUtils.parseCertificateChain(attestationChain);
5359                 }
5360             } catch (KeyAttestationException e) {
5361                 Log.e(TAG, "Error parsing attestation chain for alias " + alias, e);
5362                 mService.removeKeyPair(admin, mContext.getPackageName(), alias);
5363                 return null;
5364             }
5365             return new AttestedKeyPair(keyPair, outputChain);
5366         } catch (RemoteException e) {
5367             throw e.rethrowFromSystemServer();
5368         } catch (KeyChainException e) {
5369             Log.w(TAG, "Failed to generate key", e);
5370         } catch (InterruptedException e) {
5371             Log.w(TAG, "Interrupted while generating key", e);
5372             Thread.currentThread().interrupt();
5373         } catch (ServiceSpecificException e) {
5374             Log.w(TAG, String.format("Key Generation failure: %d", e.errorCode));
5375             switch (e.errorCode) {
5376                 case KEY_GEN_STRONGBOX_UNAVAILABLE:
5377                     throw new StrongBoxUnavailableException("No StrongBox for key generation.");
5378                 default:
5379                     throw new RuntimeException(
5380                             String.format("Unknown error while generating key: %d", e.errorCode));
5381             }
5382         }
5383         return null;
5384     }
5385 
5386 
5387     /**
5388      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
5389      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to grant an application access
5390      * to an already-installed (or generated) KeyChain key.
5391      * This is useful (in combination with {@link #installKeyPair} or {@link #generateKeyPair}) to
5392      * let an application call {@link android.security.KeyChain#getPrivateKey} without having to
5393      * call {@link android.security.KeyChain#choosePrivateKeyAlias} first.
5394      *
5395      * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED}
5396      * broadcast when access to a key is granted.
5397      *
5398      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5399      *        {@code null} if calling from a delegated certificate installer.
5400      * @param alias The alias of the key to grant access to.
5401      * @param packageName The name of the (already installed) package to grant access to.
5402      * @return {@code true} if the grant was set successfully, {@code false} otherwise.
5403      *
5404      * @throws SecurityException if the caller is not a device owner, a profile owner or
5405      *         delegated certificate chooser.
5406      * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if
5407      *         {@code packageName} is not a name of an installed package.
5408      * @see #revokeKeyPairFromApp
5409      */
grantKeyPairToApp(@ullable ComponentName admin, @NonNull String alias, @NonNull String packageName)5410     public boolean grantKeyPairToApp(@Nullable ComponentName admin, @NonNull String alias,
5411             @NonNull String packageName) {
5412         throwIfParentInstance("grantKeyPairToApp");
5413         try {
5414             return mService.setKeyGrantForApp(
5415                     admin, mContext.getPackageName(), alias, packageName, true);
5416         } catch (RemoteException e) {
5417             e.rethrowFromSystemServer();
5418         }
5419         return false;
5420     }
5421 
5422     /**
5423      * Called by a device or profile owner, or delegated certificate chooser (an app that has been
5424      * delegated the {@link #DELEGATION_CERT_SELECTION} privilege), to revoke an application's
5425      * grant to a KeyChain key pair.
5426      * Calls by the application to {@link android.security.KeyChain#getPrivateKey}
5427      * will fail after the grant is revoked.
5428      *
5429      * The grantee app will receive the {@link android.security.KeyChain#ACTION_KEY_ACCESS_CHANGED}
5430      * broadcast when access to a key is revoked.
5431      *
5432      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5433      *        {@code null} if calling from a delegated certificate installer.
5434      * @param alias The alias of the key to revoke access from.
5435      * @param packageName The name of the (already installed) package to revoke access from.
5436      * @return {@code true} if the grant was revoked successfully, {@code false} otherwise.
5437      *
5438      * @throws SecurityException if the caller is not a device owner, a profile owner or
5439      *         delegated certificate chooser.
5440      * @throws IllegalArgumentException if {@code packageName} or {@code alias} are empty, or if
5441      *         {@code packageName} is not a name of an installed package.
5442      * @see #grantKeyPairToApp
5443      */
revokeKeyPairFromApp(@ullable ComponentName admin, @NonNull String alias, @NonNull String packageName)5444     public boolean revokeKeyPairFromApp(@Nullable ComponentName admin, @NonNull String alias,
5445             @NonNull String packageName) {
5446         throwIfParentInstance("revokeKeyPairFromApp");
5447         try {
5448             return mService.setKeyGrantForApp(
5449                     admin, mContext.getPackageName(), alias, packageName, false);
5450         } catch (RemoteException e) {
5451             e.rethrowFromSystemServer();
5452         }
5453         return false;
5454     }
5455 
5456     /**
5457      * Returns {@code true} if the device supports attestation of device identifiers in addition
5458      * to key attestation. See
5459      * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}
5460      * @return {@code true} if Device ID attestation is supported.
5461      */
isDeviceIdAttestationSupported()5462     public boolean isDeviceIdAttestationSupported() {
5463         PackageManager pm = mContext.getPackageManager();
5464         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ID_ATTESTATION);
5465     }
5466 
5467     /**
5468      * Returns {@code true} if the StrongBox Keymaster implementation on the device was provisioned
5469      * with an individual attestation certificate and can sign attestation records using it (as
5470      * attestation using an individual attestation certificate is a feature only Keymaster
5471      * implementations with StrongBox security level can implement).
5472      * For use prior to calling
5473      * {@link #generateKeyPair(ComponentName, String, KeyGenParameterSpec, int)}.
5474      * @return {@code true} if individual attestation is supported.
5475      */
isUniqueDeviceAttestationSupported()5476     public boolean isUniqueDeviceAttestationSupported() {
5477         PackageManager pm = mContext.getPackageManager();
5478         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_UNIQUE_ATTESTATION);
5479     }
5480 
5481     /**
5482      * Called by a device or profile owner, or delegated certificate installer, to associate
5483      * certificates with a key pair that was generated using {@link #generateKeyPair}, and
5484      * set whether the key is available for the user to choose in the certificate selection
5485      * prompt.
5486      *
5487      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5488      *            {@code null} if calling from a delegated certificate installer.
5489      * @param alias The private key alias under which to install the certificate. The {@code alias}
5490      *        should denote an existing private key. If a certificate with that alias already
5491      *        exists, it will be overwritten.
5492      * @param certs The certificate chain to install. The chain should start with the leaf
5493      *        certificate and include the chain of trust in order. This will be returned by
5494      *        {@link android.security.KeyChain#getCertificateChain}.
5495      * @param isUserSelectable {@code true} to indicate that a user can select this key via the
5496      *        certificate selection prompt, {@code false} to indicate that this key can only be
5497      *        granted access by implementing
5498      *        {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
5499      * @return {@code true} if the provided {@code alias} exists and the certificates has been
5500      *        successfully associated with it, {@code false} otherwise.
5501      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5502      *         owner, or {@code admin} is null but the calling application is not a delegated
5503      *         certificate installer.
5504      */
setKeyPairCertificate(@ullable ComponentName admin, @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable)5505     public boolean setKeyPairCertificate(@Nullable ComponentName admin,
5506             @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable) {
5507         throwIfParentInstance("setKeyPairCertificate");
5508         try {
5509             final byte[] pemCert = Credentials.convertToPem(certs.get(0));
5510             byte[] pemChain = null;
5511             if (certs.size() > 1) {
5512                 pemChain = Credentials.convertToPem(
5513                         certs.subList(1, certs.size()).toArray(new Certificate[0]));
5514             }
5515             return mService.setKeyPairCertificate(admin, mContext.getPackageName(), alias, pemCert,
5516                     pemChain, isUserSelectable);
5517         } catch (RemoteException e) {
5518             throw e.rethrowFromSystemServer();
5519         } catch (CertificateException | IOException e) {
5520             Log.w(TAG, "Could not pem-encode certificate", e);
5521         }
5522         return false;
5523     }
5524 
5525 
5526     /**
5527      * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
5528      * doesn't exist.
5529      */
getCaCertAlias(byte[] certBuffer)5530     private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
5531         final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
5532         final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
5533                               new ByteArrayInputStream(certBuffer));
5534         return new TrustedCertificateStore().getCertificateAlias(cert);
5535     }
5536 
5537     /**
5538      * Called by a profile owner or device owner to grant access to privileged certificate
5539      * manipulation APIs to a third-party certificate installer app. Granted APIs include
5540      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
5541      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
5542      * <p>
5543      * Delegated certificate installer is a per-user state. The delegated access is persistent until
5544      * it is later cleared by calling this method with a null value or uninstallling the certificate
5545      * installer.
5546      * <p>
5547      * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
5548      * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
5549      * supplied certificate installer package must be installed when calling this API, otherwise an
5550      * {@link IllegalArgumentException} will be thrown.
5551      *
5552      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5553      * @param installerPackage The package name of the certificate installer which will be given
5554      *            access. If {@code null} is given the current package will be cleared.
5555      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5556      *
5557      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
5558      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
5559      */
5560     @Deprecated
setCertInstallerPackage(@onNull ComponentName admin, @Nullable String installerPackage)5561     public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
5562             installerPackage) throws SecurityException {
5563         throwIfParentInstance("setCertInstallerPackage");
5564         if (mService != null) {
5565             try {
5566                 mService.setCertInstallerPackage(admin, installerPackage);
5567             } catch (RemoteException e) {
5568                 throw e.rethrowFromSystemServer();
5569             }
5570         }
5571     }
5572 
5573     /**
5574      * Called by a profile owner or device owner to retrieve the certificate installer for the user,
5575      * or {@code null} if none is set. If there are multiple delegates this function will return one
5576      * of them.
5577      *
5578      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5579      * @return The package name of the current delegated certificate installer, or {@code null} if
5580      *         none is set.
5581      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5582      *
5583      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
5584      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
5585      */
5586     @Deprecated
getCertInstallerPackage(@onNull ComponentName admin)5587     public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
5588             throws SecurityException {
5589         throwIfParentInstance("getCertInstallerPackage");
5590         if (mService != null) {
5591             try {
5592                 return mService.getCertInstallerPackage(admin);
5593             } catch (RemoteException e) {
5594                 throw e.rethrowFromSystemServer();
5595             }
5596         }
5597         return null;
5598     }
5599 
5600     /**
5601      * Called by a profile owner or device owner to grant access to privileged APIs to another app.
5602      * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*}
5603      * constants.
5604      * <p>
5605      * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be
5606      * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra
5607      * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the
5608      * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag.
5609      * <p>
5610      * Delegated scopes are a per-user state. The delegated access is persistent until it is later
5611      * cleared by calling this method with an empty {@code scopes} list or uninstalling the
5612      * {@code delegatePackage}.
5613      *
5614      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5615      * @param delegatePackage The package name of the app which will be given access.
5616      * @param scopes The groups of privileged APIs whose access should be granted to
5617      *            {@code delegatedPackage}.
5618      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5619      */
setDelegatedScopes(@onNull ComponentName admin, @NonNull String delegatePackage, @NonNull List<String> scopes)5620      public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage,
5621             @NonNull List<String> scopes) {
5622         throwIfParentInstance("setDelegatedScopes");
5623         if (mService != null) {
5624             try {
5625                 mService.setDelegatedScopes(admin, delegatePackage, scopes);
5626             } catch (RemoteException e) {
5627                 throw e.rethrowFromSystemServer();
5628             }
5629         }
5630     }
5631 
5632     /**
5633      * Called by a profile owner or device owner to retrieve a list of the scopes given to a
5634      * delegate package. Other apps can use this method to retrieve their own delegated scopes by
5635      * passing {@code null} for {@code admin} and their own package name as
5636      * {@code delegatedPackage}.
5637      *
5638      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5639      *            {@code null} if the caller is {@code delegatedPackage}.
5640      * @param delegatedPackage The package name of the app whose scopes should be retrieved.
5641      * @return A list containing the scopes given to {@code delegatedPackage}.
5642      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5643      */
5644      @NonNull
getDelegatedScopes(@ullable ComponentName admin, @NonNull String delegatedPackage)5645      public List<String> getDelegatedScopes(@Nullable ComponentName admin,
5646              @NonNull String delegatedPackage) {
5647          throwIfParentInstance("getDelegatedScopes");
5648          if (mService != null) {
5649              try {
5650                  return mService.getDelegatedScopes(admin, delegatedPackage);
5651              } catch (RemoteException e) {
5652                  throw e.rethrowFromSystemServer();
5653              }
5654          }
5655          return null;
5656     }
5657 
5658     /**
5659      * Called by a profile owner or device owner to retrieve a list of delegate packages that were
5660      * granted a delegation scope.
5661      *
5662      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5663      * @param delegationScope The scope whose delegates should be retrieved.
5664      * @return A list of package names of the current delegated packages for
5665                {@code delegationScope}.
5666      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5667      */
5668      @Nullable
getDelegatePackages(@onNull ComponentName admin, @NonNull String delegationScope)5669      public List<String> getDelegatePackages(@NonNull ComponentName admin,
5670              @NonNull String delegationScope) {
5671         throwIfParentInstance("getDelegatePackages");
5672         if (mService != null) {
5673             try {
5674                 return mService.getDelegatePackages(admin, delegationScope);
5675             } catch (RemoteException e) {
5676                 throw e.rethrowFromSystemServer();
5677             }
5678         }
5679         return null;
5680     }
5681 
5682     /**
5683      * Service-specific error code used in implementation of {@code setAlwaysOnVpnPackage} methods.
5684      * @hide
5685      */
5686     public static final int ERROR_VPN_PACKAGE_NOT_FOUND = 1;
5687 
5688     /**
5689      * Called by a device or profile owner to configure an always-on VPN connection through a
5690      * specific application for the current user. This connection is automatically granted and
5691      * persisted after a reboot.
5692      * <p> To support the always-on feature, an app must
5693      * <ul>
5694      *     <li>declare a {@link android.net.VpnService} in its manifest, guarded by
5695      *         {@link android.Manifest.permission#BIND_VPN_SERVICE};</li>
5696      *     <li>target {@link android.os.Build.VERSION_CODES#N API 24} or above; and</li>
5697      *     <li><i>not</i> explicitly opt out of the feature through
5698      *         {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}.</li>
5699      * </ul>
5700      * The call will fail if called with the package name of an unsupported VPN app.
5701      * <p> Enabling lockdown via {@code lockdownEnabled} argument carries the risk that any failure
5702      * of the VPN provider could break networking for all apps. This method clears any lockdown
5703      * whitelist set by {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)}.
5704      *
5705      * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
5706      *        remove an existing always-on VPN configuration.
5707      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
5708      *        {@code false} otherwise. This has no effect when clearing.
5709      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5710      * @throws NameNotFoundException if {@code vpnPackage} is not installed.
5711      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
5712      *         set as always-on, or if always-on VPN is not available.
5713      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
5714      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled)5715     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
5716             boolean lockdownEnabled) throws NameNotFoundException {
5717         setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled, Collections.emptySet());
5718     }
5719 
5720     /**
5721      * A version of {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} that allows the
5722      * admin to specify a set of apps that should be able to access the network directly when VPN
5723      * is not connected. When VPN connects these apps switch over to VPN if allowed to use that VPN.
5724      * System apps can always bypass VPN.
5725      * <p> Note that the system doesn't update the whitelist when packages are installed or
5726      * uninstalled, the admin app must call this method to keep the list up to date.
5727      * <p> When {@code lockdownEnabled} is false {@code lockdownWhitelist} is ignored . When
5728      * {@code lockdownEnabled} is {@code true} and {@code lockdownWhitelist} is {@code null} or
5729      * empty, only system apps can bypass VPN.
5730      * <p> Setting always-on VPN package to {@code null} or using
5731      * {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} clears lockdown whitelist.
5732      *
5733      * @param vpnPackage package name for an installed VPN app on the device, or {@code null}
5734      *         to remove an existing always-on VPN configuration
5735      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
5736      *         {@code false} otherwise. This has no effect when clearing.
5737      * @param lockdownWhitelist Packages that will be able to access the network directly when VPN
5738      *         is in lockdown mode but not connected. Has no effect when clearing.
5739      * @throws SecurityException if {@code admin} is not a device or a profile
5740      *         owner.
5741      * @throws NameNotFoundException if {@code vpnPackage} or one of
5742      *         {@code lockdownWhitelist} is not installed.
5743      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does
5744      *         not support being set as always-on, or if always-on VPN is not
5745      *         available.
5746      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled, @Nullable Set<String> lockdownWhitelist)5747     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
5748             boolean lockdownEnabled, @Nullable Set<String> lockdownWhitelist)
5749             throws NameNotFoundException {
5750         throwIfParentInstance("setAlwaysOnVpnPackage");
5751         if (mService != null) {
5752             try {
5753                 mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled,
5754                         lockdownWhitelist == null ? null : new ArrayList<>(lockdownWhitelist));
5755             } catch (ServiceSpecificException e) {
5756                 switch (e.errorCode) {
5757                     case ERROR_VPN_PACKAGE_NOT_FOUND:
5758                         throw new NameNotFoundException(e.getMessage());
5759                     default:
5760                         throw new RuntimeException(
5761                                 "Unknown error setting always-on VPN: " + e.errorCode, e);
5762                 }
5763             } catch (RemoteException e) {
5764                 throw e.rethrowFromSystemServer();
5765             }
5766         }
5767     }
5768 
5769     /**
5770      * Called by device or profile owner to query whether current always-on VPN is configured in
5771      * lockdown mode. Returns {@code false} when no always-on configuration is set.
5772      *
5773      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5774      *
5775      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5776      *
5777      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean)
5778      */
isAlwaysOnVpnLockdownEnabled(@onNull ComponentName admin)5779     public boolean isAlwaysOnVpnLockdownEnabled(@NonNull ComponentName admin) {
5780         throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
5781         if (mService != null) {
5782             try {
5783                 // Starting from Android R, the caller can pass the permission check in
5784                 // DevicePolicyManagerService if it holds android.permission.MAINLINE_NETWORK_STACK.
5785                 // Note that the android.permission.MAINLINE_NETWORK_STACK is a signature permission
5786                 // which is used by the NetworkStack mainline module.
5787                 return mService.isAlwaysOnVpnLockdownEnabled(admin);
5788             } catch (RemoteException e) {
5789                 throw e.rethrowFromSystemServer();
5790             }
5791         }
5792         return false;
5793     }
5794 
5795     /**
5796      * Returns whether the admin has enabled always-on VPN lockdown for the current user.
5797      *
5798      * Only callable by the system.
5799     * @hide
5800     */
5801     @UserHandleAware
isAlwaysOnVpnLockdownEnabled()5802     public boolean isAlwaysOnVpnLockdownEnabled() {
5803         throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
5804         if (mService != null) {
5805             try {
5806                 return mService.isAlwaysOnVpnLockdownEnabledForUser(myUserId());
5807             } catch (RemoteException e) {
5808                 throw e.rethrowFromSystemServer();
5809             }
5810         }
5811         return false;
5812     }
5813 
5814     /**
5815      * Called by device or profile owner to query the set of packages that are allowed to access
5816      * the network directly when always-on VPN is in lockdown mode but not connected. Returns
5817      * {@code null} when always-on VPN is not active or not in lockdown mode.
5818      *
5819      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5820      *
5821      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5822      *
5823      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
5824      */
getAlwaysOnVpnLockdownWhitelist(@onNull ComponentName admin)5825     public @Nullable Set<String> getAlwaysOnVpnLockdownWhitelist(@NonNull ComponentName admin) {
5826         throwIfParentInstance("getAlwaysOnVpnLockdownWhitelist");
5827         if (mService != null) {
5828             try {
5829                 final List<String> whitelist =
5830                         mService.getAlwaysOnVpnLockdownWhitelist(admin);
5831                 return whitelist == null ? null : new HashSet<>(whitelist);
5832             } catch (RemoteException e) {
5833                 throw e.rethrowFromSystemServer();
5834             }
5835         }
5836         return null;
5837     }
5838 
5839     /**
5840      * Called by a device or profile owner to read the name of the package administering an
5841      * always-on VPN connection for the current user. If there is no such package, or the always-on
5842      * VPN is provided by the system instead of by an application, {@code null} will be returned.
5843      *
5844      * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
5845      *         is set.
5846      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5847      */
getAlwaysOnVpnPackage(@onNull ComponentName admin)5848     public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
5849         throwIfParentInstance("getAlwaysOnVpnPackage");
5850         if (mService != null) {
5851             try {
5852                 return mService.getAlwaysOnVpnPackage(admin);
5853             } catch (RemoteException e) {
5854                 throw e.rethrowFromSystemServer();
5855             }
5856         }
5857         return null;
5858     }
5859 
5860     /**
5861      * Returns the VPN package name if the admin has enabled always-on VPN on the current user,
5862      * or {@code null} if none is set.
5863      *
5864      * Only callable by the system.
5865      * @hide
5866      */
5867     @UserHandleAware
getAlwaysOnVpnPackage()5868     public @Nullable String getAlwaysOnVpnPackage() {
5869         throwIfParentInstance("getAlwaysOnVpnPackage");
5870         if (mService != null) {
5871             try {
5872                 return mService.getAlwaysOnVpnPackageForUser(myUserId());
5873             } catch (RemoteException e) {
5874                 throw e.rethrowFromSystemServer();
5875             }
5876         }
5877         return null;
5878     }
5879 
5880     /**
5881      * Called by an application that is administering the device to disable all cameras on the
5882      * device, for this user. After setting this, no applications running as this user will be able
5883      * to access any cameras on the device.
5884      * <p>
5885      * This method can be called on the {@link DevicePolicyManager} instance,
5886      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
5887      * the profile owner of an organization-owned managed profile.
5888      * <p>
5889      * If the caller is device owner, then the restriction will be applied to all users. If
5890      * called on the parent instance, then the restriction will be applied on the personal profile.
5891      * <p>
5892      * The calling device admin must have requested
5893      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
5894      * not, a security exception will be thrown.
5895      * <p>
5896      * <b>Note</b>, this policy type is deprecated for legacy device admins since
5897      * {@link android.os.Build.VERSION_CODES#Q}. On Android
5898      * {@link android.os.Build.VERSION_CODES#Q} devices, legacy device admins targeting SDK
5899      * version {@link android.os.Build.VERSION_CODES#P} or below can still call this API to
5900      * disable camera, while legacy device admins targeting SDK version
5901      * {@link android.os.Build.VERSION_CODES#Q} will receive a SecurityException. Starting
5902      * from Android {@link android.os.Build.VERSION_CODES#R}, requests to disable camera from
5903      * legacy device admins targeting SDK version {@link android.os.Build.VERSION_CODES#P} or
5904      * below will be silently ignored.
5905      *
5906      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5907      * @param disabled Whether or not the camera should be disabled.
5908      * @throws SecurityException if {@code admin} is not an active administrator or does not use
5909      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
5910      */
setCameraDisabled(@onNull ComponentName admin, boolean disabled)5911     public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
5912         if (mService != null) {
5913             try {
5914                 mService.setCameraDisabled(admin, disabled, mParentInstance);
5915             } catch (RemoteException e) {
5916                 throw e.rethrowFromSystemServer();
5917             }
5918         }
5919     }
5920 
5921     /**
5922      * Determine whether or not the device's cameras have been disabled for this user,
5923      * either by the calling admin, if specified, or all admins.
5924      * <p>
5925      * This method can be called on the {@link DevicePolicyManager} instance,
5926      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
5927      * the profile owner of an organization-owned managed profile.
5928      *
5929      * @param admin The name of the admin component to check, or {@code null} to check whether any admins
5930      * have disabled the camera
5931      */
getCameraDisabled(@ullable ComponentName admin)5932     public boolean getCameraDisabled(@Nullable ComponentName admin) {
5933         return getCameraDisabled(admin, myUserId());
5934     }
5935 
5936     /** @hide per-user version */
5937     @UnsupportedAppUsage
getCameraDisabled(@ullable ComponentName admin, int userHandle)5938     public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
5939         if (mService != null) {
5940             try {
5941                 return mService.getCameraDisabled(admin, userHandle, mParentInstance);
5942             } catch (RemoteException e) {
5943                 throw e.rethrowFromSystemServer();
5944             }
5945         }
5946         return false;
5947     }
5948 
5949     /**
5950      * Called by a device owner to request a bugreport.
5951      * <p>
5952      * If the device contains secondary users or profiles, they must be affiliated with the device.
5953      * Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
5954      *
5955      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5956      * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
5957      *         wasn't triggered because a previous bugreport operation is still active (either the
5958      *         bugreport is still running or waiting for the user to share or decline)
5959      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
5960      *         profile or secondary user that is not affiliated with the device.
5961      * @see #isAffiliatedUser
5962      */
requestBugreport(@onNull ComponentName admin)5963     public boolean requestBugreport(@NonNull ComponentName admin) {
5964         throwIfParentInstance("requestBugreport");
5965         if (mService != null) {
5966             try {
5967                 return mService.requestBugreport(admin);
5968             } catch (RemoteException e) {
5969                 throw e.rethrowFromSystemServer();
5970             }
5971         }
5972         return false;
5973     }
5974 
5975     /**
5976      * Determine whether or not creating a guest user has been disabled for the device
5977      *
5978      * @hide
5979      */
getGuestUserDisabled(@ullable ComponentName admin)5980     public boolean getGuestUserDisabled(@Nullable ComponentName admin) {
5981         // Currently guest users can always be created if multi-user is enabled
5982         // TODO introduce a policy for guest user creation
5983         return false;
5984     }
5985 
5986     /**
5987      * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
5988      * screen capture also prevents the content from being shown on display devices that do not have
5989      * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
5990      * secure surfaces and secure displays.
5991      * <p>
5992      * This method can be called on the {@link DevicePolicyManager} instance, returned by
5993      * {@link #getParentProfileInstance(ComponentName)}, where the calling device admin must be
5994      * the profile owner of an organization-owned managed profile. If it is not, a security
5995      * exception will be thrown.
5996      * <p>
5997      * If the caller is device owner or called on the parent instance by a profile owner of an
5998      * organization-owned managed profile, then the restriction will be applied to all users.
5999      * <p>
6000      * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
6001      * assist requests for all activities of the relevant user.
6002      *
6003      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6004      * @param disabled Whether screen capture is disabled or not.
6005      * @throws SecurityException if {@code admin} is not a device or profile owner or if
6006      *                           called on the parent profile and the {@code admin} is not a
6007      *                           profile owner of an organization-owned managed profile.
6008      */
setScreenCaptureDisabled(@onNull ComponentName admin, boolean disabled)6009     public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
6010         if (mService != null) {
6011             try {
6012                 mService.setScreenCaptureDisabled(admin, disabled, mParentInstance);
6013             } catch (RemoteException e) {
6014                 throw e.rethrowFromSystemServer();
6015             }
6016         }
6017     }
6018 
6019     /**
6020      * Determine whether or not screen capture has been disabled by the calling
6021      * admin, if specified, or all admins.
6022      * <p>
6023      * This method can be called on the {@link DevicePolicyManager} instance,
6024      * returned by {@link #getParentProfileInstance(ComponentName)}, where the caller must be
6025      * the profile owner of an organization-owned managed profile (the calling admin must be
6026      * specified).
6027      *
6028      * @param admin The name of the admin component to check, or {@code null} to check whether any
6029      *              admins have disabled screen capture.
6030      */
getScreenCaptureDisabled(@ullable ComponentName admin)6031     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
6032         return getScreenCaptureDisabled(admin, myUserId());
6033     }
6034 
6035     /** @hide per-user version */
getScreenCaptureDisabled(@ullable ComponentName admin, int userHandle)6036     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
6037         if (mService != null) {
6038             try {
6039                 return mService.getScreenCaptureDisabled(admin, userHandle, mParentInstance);
6040             } catch (RemoteException e) {
6041                 throw e.rethrowFromSystemServer();
6042             }
6043         }
6044         return false;
6045     }
6046 
6047     /**
6048      * Called by a device owner, or alternatively a profile owner from Android 8.0 (API level 26) or
6049      * higher, to set whether auto time is required. If auto time is required, no user will be able
6050      * set the date and time and network date and time will be used.
6051      * <p>
6052      * Note: if auto time is required the user can still manually set the time zone.
6053      * <p>
6054      * The calling device admin must be a device owner, or alternatively a profile owner from
6055      * Android 8.0 (API level 26) or higher. If it is not, a security exception will be thrown.
6056      * <p>
6057      * Staring from Android 11, this API switches to use
6058      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} to enforce the auto time settings. Calling
6059      * this API to enforce auto time will result in
6060      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being set, while calling this API to lift
6061      * the requirement will result in {@link UserManager#DISALLOW_CONFIG_DATE_TIME} being cleared.
6062      * From Android 11, this API can also no longer be called on a managed profile.
6063      *
6064      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6065      * @param required Whether auto time is set required or not.
6066      * @throws SecurityException if {@code admin} is not a device owner, not a profile owner or
6067      * if this API is called on a managed profile.
6068      * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #setAutoTimeEnabled}
6069      * to turn auto time on or off and use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
6070      * to prevent the user from changing this setting.
6071      */
6072     @Deprecated
setAutoTimeRequired(@onNull ComponentName admin, boolean required)6073     public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
6074         throwIfParentInstance("setAutoTimeRequired");
6075         if (mService != null) {
6076             try {
6077                 mService.setAutoTimeRequired(admin, required);
6078             } catch (RemoteException e) {
6079                 throw e.rethrowFromSystemServer();
6080             }
6081         }
6082     }
6083 
6084     /**
6085      * @return true if auto time is required.
6086      * @deprecated From {@link android.os.Build.VERSION_CODES#R}. Use {@link #getAutoTimeEnabled}
6087      */
6088     @Deprecated
getAutoTimeRequired()6089     public boolean getAutoTimeRequired() {
6090         throwIfParentInstance("getAutoTimeRequired");
6091         if (mService != null) {
6092             try {
6093                 return mService.getAutoTimeRequired();
6094             } catch (RemoteException e) {
6095                 throw e.rethrowFromSystemServer();
6096             }
6097         }
6098         return false;
6099     }
6100 
6101     /**
6102      * Called by a device owner, a profile owner for the primary user or a profile
6103      * owner of an organization-owned managed profile to turn auto time on and off.
6104      * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
6105      * to prevent the user from changing this setting.
6106      * <p>
6107      * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
6108      * no user will be able set the date and time. Instead, the network date
6109      * and time will be used.
6110      *
6111      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6112      * @param enabled Whether time should be obtained automatically from the network or not.
6113      * @throws SecurityException if caller is not a device owner, a profile owner for the
6114      * primary user, or a profile owner of an organization-owned managed profile.
6115      */
setAutoTimeEnabled(@onNull ComponentName admin, boolean enabled)6116     public void setAutoTimeEnabled(@NonNull ComponentName admin, boolean enabled) {
6117         if (mService != null) {
6118             try {
6119                 mService.setAutoTimeEnabled(admin, enabled);
6120             } catch (RemoteException e) {
6121                 throw e.rethrowFromSystemServer();
6122             }
6123         }
6124     }
6125 
6126     /**
6127      * @return true if auto time is enabled on the device.
6128      * @throws SecurityException if caller is not a device owner, a profile owner for the
6129      * primary user, or a profile owner of an organization-owned managed profile.
6130      */
getAutoTimeEnabled(@onNull ComponentName admin)6131     public boolean getAutoTimeEnabled(@NonNull ComponentName admin) {
6132         if (mService != null) {
6133             try {
6134                 return mService.getAutoTimeEnabled(admin);
6135             } catch (RemoteException e) {
6136                 throw e.rethrowFromSystemServer();
6137             }
6138         }
6139         return false;
6140     }
6141 
6142     /**
6143      * Called by a device owner, a profile owner for the primary user or a profile
6144      * owner of an organization-owned managed profile to turn auto time zone on and off.
6145      * Callers are recommended to use {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
6146      * to prevent the user from changing this setting.
6147      * <p>
6148      * If user restriction {@link UserManager#DISALLOW_CONFIG_DATE_TIME} is used,
6149      * no user will be able set the date and time zone. Instead, the network date
6150      * and time zone will be used.
6151      *
6152      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6153      * @param enabled Whether time zone should be obtained automatically from the network or not.
6154      * @throws SecurityException if caller is not a device owner, a profile owner for the
6155      * primary user, or a profile owner of an organization-owned managed profile.
6156      */
setAutoTimeZoneEnabled(@onNull ComponentName admin, boolean enabled)6157     public void setAutoTimeZoneEnabled(@NonNull ComponentName admin, boolean enabled) {
6158         throwIfParentInstance("setAutoTimeZone");
6159         if (mService != null) {
6160             try {
6161                 mService.setAutoTimeZoneEnabled(admin, enabled);
6162             } catch (RemoteException e) {
6163                 throw e.rethrowFromSystemServer();
6164             }
6165         }
6166     }
6167 
6168     /**
6169      * @return true if auto time zone is enabled on the device.
6170      * @throws SecurityException if caller is not a device owner, a profile owner for the
6171      * primary user, or a profile owner of an organization-owned managed profile.
6172      */
getAutoTimeZoneEnabled(@onNull ComponentName admin)6173     public boolean getAutoTimeZoneEnabled(@NonNull ComponentName admin) {
6174         throwIfParentInstance("getAutoTimeZone");
6175         if (mService != null) {
6176             try {
6177                 return mService.getAutoTimeZoneEnabled(admin);
6178             } catch (RemoteException e) {
6179                 throw e.rethrowFromSystemServer();
6180             }
6181         }
6182         return false;
6183     }
6184 
6185     /**
6186      * Called by a device owner to set whether all users created on the device should be ephemeral.
6187      * <p>
6188      * The system user is exempt from this policy - it is never ephemeral.
6189      * <p>
6190      * The calling device admin must be the device owner. If it is not, a security exception will be
6191      * thrown.
6192      *
6193      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6194      * @param forceEphemeralUsers If true, all the existing users will be deleted and all
6195      *            subsequently created users will be ephemeral.
6196      * @throws SecurityException if {@code admin} is not a device owner.
6197      * @hide
6198      */
setForceEphemeralUsers( @onNull ComponentName admin, boolean forceEphemeralUsers)6199     public void setForceEphemeralUsers(
6200             @NonNull ComponentName admin, boolean forceEphemeralUsers) {
6201         throwIfParentInstance("setForceEphemeralUsers");
6202         if (mService != null) {
6203             try {
6204                 mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
6205             } catch (RemoteException e) {
6206                 throw e.rethrowFromSystemServer();
6207             }
6208         }
6209     }
6210 
6211     /**
6212      * @return true if all users are created ephemeral.
6213      * @throws SecurityException if {@code admin} is not a device owner.
6214      * @hide
6215      */
getForceEphemeralUsers(@onNull ComponentName admin)6216     public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
6217         throwIfParentInstance("getForceEphemeralUsers");
6218         if (mService != null) {
6219             try {
6220                 return mService.getForceEphemeralUsers(admin);
6221             } catch (RemoteException e) {
6222                 throw e.rethrowFromSystemServer();
6223             }
6224         }
6225         return false;
6226     }
6227 
6228     /**
6229      * Called by an application that is administering the device to disable keyguard customizations,
6230      * such as widgets. After setting this, keyguard features will be disabled according to the
6231      * provided feature list.
6232      * <p>
6233      * The calling device admin must have requested
6234      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
6235      * if it has not, a security exception will be thrown.
6236      * <p>
6237      * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
6238      * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
6239      * profile owner of a managed profile can set:
6240      * <ul>
6241      * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
6242      * is no separate challenge set on the managed profile.
6243      * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FACE} or
6244      * {@link #KEYGUARD_DISABLE_IRIS} which affects the managed profile challenge if
6245      * there is one, or the parent user otherwise.
6246      * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
6247      * by applications in the managed profile.
6248      * </ul>
6249      * <p>
6250      * From version {@link android.os.Build.VERSION_CODES#R} the profile owner of an
6251      * organization-owned managed profile can set:
6252      * <ul>
6253      * <li>{@link #KEYGUARD_DISABLE_SECURE_CAMERA} which affects the parent user when called on the
6254      * parent profile.
6255      * <li>{@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS} which affects the parent user when called
6256      * on the parent profile.
6257      * </ul>
6258      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, {@link #KEYGUARD_DISABLE_FINGERPRINT},
6259      * {@link #KEYGUARD_DISABLE_FACE}, {@link #KEYGUARD_DISABLE_IRIS},
6260      * {@link #KEYGUARD_DISABLE_SECURE_CAMERA} and {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS}
6261      * can also be set on the {@link DevicePolicyManager} instance returned by
6262      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
6263      * profile. {@link #KEYGUARD_DISABLE_SECURE_CAMERA} can only be set on the parent profile
6264      * instance if the calling device admin is the profile owner of an organization-owned
6265      * managed profile.
6266      * <p>
6267      * Requests to disable other features on a managed profile will be ignored.
6268      * <p>
6269      * The admin can check which features have been disabled by calling
6270      * {@link #getKeyguardDisabledFeatures(ComponentName)}
6271      *
6272      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6273      * @param which The disabled features flag which can be either
6274      *            {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
6275      *            {@link #KEYGUARD_DISABLE_FEATURES_ALL}, or a combination of
6276      *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
6277      *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
6278      *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
6279      *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
6280      *            {@link #KEYGUARD_DISABLE_FINGERPRINT},
6281      *            {@link #KEYGUARD_DISABLE_FACE},
6282      *            {@link #KEYGUARD_DISABLE_IRIS}.
6283      * @throws SecurityException if {@code admin} is not an active administrator or does not user
6284      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
6285      */
setKeyguardDisabledFeatures(@onNull ComponentName admin, int which)6286     public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
6287         if (mService != null) {
6288             try {
6289                 mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
6290             } catch (RemoteException e) {
6291                 throw e.rethrowFromSystemServer();
6292             }
6293         }
6294     }
6295 
6296     /**
6297      * Determine whether or not features have been disabled in keyguard either by the calling
6298      * admin, if specified, or all admins that set restrictions on this user and its participating
6299      * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
6300      *
6301      * <p>This method can be called on the {@link DevicePolicyManager} instance
6302      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
6303      * restrictions on the parent profile.
6304      *
6305      * @param admin The name of the admin component to check, or {@code null} to check whether any
6306      * admins have disabled features in keyguard.
6307      * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
6308      * for a list.
6309      */
getKeyguardDisabledFeatures(@ullable ComponentName admin)6310     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
6311         return getKeyguardDisabledFeatures(admin, myUserId());
6312     }
6313 
6314     /** @hide per-user version */
6315     @UnsupportedAppUsage
getKeyguardDisabledFeatures(@ullable ComponentName admin, int userHandle)6316     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
6317         if (mService != null) {
6318             try {
6319                 return mService.getKeyguardDisabledFeatures(admin, userHandle, mParentInstance);
6320             } catch (RemoteException e) {
6321                 throw e.rethrowFromSystemServer();
6322             }
6323         }
6324         return KEYGUARD_DISABLE_FEATURES_NONE;
6325     }
6326 
6327     /**
6328      * @hide
6329      */
6330     @UnsupportedAppUsage
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing, int userHandle)6331     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
6332             int userHandle) {
6333         if (mService != null) {
6334             try {
6335                 mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
6336             } catch (RemoteException e) {
6337                 throw e.rethrowFromSystemServer();
6338             }
6339         }
6340     }
6341 
6342     /**
6343      * @hide
6344      */
6345     @UnsupportedAppUsage
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing)6346     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
6347         setActiveAdmin(policyReceiver, refreshing, myUserId());
6348     }
6349 
6350     /**
6351      * @hide
6352      */
getRemoveWarning(@ullable ComponentName admin, RemoteCallback result)6353     public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
6354         if (mService != null) {
6355             try {
6356                 mService.getRemoveWarning(admin, result, myUserId());
6357             } catch (RemoteException e) {
6358                 throw e.rethrowFromSystemServer();
6359             }
6360         }
6361     }
6362 
6363     /**
6364      * @hide
6365      */
6366     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportPasswordChanged(@serIdInt int userId)6367     public void reportPasswordChanged(@UserIdInt int userId) {
6368         if (mService != null) {
6369             try {
6370                 mService.reportPasswordChanged(userId);
6371             } catch (RemoteException e) {
6372                 throw e.rethrowFromSystemServer();
6373             }
6374         }
6375     }
6376 
6377     /**
6378      * @hide
6379      */
6380     @UnsupportedAppUsage
6381     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedPasswordAttempt(int userHandle)6382     public void reportFailedPasswordAttempt(int userHandle) {
6383         if (mService != null) {
6384             try {
6385                 mService.reportFailedPasswordAttempt(userHandle);
6386             } catch (RemoteException e) {
6387                 throw e.rethrowFromSystemServer();
6388             }
6389         }
6390     }
6391 
6392     /**
6393      * @hide
6394      */
6395     @UnsupportedAppUsage
6396     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulPasswordAttempt(int userHandle)6397     public void reportSuccessfulPasswordAttempt(int userHandle) {
6398         if (mService != null) {
6399             try {
6400                 mService.reportSuccessfulPasswordAttempt(userHandle);
6401             } catch (RemoteException e) {
6402                 throw e.rethrowFromSystemServer();
6403             }
6404         }
6405     }
6406 
6407     /**
6408      * @hide
6409      */
6410     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedBiometricAttempt(int userHandle)6411     public void reportFailedBiometricAttempt(int userHandle) {
6412         if (mService != null) {
6413             try {
6414                 mService.reportFailedBiometricAttempt(userHandle);
6415             } catch (RemoteException e) {
6416                 throw e.rethrowFromSystemServer();
6417             }
6418         }
6419     }
6420 
6421     /**
6422      * @hide
6423      */
6424     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulBiometricAttempt(int userHandle)6425     public void reportSuccessfulBiometricAttempt(int userHandle) {
6426         if (mService != null) {
6427             try {
6428                 mService.reportSuccessfulBiometricAttempt(userHandle);
6429             } catch (RemoteException e) {
6430                 throw e.rethrowFromSystemServer();
6431             }
6432         }
6433     }
6434 
6435     /**
6436      * Should be called when keyguard has been dismissed.
6437      * @hide
6438      */
reportKeyguardDismissed(int userHandle)6439     public void reportKeyguardDismissed(int userHandle) {
6440         if (mService != null) {
6441             try {
6442                 mService.reportKeyguardDismissed(userHandle);
6443             } catch (RemoteException e) {
6444                 throw e.rethrowFromSystemServer();
6445             }
6446         }
6447     }
6448 
6449     /**
6450      * Should be called when keyguard view has been shown to the user.
6451      * @hide
6452      */
reportKeyguardSecured(int userHandle)6453     public void reportKeyguardSecured(int userHandle) {
6454         if (mService != null) {
6455             try {
6456                 mService.reportKeyguardSecured(userHandle);
6457             } catch (RemoteException e) {
6458                 throw e.rethrowFromSystemServer();
6459             }
6460         }
6461     }
6462 
6463     /**
6464      * @hide
6465      * Sets the given package as the device owner.
6466      * Same as {@link #setDeviceOwner(ComponentName, String)} but without setting a device owner name.
6467      * @param who the component name to be registered as device owner.
6468      * @return whether the package was successfully registered as the device owner.
6469      * @throws IllegalArgumentException if the package name is null or invalid
6470      * @throws IllegalStateException If the preconditions mentioned are not met.
6471      */
setDeviceOwner(ComponentName who)6472     public boolean setDeviceOwner(ComponentName who) {
6473         return setDeviceOwner(who, null);
6474     }
6475 
6476     /**
6477      * @hide
6478      */
setDeviceOwner(ComponentName who, int userId)6479     public boolean setDeviceOwner(ComponentName who, int userId)  {
6480         return setDeviceOwner(who, null, userId);
6481     }
6482 
6483     /**
6484      * @hide
6485      */
setDeviceOwner(ComponentName who, String ownerName)6486     public boolean setDeviceOwner(ComponentName who, String ownerName) {
6487         return setDeviceOwner(who, ownerName, UserHandle.USER_SYSTEM);
6488     }
6489 
6490     /**
6491      * @hide
6492      * Sets the given package as the device owner. The package must already be installed. There
6493      * must not already be a device owner.
6494      * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
6495      * this method.
6496      * Calling this after the setup phase of the primary user has completed is allowed only if
6497      * the caller is the shell uid, and there are no additional users and no accounts.
6498      * @param who the component name to be registered as device owner.
6499      * @param ownerName the human readable name of the institution that owns this device.
6500      * @param userId ID of the user on which the device owner runs.
6501      * @return whether the package was successfully registered as the device owner.
6502      * @throws IllegalArgumentException if the package name is null or invalid
6503      * @throws IllegalStateException If the preconditions mentioned are not met.
6504      */
setDeviceOwner(ComponentName who, String ownerName, int userId)6505     public boolean setDeviceOwner(ComponentName who, String ownerName, int userId)
6506             throws IllegalArgumentException, IllegalStateException {
6507         if (mService != null) {
6508             try {
6509                 return mService.setDeviceOwner(who, ownerName, userId);
6510             } catch (RemoteException re) {
6511                 throw re.rethrowFromSystemServer();
6512             }
6513         }
6514         return false;
6515     }
6516 
6517     /**
6518      * Used to determine if a particular package has been registered as a Device Owner app.
6519      * A device owner app is a special device admin that cannot be deactivated by the user, once
6520      * activated as a device admin. It also cannot be uninstalled. To check whether a particular
6521      * package is currently registered as the device owner app, pass in the package name from
6522      * {@link Context#getPackageName()} to this method.<p/>This is useful for device
6523      * admin apps that want to check whether they are also registered as the device owner app. The
6524      * exact mechanism by which a device admin app is registered as a device owner app is defined by
6525      * the setup process.
6526      * @param packageName the package name of the app, to compare with the registered device owner
6527      * app, if any.
6528      * @return whether or not the package is registered as the device owner app.
6529      */
isDeviceOwnerApp(String packageName)6530     public boolean isDeviceOwnerApp(String packageName) {
6531         throwIfParentInstance("isDeviceOwnerApp");
6532         return isDeviceOwnerAppOnCallingUser(packageName);
6533     }
6534 
6535     /**
6536      * @return true if a package is registered as device owner, only when it's running on the
6537      * calling user.
6538      *
6539      * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
6540      * @hide
6541      */
isDeviceOwnerAppOnCallingUser(String packageName)6542     public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
6543         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
6544     }
6545 
6546     /**
6547      * @return true if a package is registered as device owner, even if it's running on a different
6548      * user.
6549      *
6550      * <p>Requires the MANAGE_USERS permission.
6551      *
6552      * @hide
6553      */
isDeviceOwnerAppOnAnyUser(String packageName)6554     public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
6555         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
6556     }
6557 
6558     /**
6559      * @return device owner component name, only when it's running on the calling user.
6560      *
6561      * @hide
6562      */
getDeviceOwnerComponentOnCallingUser()6563     public ComponentName getDeviceOwnerComponentOnCallingUser() {
6564         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
6565     }
6566 
6567     /**
6568      * @return device owner component name, even if it's running on a different user.
6569      *
6570      * @hide
6571      */
6572     @SystemApi
6573     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwnerComponentOnAnyUser()6574     public ComponentName getDeviceOwnerComponentOnAnyUser() {
6575         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
6576     }
6577 
isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly)6578     private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
6579         if (packageName == null) {
6580             return false;
6581         }
6582         final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
6583         if (deviceOwner == null) {
6584             return false;
6585         }
6586         return packageName.equals(deviceOwner.getPackageName());
6587     }
6588 
getDeviceOwnerComponentInner(boolean callingUserOnly)6589     private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
6590         if (mService != null) {
6591             try {
6592                 return mService.getDeviceOwnerComponent(callingUserOnly);
6593             } catch (RemoteException re) {
6594                 throw re.rethrowFromSystemServer();
6595             }
6596         }
6597         return null;
6598     }
6599 
6600     /**
6601      * @return Handle of the user who runs device owner, or {@code null} if there's no device owner.
6602      *
6603      * @hide
6604      */
6605     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
6606     @SystemApi
getDeviceOwnerUser()6607     public @Nullable UserHandle getDeviceOwnerUser() {
6608         if (mService != null) {
6609             try {
6610                 int userId = mService.getDeviceOwnerUserId();
6611 
6612                 if (userId != UserHandle.USER_NULL) {
6613                     return UserHandle.of(userId);
6614                 }
6615             } catch (RemoteException re) {
6616                 throw re.rethrowFromSystemServer();
6617             }
6618         }
6619         return null;
6620     }
6621 
6622     /**
6623      * @hide
6624      */
getDeviceOwnerUserId()6625     public int getDeviceOwnerUserId() {
6626         if (mService != null) {
6627             try {
6628                 return mService.getDeviceOwnerUserId();
6629             } catch (RemoteException re) {
6630                 throw re.rethrowFromSystemServer();
6631             }
6632         }
6633         return UserHandle.USER_NULL;
6634     }
6635 
6636     /**
6637      * Clears the current device owner. The caller must be the device owner. This function should be
6638      * used cautiously as once it is called it cannot be undone. The device owner can only be set as
6639      * a part of device setup, before it completes.
6640      * <p>
6641      * While some policies previously set by the device owner will be cleared by this method, it is
6642      * a best-effort process and some other policies will still remain in place after the device
6643      * owner is cleared.
6644      *
6645      * @param packageName The package name of the device owner.
6646      * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
6647      *             does not own the current device owner component.
6648      *
6649      * @deprecated This method is expected to be used for testing purposes only. The device owner
6650      * will lose control of the device and its data after calling it. In order to protect any
6651      * sensitive data that remains on the device, it is advised that the device owner factory resets
6652      * the device instead of calling this method. See {@link #wipeData(int)}.
6653      */
6654     @Deprecated
clearDeviceOwnerApp(String packageName)6655     public void clearDeviceOwnerApp(String packageName) {
6656         throwIfParentInstance("clearDeviceOwnerApp");
6657         if (mService != null) {
6658             try {
6659                 mService.clearDeviceOwner(packageName);
6660             } catch (RemoteException re) {
6661                 throw re.rethrowFromSystemServer();
6662             }
6663         }
6664     }
6665 
6666     /**
6667      * Returns the device owner package name, only if it's running on the calling user.
6668      *
6669      * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
6670      *
6671      * @hide
6672      */
6673     @SystemApi
6674     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwner()6675     public @Nullable String getDeviceOwner() {
6676         throwIfParentInstance("getDeviceOwner");
6677         final ComponentName name = getDeviceOwnerComponentOnCallingUser();
6678         return name != null ? name.getPackageName() : null;
6679     }
6680 
6681     /**
6682      * Called by the system to find out whether the device is managed by a Device Owner.
6683      *
6684      * @return whether the device is managed by a Device Owner.
6685      * @throws SecurityException if the caller is not the device owner, does not hold the
6686      *         MANAGE_USERS permission and is not the system.
6687      *
6688      * @hide
6689      */
6690     @SystemApi
6691     @TestApi
6692     @SuppressLint("Doclava125")
isDeviceManaged()6693     public boolean isDeviceManaged() {
6694         try {
6695             return mService.hasDeviceOwner();
6696         } catch (RemoteException re) {
6697             throw re.rethrowFromSystemServer();
6698         }
6699     }
6700 
6701     /**
6702      * Returns the device owner name.  Note this method *will* return the device owner
6703      * name when it's running on a different user.
6704      *
6705      * @hide
6706      */
6707     @SystemApi
6708     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwnerNameOnAnyUser()6709     public String getDeviceOwnerNameOnAnyUser() {
6710         throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
6711         if (mService != null) {
6712             try {
6713                 return mService.getDeviceOwnerName();
6714             } catch (RemoteException re) {
6715                 throw re.rethrowFromSystemServer();
6716             }
6717         }
6718         return null;
6719     }
6720 
6721     /**
6722      * @hide
6723      * @deprecated Use #ACTION_SET_PROFILE_OWNER
6724      * Sets the given component as an active admin and registers the package as the profile
6725      * owner for this user. The package must already be installed and there shouldn't be
6726      * an existing profile owner registered for this user. Also, this method must be called
6727      * before the user setup has been completed.
6728      * <p>
6729      * This method can only be called by system apps that hold MANAGE_USERS permission and
6730      * MANAGE_DEVICE_ADMINS permission.
6731      * @param admin The component to register as an active admin and profile owner.
6732      * @param ownerName The user-visible name of the entity that is managing this user.
6733      * @return whether the admin was successfully registered as the profile owner.
6734      * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
6735      *         the user has already been set up.
6736      */
6737     @Deprecated
6738     @SystemApi
6739     @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
setActiveProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName)6740     public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
6741             throws IllegalArgumentException {
6742         throwIfParentInstance("setActiveProfileOwner");
6743         if (mService != null) {
6744             try {
6745                 final int myUserId = myUserId();
6746                 mService.setActiveAdmin(admin, false, myUserId);
6747                 return mService.setProfileOwner(admin, ownerName, myUserId);
6748             } catch (RemoteException re) {
6749                 throw re.rethrowFromSystemServer();
6750             }
6751         }
6752         return false;
6753     }
6754 
6755     /**
6756      * Clears the active profile owner. The caller must be the profile owner of this user, otherwise
6757      * a SecurityException will be thrown. This method is not available to managed profile owners.
6758      * <p>
6759      * While some policies previously set by the profile owner will be cleared by this method, it is
6760      * a best-effort process and some other policies will still remain in place after the profile
6761      * owner is cleared.
6762      *
6763      * @param admin The component to remove as the profile owner.
6764      * @throws SecurityException if {@code admin} is not an active profile owner, or the method is
6765      * being called from a managed profile.
6766      *
6767      * @deprecated This method is expected to be used for testing purposes only. The profile owner
6768      * will lose control of the user and its data after calling it. In order to protect any
6769      * sensitive data that remains on this user, it is advised that the profile owner deletes it
6770      * instead of calling this method. See {@link #wipeData(int)}.
6771      */
6772     @Deprecated
clearProfileOwner(@onNull ComponentName admin)6773     public void clearProfileOwner(@NonNull ComponentName admin) {
6774         throwIfParentInstance("clearProfileOwner");
6775         if (mService != null) {
6776             try {
6777                 mService.clearProfileOwner(admin);
6778             } catch (RemoteException re) {
6779                 throw re.rethrowFromSystemServer();
6780             }
6781         }
6782     }
6783 
6784     /**
6785      * @hide
6786      * Checks whether the user was already setup.
6787      */
hasUserSetupCompleted()6788     public boolean hasUserSetupCompleted() {
6789         if (mService != null) {
6790             try {
6791                 return mService.hasUserSetupCompleted();
6792             } catch (RemoteException re) {
6793                 throw re.rethrowFromSystemServer();
6794             }
6795         }
6796         return true;
6797     }
6798 
6799     /**
6800      * @hide
6801      * Sets the given component as the profile owner of the given user profile. The package must
6802      * already be installed. There must not already be a profile owner for this user.
6803      * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
6804      * this method.
6805      * Calling this after the setup phase of the specified user has completed is allowed only if:
6806      * - the caller is SYSTEM_UID.
6807      * - or the caller is the shell uid, and there are no accounts on the specified user.
6808      * @param admin the component name to be registered as profile owner.
6809      * @param ownerName the human readable name of the organisation associated with this DPM.
6810      * @param userHandle the userId to set the profile owner for.
6811      * @return whether the component was successfully registered as the profile owner.
6812      * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
6813      * preconditions mentioned are not met.
6814      */
setProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName, int userHandle)6815     public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
6816             int userHandle) throws IllegalArgumentException {
6817         if (mService != null) {
6818             try {
6819                 if (ownerName == null) {
6820                     ownerName = "";
6821                 }
6822                 return mService.setProfileOwner(admin, ownerName, userHandle);
6823             } catch (RemoteException re) {
6824                 throw re.rethrowFromSystemServer();
6825             }
6826         }
6827         return false;
6828     }
6829 
6830     /**
6831      * Sets the device owner information to be shown on the lock screen.
6832      * <p>
6833      * Device owner information set using this method overrides any owner information manually set
6834      * by the user and prevents the user from further changing it.
6835      * <p>
6836      * If the device owner information is {@code null} or empty then the device owner info is
6837      * cleared and the user owner info is shown on the lock screen if it is set.
6838      * <p>
6839      * If the device owner information contains only whitespaces then the message on the lock screen
6840      * will be blank and the user will not be allowed to change it.
6841      * <p>
6842      * If the device owner information needs to be localized, it is the responsibility of the
6843      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
6844      * and set a new version of this string accordingly.
6845      * <p>
6846      * May be called by the device owner or the profile owner of an organization-owned device.
6847      *
6848      * @param admin The name of the admin component to check.
6849      * @param info Device owner information which will be displayed instead of the user owner info.
6850      * @throws SecurityException if {@code admin} is not a device owner.
6851      */
setDeviceOwnerLockScreenInfo(@onNull ComponentName admin, CharSequence info)6852     public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
6853         throwIfParentInstance("setDeviceOwnerLockScreenInfo");
6854         if (mService != null) {
6855             try {
6856                 mService.setDeviceOwnerLockScreenInfo(admin, info);
6857             } catch (RemoteException re) {
6858                 throw re.rethrowFromSystemServer();
6859             }
6860         }
6861     }
6862 
6863     /**
6864      * @return The device owner information. If it is not set returns {@code null}.
6865      */
getDeviceOwnerLockScreenInfo()6866     public CharSequence getDeviceOwnerLockScreenInfo() {
6867         throwIfParentInstance("getDeviceOwnerLockScreenInfo");
6868         if (mService != null) {
6869             try {
6870                 return mService.getDeviceOwnerLockScreenInfo();
6871             } catch (RemoteException re) {
6872                 throw re.rethrowFromSystemServer();
6873             }
6874         }
6875         return null;
6876     }
6877 
6878     /**
6879      * Called by device or profile owners to suspend packages for this user. This function can be
6880      * called by a device owner, profile owner, or by a delegate given the
6881      * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}.
6882      * <p>
6883      * A suspended package will not be able to start activities. Its notifications will be hidden,
6884      * it will not show up in recents, will not be able to show toasts or dialogs or ring the
6885      * device.
6886      * <p>
6887      * The package must already be installed. If the package is uninstalled while suspended the
6888      * package will no longer be suspended. The admin can block this by using
6889      * {@link #setUninstallBlocked}.
6890      *
6891      * <p>Some apps cannot be suspended, such as device admins, the active launcher, the required
6892      * package installer, the required package uninstaller, the required package verifier, the
6893      * default dialer, and the permission controller.
6894      *
6895      * @param admin The name of the admin component to check, or {@code null} if the caller is a
6896      *            package access delegate.
6897      * @param packageNames The package names to suspend or unsuspend.
6898      * @param suspended If set to {@code true} than the packages will be suspended, if set to
6899      *            {@code false} the packages will be unsuspended.
6900      * @return an array of package names for which the suspended status is not set as requested in
6901      *         this method.
6902      * @throws SecurityException if {@code admin} is not a device or profile owner.
6903      * @see #setDelegatedScopes
6904      * @see #DELEGATION_PACKAGE_ACCESS
6905      */
setPackagesSuspended(@onNull ComponentName admin, @NonNull String[] packageNames, boolean suspended)6906     public @NonNull String[] setPackagesSuspended(@NonNull ComponentName admin,
6907             @NonNull String[] packageNames, boolean suspended) {
6908         throwIfParentInstance("setPackagesSuspended");
6909         if (mService != null) {
6910             try {
6911                 return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames,
6912                         suspended);
6913             } catch (RemoteException re) {
6914                 throw re.rethrowFromSystemServer();
6915             }
6916         }
6917         return packageNames;
6918     }
6919 
6920     /**
6921      * Determine if a package is suspended. This function can be called by a device owner, profile
6922      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
6923      * {@link #setDelegatedScopes}.
6924      *
6925      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6926      *            {@code null} if the caller is a package access delegate.
6927      * @param packageName The name of the package to retrieve the suspended status of.
6928      * @return {@code true} if the package is suspended or {@code false} if the package is not
6929      *         suspended, could not be found or an error occurred.
6930      * @throws SecurityException if {@code admin} is not a device or profile owner.
6931      * @throws NameNotFoundException if the package could not be found.
6932      * @see #setDelegatedScopes
6933      * @see #DELEGATION_PACKAGE_ACCESS
6934      */
isPackageSuspended(@onNull ComponentName admin, String packageName)6935     public boolean isPackageSuspended(@NonNull ComponentName admin, String packageName)
6936             throws NameNotFoundException {
6937         throwIfParentInstance("isPackageSuspended");
6938         if (mService != null) {
6939             try {
6940                 return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName);
6941             } catch (RemoteException e) {
6942                 throw e.rethrowFromSystemServer();
6943             } catch (IllegalArgumentException ex) {
6944                 throw new NameNotFoundException(packageName);
6945             }
6946         }
6947         return false;
6948     }
6949 
6950     /**
6951      * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
6952      * be used. Only the profile owner can call this.
6953      *
6954      * @see #isProfileOwnerApp
6955      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6956      * @throws SecurityException if {@code admin} is not a profile owner.
6957      */
setProfileEnabled(@onNull ComponentName admin)6958     public void setProfileEnabled(@NonNull ComponentName admin) {
6959         throwIfParentInstance("setProfileEnabled");
6960         if (mService != null) {
6961             try {
6962                 mService.setProfileEnabled(admin);
6963             } catch (RemoteException e) {
6964                 throw e.rethrowFromSystemServer();
6965             }
6966         }
6967     }
6968 
6969     /**
6970      * Sets the name of the profile. In the device owner case it sets the name of the user which it
6971      * is called from. Only a profile owner or device owner can call this. If this is never called
6972      * by the profile or device owner, the name will be set to default values.
6973      *
6974      * @see #isProfileOwnerApp
6975      * @see #isDeviceOwnerApp
6976      * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
6977      * @param profileName The name of the profile.
6978      * @throws SecurityException if {@code admin} is not a device or profile owner.
6979      */
setProfileName(@onNull ComponentName admin, String profileName)6980     public void setProfileName(@NonNull ComponentName admin, String profileName) {
6981         throwIfParentInstance("setProfileName");
6982         if (mService != null) {
6983             try {
6984                 mService.setProfileName(admin, profileName);
6985             } catch (RemoteException e) {
6986                 throw e.rethrowFromSystemServer();
6987             }
6988         }
6989     }
6990 
6991     /**
6992      * Used to determine if a particular package is registered as the profile owner for the
6993      * user. A profile owner is a special device admin that has additional privileges
6994      * within the profile.
6995      *
6996      * @param packageName The package name of the app to compare with the registered profile owner.
6997      * @return Whether or not the package is registered as the profile owner.
6998      */
isProfileOwnerApp(String packageName)6999     public boolean isProfileOwnerApp(String packageName) {
7000         throwIfParentInstance("isProfileOwnerApp");
7001         if (mService != null) {
7002             try {
7003                 ComponentName profileOwner = mService.getProfileOwner(myUserId());
7004                 return profileOwner != null
7005                         && profileOwner.getPackageName().equals(packageName);
7006             } catch (RemoteException re) {
7007                 throw re.rethrowFromSystemServer();
7008             }
7009         }
7010         return false;
7011     }
7012 
7013     /**
7014      * @hide
7015      * @return the packageName of the owner of the given user profile or {@code null} if no profile
7016      * owner has been set for that user.
7017      * @throws IllegalArgumentException if the userId is invalid.
7018      */
7019     @SystemApi
getProfileOwner()7020     public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
7021         throwIfParentInstance("getProfileOwner");
7022         return getProfileOwnerAsUser(mContext.getUserId());
7023     }
7024 
7025     /**
7026      * @see #getProfileOwner()
7027      * @hide
7028      */
7029     @RequiresPermission(value = android.Manifest.permission.INTERACT_ACROSS_USERS,
7030             conditional = true)
getProfileOwnerAsUser(@onNull UserHandle user)7031     public @Nullable ComponentName getProfileOwnerAsUser(@NonNull UserHandle user) {
7032         if (mService != null) {
7033             try {
7034                 return mService.getProfileOwnerAsUser(user.getIdentifier());
7035             } catch (RemoteException re) {
7036                 throw re.rethrowFromSystemServer();
7037             }
7038         }
7039         return null;
7040     }
7041 
7042     /**
7043      * @hide
7044      */
7045     @UnsupportedAppUsage
getProfileOwnerAsUser(final int userId)7046     public @Nullable ComponentName getProfileOwnerAsUser(final int userId) {
7047         if (mService != null) {
7048             try {
7049                 return mService.getProfileOwnerAsUser(userId);
7050             } catch (RemoteException re) {
7051                 throw re.rethrowFromSystemServer();
7052             }
7053         }
7054         return null;
7055     }
7056 
7057     /**
7058      * Returns the configured supervision app if it exists and is the device owner or policy owner.
7059      * @hide
7060      */
getProfileOwnerOrDeviceOwnerSupervisionComponent( @onNull UserHandle user)7061     public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent(
7062             @NonNull UserHandle user) {
7063         if (mService != null) {
7064             try {
7065                 return mService.getProfileOwnerOrDeviceOwnerSupervisionComponent(user);
7066             } catch (RemoteException re) {
7067                 throw re.rethrowFromSystemServer();
7068             }
7069         }
7070         return null;
7071     }
7072 
7073     /**
7074      * @hide
7075      * @return the human readable name of the organisation associated with this DPM or {@code null}
7076      *         if one is not set.
7077      * @throws IllegalArgumentException if the userId is invalid.
7078      */
getProfileOwnerName()7079     public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
7080         if (mService != null) {
7081             try {
7082                 return mService.getProfileOwnerName(mContext.getUserId());
7083             } catch (RemoteException re) {
7084                 throw re.rethrowFromSystemServer();
7085             }
7086         }
7087         return null;
7088     }
7089 
7090     /**
7091      * @hide
7092      * @param userId The user for whom to fetch the profile owner name, if any.
7093      * @return the human readable name of the organisation associated with this profile owner or
7094      *         null if one is not set.
7095      * @throws IllegalArgumentException if the userId is invalid.
7096      */
7097     @SystemApi
7098     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getProfileOwnerNameAsUser(int userId)7099     public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
7100         throwIfParentInstance("getProfileOwnerNameAsUser");
7101         if (mService != null) {
7102             try {
7103                 return mService.getProfileOwnerName(userId);
7104             } catch (RemoteException re) {
7105                 throw re.rethrowFromSystemServer();
7106             }
7107         }
7108         return null;
7109     }
7110 
7111     /**
7112      * Apps can use this method to find out if the device was provisioned as
7113      * organization-owend device with a managed profile.
7114      *
7115      * This, together with checking whether the device has a device owner (by calling
7116      * {@link #isDeviceOwnerApp}), could be used to learn whether the device is owned by an
7117      * organization or an individual:
7118      * If this method returns true OR {@link #isDeviceOwnerApp} returns true (for any package),
7119      * then the device is owned by an organization. Otherwise, it's owned by an individual.
7120      *
7121      * @return {@code true} if the device was provisioned as organization-owned device,
7122      * {@code false} otherwise.
7123      */
isOrganizationOwnedDeviceWithManagedProfile()7124     public boolean isOrganizationOwnedDeviceWithManagedProfile() {
7125         throwIfParentInstance("isOrganizationOwnedDeviceWithManagedProfile");
7126         if (mService != null) {
7127             try {
7128                 return mService.isOrganizationOwnedDeviceWithManagedProfile();
7129             } catch (RemoteException re) {
7130                 throw re.rethrowFromSystemServer();
7131             }
7132         }
7133         return false;
7134     }
7135 
7136     /**
7137      * Returns whether the specified package can read the device identifiers.
7138      *
7139      * @param packageName The package name of the app to check for device identifier access.
7140      * @param pid The process id of the package to be checked.
7141      * @param uid The uid of the package to be checked.
7142      * @return whether the package can read the device identifiers.
7143      *
7144      * @hide
7145      */
hasDeviceIdentifierAccess(@onNull String packageName, int pid, int uid)7146     public boolean hasDeviceIdentifierAccess(@NonNull String packageName, int pid, int uid) {
7147         throwIfParentInstance("hasDeviceIdentifierAccess");
7148         if (packageName == null) {
7149             return false;
7150         }
7151         if (mService != null) {
7152             try {
7153                 return mService.checkDeviceIdentifierAccess(packageName, pid, uid);
7154             } catch (RemoteException re) {
7155                 throw re.rethrowFromSystemServer();
7156             }
7157         }
7158         return false;
7159     }
7160 
7161     /**
7162      * Called by a profile owner or device owner to set a default activity that the system selects
7163      * to handle intents that match the given {@link IntentFilter}. This activity will remain the
7164      * default intent handler even if the set of potential event handlers for the intent filter
7165      * changes and if the intent preferences are reset.
7166      * <p>
7167      * Note that the caller should still declare the activity in the manifest, the API just sets
7168      * the activity to be the default one to handle the given intent filter.
7169      * <p>
7170      * The default disambiguation mechanism takes over if the activity is not installed (anymore).
7171      * When the activity is (re)installed, it is automatically reset as default intent handler for
7172      * the filter.
7173      * <p>
7174      * The calling device admin must be a profile owner or device owner. If it is not, a security
7175      * exception will be thrown.
7176      *
7177      * <p>NOTE: Performs disk I/O and shouldn't be called on the main thread.
7178      *
7179      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7180      * @param filter The IntentFilter for which a default handler is added.
7181      * @param activity The Activity that is added as default intent handler.
7182      * @throws SecurityException if {@code admin} is not a device or profile owner.
7183      */
addPersistentPreferredActivity(@onNull ComponentName admin, IntentFilter filter, @NonNull ComponentName activity)7184     public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
7185             @NonNull ComponentName activity) {
7186         throwIfParentInstance("addPersistentPreferredActivity");
7187         if (mService != null) {
7188             try {
7189                 mService.addPersistentPreferredActivity(admin, filter, activity);
7190             } catch (RemoteException e) {
7191                 throw e.rethrowFromSystemServer();
7192             }
7193         }
7194     }
7195 
7196     /**
7197      * Called by a profile owner or device owner to remove all persistent intent handler preferences
7198      * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
7199      * <p>
7200      * The calling device admin must be a profile owner. If it is not, a security exception will be
7201      * thrown.
7202      *
7203      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7204      * @param packageName The name of the package for which preferences are removed.
7205      * @throws SecurityException if {@code admin} is not a device or profile owner.
7206      */
clearPackagePersistentPreferredActivities(@onNull ComponentName admin, String packageName)7207     public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
7208             String packageName) {
7209         throwIfParentInstance("clearPackagePersistentPreferredActivities");
7210         if (mService != null) {
7211             try {
7212                 mService.clearPackagePersistentPreferredActivities(admin, packageName);
7213             } catch (RemoteException e) {
7214                 throw e.rethrowFromSystemServer();
7215             }
7216         }
7217     }
7218 
7219     /**
7220      * Must be called by a device owner or a profile owner of an organization-owned managed profile
7221      * to set the default SMS application.
7222      * <p>
7223      * This method can be called on the {@link DevicePolicyManager} instance, returned by
7224      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
7225      * of an organization-owned managed profile and the package must be a pre-installed system
7226      * package. If called on the parent instance, then the default SMS application is set on the
7227      * personal profile.
7228      *
7229      * @param admin       Which {@link DeviceAdminReceiver} this request is associated with.
7230      * @param packageName The name of the package to set as the default SMS application.
7231      * @throws SecurityException        if {@code admin} is not a device or profile owner or if
7232      *                                  called on the parent profile and the {@code admin} is not a
7233      *                                  profile owner of an organization-owned managed profile.
7234      * @throws IllegalArgumentException if called on the parent profile and the package
7235      *                                  provided is not a pre-installed system package.
7236      */
setDefaultSmsApplication(@onNull ComponentName admin, @NonNull String packageName)7237     public void setDefaultSmsApplication(@NonNull ComponentName admin,
7238             @NonNull String packageName) {
7239         if (mService != null) {
7240             try {
7241                 mService.setDefaultSmsApplication(admin, packageName, mParentInstance);
7242             } catch (RemoteException e) {
7243                 throw e.rethrowFromSystemServer();
7244             }
7245         }
7246     }
7247 
7248     /**
7249      * Called by a profile owner or device owner to grant permission to a package to manage
7250      * application restrictions for the calling user via {@link #setApplicationRestrictions} and
7251      * {@link #getApplicationRestrictions}.
7252      * <p>
7253      * This permission is persistent until it is later cleared by calling this method with a
7254      * {@code null} value or uninstalling the managing package.
7255      * <p>
7256      * The supplied application restriction managing package must be installed when calling this
7257      * API, otherwise an {@link NameNotFoundException} will be thrown.
7258      *
7259      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7260      * @param packageName The package name which will be given access to application restrictions
7261      *            APIs. If {@code null} is given the current package will be cleared.
7262      * @throws SecurityException if {@code admin} is not a device or profile owner.
7263      * @throws NameNotFoundException if {@code packageName} is not found
7264      *
7265      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
7266      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
7267      */
7268     @Deprecated
setApplicationRestrictionsManagingPackage(@onNull ComponentName admin, @Nullable String packageName)7269     public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
7270             @Nullable String packageName) throws NameNotFoundException {
7271         throwIfParentInstance("setApplicationRestrictionsManagingPackage");
7272         if (mService != null) {
7273             try {
7274                 if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
7275                     throw new NameNotFoundException(packageName);
7276                 }
7277             } catch (RemoteException e) {
7278                 throw e.rethrowFromSystemServer();
7279             }
7280         }
7281     }
7282 
7283     /**
7284      * Called by a profile owner or device owner to retrieve the application restrictions managing
7285      * package for the current user, or {@code null} if none is set. If there are multiple
7286      * delegates this function will return one of them.
7287      *
7288      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7289      * @return The package name allowed to manage application restrictions on the current user, or
7290      *         {@code null} if none is set.
7291      * @throws SecurityException if {@code admin} is not a device or profile owner.
7292      *
7293      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
7294      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
7295      */
7296     @Deprecated
7297     @Nullable
getApplicationRestrictionsManagingPackage( @onNull ComponentName admin)7298     public String getApplicationRestrictionsManagingPackage(
7299             @NonNull ComponentName admin) {
7300         throwIfParentInstance("getApplicationRestrictionsManagingPackage");
7301         if (mService != null) {
7302             try {
7303                 return mService.getApplicationRestrictionsManagingPackage(admin);
7304             } catch (RemoteException e) {
7305                 throw e.rethrowFromSystemServer();
7306             }
7307         }
7308         return null;
7309     }
7310 
7311     /**
7312      * Called by any application to find out whether it has been granted permission via
7313      * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
7314      * for the calling user.
7315      *
7316      * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
7317      * that method.
7318      *
7319      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes}
7320      * instead.
7321      */
7322     @Deprecated
isCallerApplicationRestrictionsManagingPackage()7323     public boolean isCallerApplicationRestrictionsManagingPackage() {
7324         throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
7325         if (mService != null) {
7326             try {
7327                 return mService.isCallerApplicationRestrictionsManagingPackage(
7328                         mContext.getPackageName());
7329             } catch (RemoteException e) {
7330                 throw e.rethrowFromSystemServer();
7331             }
7332         }
7333         return false;
7334     }
7335 
7336     /**
7337      * Sets the application restrictions for a given target application running in the calling user.
7338      * <p>
7339      * The caller must be a profile or device owner on that user, or the package allowed to manage
7340      * application restrictions via {@link #setDelegatedScopes} with the
7341      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
7342      * <p>
7343      * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
7344      * <ul>
7345      * <li>{@code boolean}
7346      * <li>{@code int}
7347      * <li>{@code String} or {@code String[]}
7348      * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
7349      * </ul>
7350      * <p>
7351      * If the restrictions are not available yet, but may be applied in the near future, the caller
7352      * can notify the target application of that by adding
7353      * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
7354      * <p>
7355      * The application restrictions are only made visible to the target application via
7356      * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
7357      * owner, and the application restrictions managing package via
7358      * {@link #getApplicationRestrictions}.
7359      *
7360      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
7361      *
7362      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7363      *            {@code null} if called by the application restrictions managing package.
7364      * @param packageName The name of the package to update restricted settings for.
7365      * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
7366      *            set of active restrictions.
7367      * @throws SecurityException if {@code admin} is not a device or profile owner.
7368      * @see #setDelegatedScopes
7369      * @see #DELEGATION_APP_RESTRICTIONS
7370      * @see UserManager#KEY_RESTRICTIONS_PENDING
7371      */
7372     @WorkerThread
setApplicationRestrictions(@ullable ComponentName admin, String packageName, Bundle settings)7373     public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
7374             Bundle settings) {
7375         throwIfParentInstance("setApplicationRestrictions");
7376         if (mService != null) {
7377             try {
7378                 mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName,
7379                         settings);
7380             } catch (RemoteException e) {
7381                 throw e.rethrowFromSystemServer();
7382             }
7383         }
7384     }
7385 
7386     /**
7387      * Sets a list of configuration features to enable for a trust agent component. This is meant to
7388      * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
7389      * agents but those enabled by this function call. If flag
7390      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
7391      * <p>
7392      * For any specific trust agent, whether it is disabled or not depends on the aggregated state
7393      * of each admin's {@link #KEYGUARD_DISABLE_TRUST_AGENTS} setting and its trust agent
7394      * configuration as set by this function call. In particular: if any admin sets
7395      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and does not additionally set any
7396      * trust agent configuration, the trust agent is disabled completely. Otherwise, the trust agent
7397      * will receive the list of configurations from all admins who set
7398      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and aggregate the configurations to determine its
7399      * behavior. The exact meaning of aggregation is trust-agent-specific.
7400      * <p>
7401      * The calling device admin must have requested
7402      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
7403      * if not, a security exception will be thrown.
7404      * <p>
7405      * This method can be called on the {@link DevicePolicyManager} instance returned by
7406      * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
7407      * the parent profile.
7408      * <p>
7409      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, calling
7410      * this method has no effect - no trust agent configuration will be set.
7411      *
7412      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7413      * @param target Component name of the agent to be configured.
7414      * @param configuration Trust-agent-specific feature configuration bundle. Please consult
7415      *        documentation of the specific trust agent to determine the interpretation of this
7416      *        bundle.
7417      * @throws SecurityException if {@code admin} is not an active administrator or does not use
7418      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
7419      */
7420     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setTrustAgentConfiguration(@onNull ComponentName admin, @NonNull ComponentName target, PersistableBundle configuration)7421     public void setTrustAgentConfiguration(@NonNull ComponentName admin,
7422             @NonNull ComponentName target, PersistableBundle configuration) {
7423         if (mService != null) {
7424             try {
7425                 mService.setTrustAgentConfiguration(admin, target, configuration, mParentInstance);
7426             } catch (RemoteException e) {
7427                 throw e.rethrowFromSystemServer();
7428             }
7429         }
7430     }
7431 
7432     /**
7433      * Gets configuration for the given trust agent based on aggregating all calls to
7434      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
7435      * all device admins.
7436      * <p>
7437      * This method can be called on the {@link DevicePolicyManager} instance returned by
7438      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
7439      * on the parent profile.
7440      * <p>
7441      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, null is
7442      * always returned.
7443      *
7444      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
7445      * this function returns a list of configurations for all admins that declare
7446      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
7447      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
7448      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
7449      * for this {@param agent} or calls it with a null configuration, null is returned.
7450      * @param agent Which component to get enabled features for.
7451      * @return configuration for the given trust agent.
7452      */
7453     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent)7454     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
7455             @Nullable ComponentName admin, @NonNull ComponentName agent) {
7456         return getTrustAgentConfiguration(admin, agent, myUserId());
7457     }
7458 
7459     /** @hide per-user version */
7460     @UnsupportedAppUsage
7461     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent, int userHandle)7462     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
7463             @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
7464         if (mService != null) {
7465             try {
7466                 return mService.getTrustAgentConfiguration(admin, agent, userHandle,
7467                         mParentInstance);
7468             } catch (RemoteException e) {
7469                 throw e.rethrowFromSystemServer();
7470             }
7471         }
7472         return new ArrayList<PersistableBundle>(); // empty list
7473     }
7474 
7475     /**
7476      * Called by a profile owner of a managed profile to set whether caller-Id information from the
7477      * managed profile will be shown in the parent profile, for incoming calls.
7478      * <p>
7479      * The calling device admin must be a profile owner. If it is not, a security exception will be
7480      * thrown.
7481      *
7482      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7483      * @param disabled If true caller-Id information in the managed profile is not displayed.
7484      * @throws SecurityException if {@code admin} is not a profile owner.
7485      */
setCrossProfileCallerIdDisabled(@onNull ComponentName admin, boolean disabled)7486     public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
7487         throwIfParentInstance("setCrossProfileCallerIdDisabled");
7488         if (mService != null) {
7489             try {
7490                 mService.setCrossProfileCallerIdDisabled(admin, disabled);
7491             } catch (RemoteException e) {
7492                 throw e.rethrowFromSystemServer();
7493             }
7494         }
7495     }
7496 
7497     /**
7498      * Called by a profile owner of a managed profile to determine whether or not caller-Id
7499      * information has been disabled.
7500      * <p>
7501      * The calling device admin must be a profile owner. If it is not, a security exception will be
7502      * thrown.
7503      *
7504      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7505      * @throws SecurityException if {@code admin} is not a profile owner.
7506      */
getCrossProfileCallerIdDisabled(@onNull ComponentName admin)7507     public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
7508         throwIfParentInstance("getCrossProfileCallerIdDisabled");
7509         if (mService != null) {
7510             try {
7511                 return mService.getCrossProfileCallerIdDisabled(admin);
7512             } catch (RemoteException e) {
7513                 throw e.rethrowFromSystemServer();
7514             }
7515         }
7516         return false;
7517     }
7518 
7519     /**
7520      * Determine whether or not caller-Id information has been disabled.
7521      *
7522      * @param userHandle The user for whom to check the caller-id permission
7523      * @hide
7524      */
getCrossProfileCallerIdDisabled(UserHandle userHandle)7525     public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
7526         if (mService != null) {
7527             try {
7528                 return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
7529             } catch (RemoteException e) {
7530                 throw e.rethrowFromSystemServer();
7531             }
7532         }
7533         return false;
7534     }
7535 
7536     /**
7537      * Called by a profile owner of a managed profile to set whether contacts search from the
7538      * managed profile will be shown in the parent profile, for incoming calls.
7539      * <p>
7540      * The calling device admin must be a profile owner. If it is not, a security exception will be
7541      * thrown.
7542      *
7543      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7544      * @param disabled If true contacts search in the managed profile is not displayed.
7545      * @throws SecurityException if {@code admin} is not a profile owner.
7546      */
setCrossProfileContactsSearchDisabled(@onNull ComponentName admin, boolean disabled)7547     public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
7548             boolean disabled) {
7549         throwIfParentInstance("setCrossProfileContactsSearchDisabled");
7550         if (mService != null) {
7551             try {
7552                 mService.setCrossProfileContactsSearchDisabled(admin, disabled);
7553             } catch (RemoteException e) {
7554                 throw e.rethrowFromSystemServer();
7555             }
7556         }
7557     }
7558 
7559     /**
7560      * Called by a profile owner of a managed profile to determine whether or not contacts search
7561      * has been disabled.
7562      * <p>
7563      * The calling device admin must be a profile owner. If it is not, a security exception will be
7564      * thrown.
7565      *
7566      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7567      * @throws SecurityException if {@code admin} is not a profile owner.
7568      */
getCrossProfileContactsSearchDisabled(@onNull ComponentName admin)7569     public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
7570         throwIfParentInstance("getCrossProfileContactsSearchDisabled");
7571         if (mService != null) {
7572             try {
7573                 return mService.getCrossProfileContactsSearchDisabled(admin);
7574             } catch (RemoteException e) {
7575                 throw e.rethrowFromSystemServer();
7576             }
7577         }
7578         return false;
7579     }
7580 
7581 
7582     /**
7583      * Determine whether or not contacts search has been disabled.
7584      *
7585      * @param userHandle The user for whom to check the contacts search permission
7586      * @hide
7587      */
getCrossProfileContactsSearchDisabled(@onNull UserHandle userHandle)7588     public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
7589         if (mService != null) {
7590             try {
7591                 return mService
7592                         .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
7593             } catch (RemoteException e) {
7594                 throw e.rethrowFromSystemServer();
7595             }
7596         }
7597         return false;
7598     }
7599 
7600     /**
7601      * Start Quick Contact on the managed profile for the user, if the policy allows.
7602      *
7603      * @hide
7604      */
startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long directoryId, Intent originalIntent)7605     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7606             boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
7607         if (mService != null) {
7608             try {
7609                 mService.startManagedQuickContact(actualLookupKey, actualContactId,
7610                         isContactIdIgnored, directoryId, originalIntent);
7611             } catch (RemoteException e) {
7612                 throw e.rethrowFromSystemServer();
7613             }
7614         }
7615     }
7616 
7617     /**
7618      * Start Quick Contact on the managed profile for the user, if the policy allows.
7619      * @hide
7620      */
startManagedQuickContact(String actualLookupKey, long actualContactId, Intent originalIntent)7621     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7622             Intent originalIntent) {
7623         startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
7624                 originalIntent);
7625     }
7626 
7627     /**
7628      * Called by a profile owner of a managed profile to set whether bluetooth devices can access
7629      * enterprise contacts.
7630      * <p>
7631      * The calling device admin must be a profile owner. If it is not, a security exception will be
7632      * thrown.
7633      * <p>
7634      * This API works on managed profile only.
7635      *
7636      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7637      * @param disabled If true, bluetooth devices cannot access enterprise contacts.
7638      * @throws SecurityException if {@code admin} is not a profile owner.
7639      */
setBluetoothContactSharingDisabled(@onNull ComponentName admin, boolean disabled)7640     public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
7641         throwIfParentInstance("setBluetoothContactSharingDisabled");
7642         if (mService != null) {
7643             try {
7644                 mService.setBluetoothContactSharingDisabled(admin, disabled);
7645             } catch (RemoteException e) {
7646                 throw e.rethrowFromSystemServer();
7647             }
7648         }
7649     }
7650 
7651     /**
7652      * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
7653      * cannot access enterprise contacts.
7654      * <p>
7655      * The calling device admin must be a profile owner. If it is not, a security exception will be
7656      * thrown.
7657      * <p>
7658      * This API works on managed profile only.
7659      *
7660      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7661      * @throws SecurityException if {@code admin} is not a profile owner.
7662      */
getBluetoothContactSharingDisabled(@onNull ComponentName admin)7663     public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
7664         throwIfParentInstance("getBluetoothContactSharingDisabled");
7665         if (mService != null) {
7666             try {
7667                 return mService.getBluetoothContactSharingDisabled(admin);
7668             } catch (RemoteException e) {
7669                 throw e.rethrowFromSystemServer();
7670             }
7671         }
7672         return true;
7673     }
7674 
7675     /**
7676      * Determine whether or not Bluetooth devices cannot access contacts.
7677      * <p>
7678      * This API works on managed profile UserHandle only.
7679      *
7680      * @param userHandle The user for whom to check the caller-id permission
7681      * @hide
7682      */
7683     @SystemApi
7684     @RequiresPermission(permission.INTERACT_ACROSS_USERS)
getBluetoothContactSharingDisabled(@onNull UserHandle userHandle)7685     public boolean getBluetoothContactSharingDisabled(@NonNull UserHandle userHandle) {
7686         if (mService != null) {
7687             try {
7688                 return mService.getBluetoothContactSharingDisabledForUser(userHandle
7689                         .getIdentifier());
7690             } catch (RemoteException e) {
7691                 throw e.rethrowFromSystemServer();
7692             }
7693         }
7694         return true;
7695     }
7696 
7697     /**
7698      * Called by the profile owner of a managed profile so that some intents sent in the managed
7699      * profile can also be resolved in the parent, or vice versa. Only activity intents are
7700      * supported.
7701      *
7702      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7703      * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
7704      *            other profile
7705      * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
7706      *            {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
7707      * @throws SecurityException if {@code admin} is not a device or profile owner.
7708      */
addCrossProfileIntentFilter(@onNull ComponentName admin, IntentFilter filter, int flags)7709     public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
7710         throwIfParentInstance("addCrossProfileIntentFilter");
7711         if (mService != null) {
7712             try {
7713                 mService.addCrossProfileIntentFilter(admin, filter, flags);
7714             } catch (RemoteException e) {
7715                 throw e.rethrowFromSystemServer();
7716             }
7717         }
7718     }
7719 
7720     /**
7721      * Called by a profile owner of a managed profile to remove the cross-profile intent filters
7722      * that go from the managed profile to the parent, or from the parent to the managed profile.
7723      * Only removes those that have been set by the profile owner.
7724      * <p>
7725      * <em>Note</em>: A list of default cross profile intent filters are set up by the system when
7726      * the profile is created, some of them ensure the proper functioning of the profile, while
7727      * others enable sharing of data from the parent to the managed profile for user convenience.
7728      * These default intent filters are not cleared when this API is called. If the default cross
7729      * profile data sharing is not desired, they can be disabled with
7730      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE}.
7731      *
7732      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7733      * @throws SecurityException if {@code admin} is not a profile owner.
7734      */
clearCrossProfileIntentFilters(@onNull ComponentName admin)7735     public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
7736         throwIfParentInstance("clearCrossProfileIntentFilters");
7737         if (mService != null) {
7738             try {
7739                 mService.clearCrossProfileIntentFilters(admin);
7740             } catch (RemoteException e) {
7741                 throw e.rethrowFromSystemServer();
7742             }
7743         }
7744     }
7745 
7746     /**
7747      * Called by a profile or device owner to set the permitted
7748      * {@link android.accessibilityservice.AccessibilityService}. When set by
7749      * a device owner or profile owner the restriction applies to all profiles of the user the
7750      * device owner or profile owner is an admin for. By default, the user can use any accessibility
7751      * service. When zero or more packages have been added, accessibility services that are not in
7752      * the list and not part of the system can not be enabled by the user.
7753      * <p>
7754      * Calling with a null value for the list disables the restriction so that all services can be
7755      * used, calling with an empty list only allows the built-in system services. Any non-system
7756      * accessibility service that's currently enabled must be included in the list.
7757      * <p>
7758      * System accessibility services are always available to the user and this method can't
7759      * disable them.
7760      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7761      * @param packageNames List of accessibility service package names.
7762      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
7763      *         contain every enabled non-system accessibility service.
7764      * @throws SecurityException if {@code admin} is not a device or profile owner.
7765      */
setPermittedAccessibilityServices(@onNull ComponentName admin, List<String> packageNames)7766     public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
7767             List<String> packageNames) {
7768         throwIfParentInstance("setPermittedAccessibilityServices");
7769         if (mService != null) {
7770             try {
7771                 return mService.setPermittedAccessibilityServices(admin, packageNames);
7772             } catch (RemoteException e) {
7773                 throw e.rethrowFromSystemServer();
7774             }
7775         }
7776         return false;
7777     }
7778 
7779     /**
7780      * Returns the list of permitted accessibility services set by this device or profile owner.
7781      * <p>
7782      * An empty list means no accessibility services except system services are allowed. Null means
7783      * all accessibility services are allowed.
7784      *
7785      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7786      * @return List of accessiblity service package names.
7787      * @throws SecurityException if {@code admin} is not a device or profile owner.
7788      */
getPermittedAccessibilityServices(@onNull ComponentName admin)7789     public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
7790         throwIfParentInstance("getPermittedAccessibilityServices");
7791         if (mService != null) {
7792             try {
7793                 return mService.getPermittedAccessibilityServices(admin);
7794             } catch (RemoteException e) {
7795                 throw e.rethrowFromSystemServer();
7796             }
7797         }
7798         return null;
7799     }
7800 
7801     /**
7802      * Called by the system to check if a specific accessibility service is disabled by admin.
7803      *
7804      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7805      * @param packageName Accessibility service package name that needs to be checked.
7806      * @param userHandle user id the admin is running as.
7807      * @return true if the accessibility service is permitted, otherwise false.
7808      *
7809      * @hide
7810      */
isAccessibilityServicePermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)7811     public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
7812             @NonNull String packageName, int userHandle) {
7813         if (mService != null) {
7814             try {
7815                 return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
7816                         userHandle);
7817             } catch (RemoteException e) {
7818                 throw e.rethrowFromSystemServer();
7819             }
7820         }
7821         return false;
7822     }
7823 
7824     /**
7825      * Returns the list of accessibility services permitted by the device or profiles
7826      * owners of this user.
7827      *
7828      * <p>Null means all accessibility services are allowed, if a non-null list is returned
7829      * it will contain the intersection of the permitted lists for any device or profile
7830      * owners that apply to this user. It will also include any system accessibility services.
7831      *
7832      * @param userId which user to check for.
7833      * @return List of accessiblity service package names.
7834      * @hide
7835      */
7836      @SystemApi
7837      @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getPermittedAccessibilityServices(int userId)7838      public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
7839         throwIfParentInstance("getPermittedAccessibilityServices");
7840         if (mService != null) {
7841             try {
7842                 return mService.getPermittedAccessibilityServicesForUser(userId);
7843             } catch (RemoteException e) {
7844                 throw e.rethrowFromSystemServer();
7845             }
7846         }
7847         return null;
7848      }
7849 
7850     /**
7851      * Called by a profile or device owner to set the permitted input methods services for this
7852      * user. By default, the user can use any input method.
7853      * <p>
7854      * When zero or more packages have been added, input method that are not in the list and not
7855      * part of the system can not be enabled by the user. This method will fail if it is called for
7856      * a admin that is not for the foreground user or a profile of the foreground user. Any
7857      * non-system input method service that's currently enabled must be included in the list.
7858      * <p>
7859      * Calling with a null value for the list disables the restriction so that all input methods can
7860      * be used, calling with an empty list disables all but the system's own input methods.
7861      * <p>
7862      * System input methods are always available to the user - this method can't modify this.
7863      *
7864      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7865      * @param packageNames List of input method package names.
7866      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
7867      *        contain every enabled non-system input method service.
7868      * @throws SecurityException if {@code admin} is not a device or profile owner.
7869      */
setPermittedInputMethods( @onNull ComponentName admin, List<String> packageNames)7870     public boolean setPermittedInputMethods(
7871             @NonNull ComponentName admin, List<String> packageNames) {
7872         throwIfParentInstance("setPermittedInputMethods");
7873         if (mService != null) {
7874             try {
7875                 return mService.setPermittedInputMethods(admin, packageNames);
7876             } catch (RemoteException e) {
7877                 throw e.rethrowFromSystemServer();
7878             }
7879         }
7880         return false;
7881     }
7882 
7883 
7884     /**
7885      * Returns the list of permitted input methods set by this device or profile owner.
7886      * <p>
7887      * An empty list means no input methods except system input methods are allowed. Null means all
7888      * input methods are allowed.
7889      *
7890      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7891      * @return List of input method package names.
7892      * @throws SecurityException if {@code admin} is not a device or profile owner.
7893      */
getPermittedInputMethods(@onNull ComponentName admin)7894     public @Nullable List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
7895         throwIfParentInstance("getPermittedInputMethods");
7896         if (mService != null) {
7897             try {
7898                 return mService.getPermittedInputMethods(admin);
7899             } catch (RemoteException e) {
7900                 throw e.rethrowFromSystemServer();
7901             }
7902         }
7903         return null;
7904     }
7905 
7906     /**
7907      * Called by the system to check if a specific input method is disabled by admin.
7908      *
7909      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7910      * @param packageName Input method package name that needs to be checked.
7911      * @param userHandle user id the admin is running as.
7912      * @return true if the input method is permitted, otherwise false.
7913      *
7914      * @hide
7915      */
isInputMethodPermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)7916     public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
7917             @NonNull String packageName, int userHandle) {
7918         if (mService != null) {
7919             try {
7920                 return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle);
7921             } catch (RemoteException e) {
7922                 throw e.rethrowFromSystemServer();
7923             }
7924         }
7925         return false;
7926     }
7927 
7928     /**
7929      * Returns the list of input methods permitted by the device or profiles owners.
7930      *
7931      * <p>On {@link android.os.Build.VERSION_CODES#Q} and later devices, this method returns the
7932      * result for the calling user.</p>
7933      *
7934      * <p>On Android P and prior devices, this method returns the result for the current user.</p>
7935      *
7936      * <p>Null means all input methods are allowed, if a non-null list is returned
7937      * it will contain the intersection of the permitted lists for any device or profile
7938      * owners that apply to this user. It will also include any system input methods.
7939      *
7940      * @return List of input method package names.
7941      * @hide
7942      */
7943     @SystemApi
7944     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getPermittedInputMethodsForCurrentUser()7945     public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
7946         throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
7947         if (mService != null) {
7948             try {
7949                 return mService.getPermittedInputMethodsForCurrentUser();
7950             } catch (RemoteException e) {
7951                 throw e.rethrowFromSystemServer();
7952             }
7953         }
7954         return null;
7955     }
7956 
7957     /**
7958      * Called by a profile owner of a managed profile to set the packages that are allowed to use
7959      * a {@link android.service.notification.NotificationListenerService} in the primary user to
7960      * see notifications from the managed profile. By default all packages are permitted by this
7961      * policy. When zero or more packages have been added, notification listeners installed on the
7962      * primary user that are not in the list and are not part of the system won't receive events
7963      * for managed profile notifications.
7964      * <p>
7965      * Calling with a {@code null} value for the list disables the restriction so that all
7966      * notification listener services be used. Calling with an empty list disables all but the
7967      * system's own notification listeners. System notification listener services are always
7968      * available to the user.
7969      * <p>
7970      * If a device or profile owner want to stop notification listeners in their user from seeing
7971      * that user's notifications they should prevent that service from running instead (e.g. via
7972      * {@link #setApplicationHidden(ComponentName, String, boolean)})
7973      *
7974      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7975      * @param packageList List of package names to whitelist
7976      * @return true if setting the restriction succeeded. It will fail if called outside a managed
7977      * profile
7978      * @throws SecurityException if {@code admin} is not a profile owner.
7979      *
7980      * @see android.service.notification.NotificationListenerService
7981      */
setPermittedCrossProfileNotificationListeners( @onNull ComponentName admin, @Nullable List<String> packageList)7982     public boolean setPermittedCrossProfileNotificationListeners(
7983             @NonNull ComponentName admin, @Nullable List<String> packageList) {
7984         throwIfParentInstance("setPermittedCrossProfileNotificationListeners");
7985         if (mService != null) {
7986             try {
7987                 return mService.setPermittedCrossProfileNotificationListeners(admin, packageList);
7988             } catch (RemoteException e) {
7989                 throw e.rethrowFromSystemServer();
7990             }
7991         }
7992         return false;
7993     }
7994 
7995     /**
7996      * Returns the list of packages installed on the primary user that allowed to use a
7997      * {@link android.service.notification.NotificationListenerService} to receive
7998      * notifications from this managed profile, as set by the profile owner.
7999      * <p>
8000      * An empty list means no notification listener services except system ones are allowed.
8001      * A {@code null} return value indicates that all notification listeners are allowed.
8002      */
getPermittedCrossProfileNotificationListeners( @onNull ComponentName admin)8003     public @Nullable List<String> getPermittedCrossProfileNotificationListeners(
8004             @NonNull ComponentName admin) {
8005         throwIfParentInstance("getPermittedCrossProfileNotificationListeners");
8006         if (mService != null) {
8007             try {
8008                 return mService.getPermittedCrossProfileNotificationListeners(admin);
8009             } catch (RemoteException e) {
8010                 throw e.rethrowFromSystemServer();
8011             }
8012         }
8013         return null;
8014     }
8015 
8016     /**
8017      * Returns true if {@code NotificationListenerServices} from the given package are allowed to
8018      * receive events for notifications from the given user id. Can only be called by the system uid
8019      *
8020      * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List)
8021      *
8022      * @hide
8023      */
isNotificationListenerServicePermitted( @onNull String packageName, @UserIdInt int userId)8024     public boolean isNotificationListenerServicePermitted(
8025             @NonNull String packageName, @UserIdInt int userId) {
8026         if (mService != null) {
8027             try {
8028                 return mService.isNotificationListenerServicePermitted(packageName, userId);
8029             } catch (RemoteException e) {
8030                 throw e.rethrowFromSystemServer();
8031             }
8032         }
8033         return true;
8034     }
8035 
8036     /**
8037      * Get the list of apps to keep around as APKs even if no user has currently installed it. This
8038      * function can be called by a device owner or by a delegate given the
8039      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
8040      * <p>
8041      * Please note that packages returned in this method are not automatically pre-cached.
8042      *
8043      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8044      *            {@code null} if the caller is a keep uninstalled packages delegate.
8045      * @return List of package names to keep cached.
8046      * @see #setDelegatedScopes
8047      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
8048      */
getKeepUninstalledPackages(@ullable ComponentName admin)8049     public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) {
8050         throwIfParentInstance("getKeepUninstalledPackages");
8051         if (mService != null) {
8052             try {
8053                 return mService.getKeepUninstalledPackages(admin, mContext.getPackageName());
8054             } catch (RemoteException e) {
8055                 throw e.rethrowFromSystemServer();
8056             }
8057         }
8058         return null;
8059     }
8060 
8061     /**
8062      * Set a list of apps to keep around as APKs even if no user has currently installed it. This
8063      * function can be called by a device owner or by a delegate given the
8064      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
8065      *
8066      * <p>Please note that setting this policy does not imply that specified apps will be
8067      * automatically pre-cached.</p>
8068      *
8069      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8070      *            {@code null} if the caller is a keep uninstalled packages delegate.
8071      * @param packageNames List of package names to keep cached.
8072      * @throws SecurityException if {@code admin} is not a device owner.
8073      * @see #setDelegatedScopes
8074      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
8075      */
setKeepUninstalledPackages(@ullable ComponentName admin, @NonNull List<String> packageNames)8076     public void setKeepUninstalledPackages(@Nullable ComponentName admin,
8077             @NonNull List<String> packageNames) {
8078         throwIfParentInstance("setKeepUninstalledPackages");
8079         if (mService != null) {
8080             try {
8081                 mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames);
8082             } catch (RemoteException e) {
8083                 throw e.rethrowFromSystemServer();
8084             }
8085         }
8086     }
8087 
8088     /**
8089       * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
8090       */
8091     public static final int SKIP_SETUP_WIZARD = 0x0001;
8092 
8093     /**
8094      * Flag used by {@link #createAndManageUser} to specify that the user should be created
8095      * ephemeral. Ephemeral users will be removed after switching to another user or rebooting the
8096      * device.
8097      */
8098     public static final int MAKE_USER_EPHEMERAL = 0x0002;
8099 
8100     /**
8101      * Flag used by {@link #createAndManageUser} to specify that the user should be created as a
8102      * demo user.
8103      * @hide
8104      */
8105     public static final int MAKE_USER_DEMO = 0x0004;
8106 
8107     /**
8108      * Flag used by {@link #createAndManageUser} to specify that the newly created user should skip
8109      * the disabling of system apps during provisioning.
8110      */
8111     public static final int LEAVE_ALL_SYSTEM_APPS_ENABLED = 0x0010;
8112 
8113     /**
8114      * @hide
8115      */
8116     @IntDef(flag = true, prefix = { "SKIP_", "MAKE_USER_", "START_", "LEAVE_" }, value = {
8117             SKIP_SETUP_WIZARD,
8118             MAKE_USER_EPHEMERAL,
8119             MAKE_USER_DEMO,
8120             LEAVE_ALL_SYSTEM_APPS_ENABLED
8121     })
8122     @Retention(RetentionPolicy.SOURCE)
8123     public @interface CreateAndManageUserFlags {}
8124 
8125     /**
8126      * Called by a device owner to create a user with the specified name and a given component of
8127      * the calling package as profile owner. The UserHandle returned by this method should not be
8128      * persisted as user handles are recycled as users are removed and created. If you need to
8129      * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
8130      * user will not be started in the background.
8131      * <p>
8132      * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
8133      * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
8134      * be registered as an active admin on the new user. The profile owner package will be installed
8135      * on the new user.
8136      * <p>
8137      * If the adminExtras are not null, they will be stored on the device until the user is started
8138      * for the first time. Then the extras will be passed to the admin when onEnable is called.
8139      * <p>From {@link android.os.Build.VERSION_CODES#P} onwards, if targeting
8140      * {@link android.os.Build.VERSION_CODES#P}, throws {@link UserOperationException} instead of
8141      * returning {@code null} on failure.
8142      *
8143      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8144      * @param name The user's name.
8145      * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
8146      *            same package as admin, otherwise no user is created and an
8147      *            IllegalArgumentException is thrown.
8148      * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
8149      *            user.
8150      * @param flags {@link #SKIP_SETUP_WIZARD}, {@link #MAKE_USER_EPHEMERAL} and
8151      *        {@link #LEAVE_ALL_SYSTEM_APPS_ENABLED} are supported.
8152      * @see UserHandle
8153      * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
8154      *         user could not be created.
8155      * @throws SecurityException if {@code admin} is not a device owner.
8156      * @throws UserOperationException if the user could not be created and the calling app is
8157      * targeting {@link android.os.Build.VERSION_CODES#P} and running on
8158      * {@link android.os.Build.VERSION_CODES#P}.
8159      */
createAndManageUser(@onNull ComponentName admin, @NonNull String name, @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras, @CreateAndManageUserFlags int flags)8160     public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
8161             @NonNull String name,
8162             @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
8163             @CreateAndManageUserFlags int flags) {
8164         throwIfParentInstance("createAndManageUser");
8165         try {
8166             return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
8167         } catch (ServiceSpecificException e) {
8168             throw new UserOperationException(e.getMessage(), e.errorCode);
8169         } catch (RemoteException re) {
8170             throw re.rethrowFromSystemServer();
8171         }
8172     }
8173 
8174     /**
8175      * Called by a device owner to remove a user/profile and all associated data. The primary user
8176      * can not be removed.
8177      *
8178      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8179      * @param userHandle the user to remove.
8180      * @return {@code true} if the user was removed, {@code false} otherwise.
8181      * @throws SecurityException if {@code admin} is not a device owner.
8182      */
removeUser(@onNull ComponentName admin, @NonNull UserHandle userHandle)8183     public boolean removeUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) {
8184         throwIfParentInstance("removeUser");
8185         try {
8186             return mService.removeUser(admin, userHandle);
8187         } catch (RemoteException re) {
8188             throw re.rethrowFromSystemServer();
8189         }
8190     }
8191 
8192     /**
8193      * Called by a device owner to switch the specified secondary user to the foreground.
8194      *
8195      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8196      * @param userHandle the user to switch to; null will switch to primary.
8197      * @return {@code true} if the switch was successful, {@code false} otherwise.
8198      * @throws SecurityException if {@code admin} is not a device owner.
8199      * @see Intent#ACTION_USER_FOREGROUND
8200      * @see #getSecondaryUsers(ComponentName)
8201      */
switchUser(@onNull ComponentName admin, @Nullable UserHandle userHandle)8202     public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
8203         throwIfParentInstance("switchUser");
8204         try {
8205             return mService.switchUser(admin, userHandle);
8206         } catch (RemoteException re) {
8207             throw re.rethrowFromSystemServer();
8208         }
8209     }
8210 
8211     /**
8212      * Called by a device owner to start the specified secondary user in background.
8213      *
8214      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8215      * @param userHandle the user to be started in background.
8216      * @return one of the following result codes:
8217      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
8218      * {@link UserManager#USER_OPERATION_SUCCESS},
8219      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
8220      * {@link UserManager#USER_OPERATION_ERROR_MAX_RUNNING_USERS},
8221      * @throws SecurityException if {@code admin} is not a device owner.
8222      * @see #getSecondaryUsers(ComponentName)
8223      */
startUserInBackground( @onNull ComponentName admin, @NonNull UserHandle userHandle)8224     public @UserOperationResult int startUserInBackground(
8225             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
8226         throwIfParentInstance("startUserInBackground");
8227         try {
8228             return mService.startUserInBackground(admin, userHandle);
8229         } catch (RemoteException re) {
8230             throw re.rethrowFromSystemServer();
8231         }
8232     }
8233 
8234     /**
8235      * Called by a device owner to stop the specified secondary user.
8236      *
8237      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8238      * @param userHandle the user to be stopped.
8239      * @return one of the following result codes:
8240      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
8241      * {@link UserManager#USER_OPERATION_SUCCESS},
8242      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
8243      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
8244      * @throws SecurityException if {@code admin} is not a device owner.
8245      * @see #getSecondaryUsers(ComponentName)
8246      */
stopUser( @onNull ComponentName admin, @NonNull UserHandle userHandle)8247     public @UserOperationResult int stopUser(
8248             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
8249         throwIfParentInstance("stopUser");
8250         try {
8251             return mService.stopUser(admin, userHandle);
8252         } catch (RemoteException re) {
8253             throw re.rethrowFromSystemServer();
8254         }
8255     }
8256 
8257     /**
8258      * Called by a profile owner of secondary user that is affiliated with the device to stop the
8259      * calling user and switch back to primary.
8260      *
8261      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8262      * @return one of the following result codes:
8263      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
8264      * {@link UserManager#USER_OPERATION_SUCCESS},
8265      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
8266      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
8267      * @throws SecurityException if {@code admin} is not a profile owner affiliated with the device.
8268      * @see #getSecondaryUsers(ComponentName)
8269      */
logoutUser(@onNull ComponentName admin)8270     public @UserOperationResult int logoutUser(@NonNull ComponentName admin) {
8271         throwIfParentInstance("logoutUser");
8272         try {
8273             return mService.logoutUser(admin);
8274         } catch (RemoteException re) {
8275             throw re.rethrowFromSystemServer();
8276         }
8277     }
8278 
8279     /**
8280      * Called by a device owner to list all secondary users on the device. Managed profiles are not
8281      * considered as secondary users.
8282      * <p> Used for various user management APIs, including {@link #switchUser}, {@link #removeUser}
8283      * and {@link #stopUser}.
8284      *
8285      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8286      * @return list of other {@link UserHandle}s on the device.
8287      * @throws SecurityException if {@code admin} is not a device owner.
8288      * @see #removeUser(ComponentName, UserHandle)
8289      * @see #switchUser(ComponentName, UserHandle)
8290      * @see #startUserInBackground(ComponentName, UserHandle)
8291      * @see #stopUser(ComponentName, UserHandle)
8292      */
getSecondaryUsers(@onNull ComponentName admin)8293     public List<UserHandle> getSecondaryUsers(@NonNull ComponentName admin) {
8294         throwIfParentInstance("getSecondaryUsers");
8295         try {
8296             return mService.getSecondaryUsers(admin);
8297         } catch (RemoteException re) {
8298             throw re.rethrowFromSystemServer();
8299         }
8300     }
8301 
8302     /**
8303      * Checks if the profile owner is running in an ephemeral user.
8304      *
8305      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8306      * @return whether the profile owner is running in an ephemeral user.
8307      */
isEphemeralUser(@onNull ComponentName admin)8308     public boolean isEphemeralUser(@NonNull ComponentName admin) {
8309         throwIfParentInstance("isEphemeralUser");
8310         try {
8311             return mService.isEphemeralUser(admin);
8312         } catch (RemoteException re) {
8313             throw re.rethrowFromSystemServer();
8314         }
8315     }
8316 
8317     /**
8318      * Retrieves the application restrictions for a given target application running in the calling
8319      * user.
8320      * <p>
8321      * The caller must be a profile or device owner on that user, or the package allowed to manage
8322      * application restrictions via {@link #setDelegatedScopes} with the
8323      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
8324      *
8325      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
8326      *
8327      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8328      *            {@code null} if called by the application restrictions managing package.
8329      * @param packageName The name of the package to fetch restricted settings of.
8330      * @return {@link Bundle} of settings corresponding to what was set last time
8331      *         {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
8332      *         {@link Bundle} if no restrictions have been set.
8333      * @throws SecurityException if {@code admin} is not a device or profile owner.
8334      * @see #setDelegatedScopes
8335      * @see #DELEGATION_APP_RESTRICTIONS
8336      */
8337     @WorkerThread
getApplicationRestrictions( @ullable ComponentName admin, String packageName)8338     public @NonNull Bundle getApplicationRestrictions(
8339             @Nullable ComponentName admin, String packageName) {
8340         throwIfParentInstance("getApplicationRestrictions");
8341         if (mService != null) {
8342             try {
8343                 return mService.getApplicationRestrictions(admin, mContext.getPackageName(),
8344                         packageName);
8345             } catch (RemoteException e) {
8346                 throw e.rethrowFromSystemServer();
8347             }
8348         }
8349         return null;
8350     }
8351 
8352     /**
8353      * Called by a profile or device owner to set a user restriction specified by the key.
8354      * <p>
8355      * The calling device admin must be a profile or device owner; if it is not, a security
8356      * exception will be thrown.
8357      * <p>
8358      * The profile owner of an organization-owned managed profile may invoke this method on
8359      * the {@link DevicePolicyManager} instance it obtained from
8360      * {@link #getParentProfileInstance(ComponentName)}, for enforcing device-wide restrictions.
8361      * <p>
8362      * See the constants in {@link android.os.UserManager} for the list of restrictions that can
8363      * be enforced device-wide.
8364      *
8365      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8366      * @param key   The key of the restriction.
8367      * @throws SecurityException if {@code admin} is not a device or profile owner.
8368      */
addUserRestriction(@onNull ComponentName admin, @UserManager.UserRestrictionKey String key)8369     public void addUserRestriction(@NonNull ComponentName admin,
8370             @UserManager.UserRestrictionKey String key) {
8371         if (mService != null) {
8372             try {
8373                 mService.setUserRestriction(admin, key, true, mParentInstance);
8374             } catch (RemoteException e) {
8375                 throw e.rethrowFromSystemServer();
8376             }
8377         }
8378     }
8379 
8380     /**
8381      * Called by a profile or device owner to clear a user restriction specified by the key.
8382      * <p>
8383      * The calling device admin must be a profile or device owner; if it is not, a security
8384      * exception will be thrown.
8385      * <p>
8386      * The profile owner of an organization-owned managed profile may invoke this method on
8387      * the {@link DevicePolicyManager} instance it obtained from
8388      * {@link #getParentProfileInstance(ComponentName)}, for clearing device-wide restrictions.
8389      * <p>
8390      * See the constants in {@link android.os.UserManager} for the list of restrictions.
8391      *
8392      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8393      * @param key   The key of the restriction.
8394      * @throws SecurityException if {@code admin} is not a device or profile owner.
8395      */
clearUserRestriction(@onNull ComponentName admin, @UserManager.UserRestrictionKey String key)8396     public void clearUserRestriction(@NonNull ComponentName admin,
8397             @UserManager.UserRestrictionKey String key) {
8398         if (mService != null) {
8399             try {
8400                 mService.setUserRestriction(admin, key, false, mParentInstance);
8401             } catch (RemoteException e) {
8402                 throw e.rethrowFromSystemServer();
8403             }
8404         }
8405     }
8406 
8407     /**
8408      * Called by a profile or device owner to get user restrictions set with
8409      * {@link #addUserRestriction(ComponentName, String)}.
8410      * <p>
8411      * The target user may have more restrictions set by the system or other device owner / profile
8412      * owner. To get all the user restrictions currently set, use
8413      * {@link UserManager#getUserRestrictions()}.
8414      * <p>
8415      * The profile owner of an organization-owned managed profile may invoke this method on
8416      * the {@link DevicePolicyManager} instance it obtained from
8417      * {@link #getParentProfileInstance(ComponentName)}, for retrieving device-wide restrictions
8418      * it previously set with {@link #addUserRestriction(ComponentName, String)}.
8419      *
8420      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8421      * @throws SecurityException if {@code admin} is not a device or profile owner.
8422      */
getUserRestrictions(@onNull ComponentName admin)8423     public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
8424         Bundle ret = null;
8425         if (mService != null) {
8426             try {
8427                 ret = mService.getUserRestrictions(admin, mParentInstance);
8428             } catch (RemoteException e) {
8429                 throw e.rethrowFromSystemServer();
8430             }
8431         }
8432         return ret == null ? new Bundle() : ret;
8433     }
8434 
8435     /**
8436      * Called by any app to display a support dialog when a feature was disabled by an admin.
8437      * This returns an intent that can be used with {@link Context#startActivity(Intent)} to
8438      * display the dialog. It will tell the user that the feature indicated by {@code restriction}
8439      * was disabled by an admin, and include a link for more information. The default content of
8440      * the dialog can be changed by the restricting admin via
8441      * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not
8442      * set (i.e. the feature is available), then the return value will be {@code null}.
8443      * @param restriction Indicates for which feature the dialog should be displayed. Can be a
8444      *            user restriction from {@link UserManager}, e.g.
8445      *            {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants
8446      *            {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
8447      * @return Intent An intent to be used to start the dialog-activity if the restriction is
8448      *            set by an admin, or null if the restriction does not exist or no admin set it.
8449      */
createAdminSupportIntent(@onNull String restriction)8450     public Intent createAdminSupportIntent(@NonNull String restriction) {
8451         throwIfParentInstance("createAdminSupportIntent");
8452         if (mService != null) {
8453             try {
8454                 return mService.createAdminSupportIntent(restriction);
8455             } catch (RemoteException e) {
8456                 throw e.rethrowFromSystemServer();
8457             }
8458         }
8459         return null;
8460     }
8461 
8462     /**
8463      * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and
8464      * actual package file remain. This function can be called by a device owner, profile owner, or
8465      * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
8466      * {@link #setDelegatedScopes}.
8467      * <p>
8468      * This method can be called on the {@link DevicePolicyManager} instance, returned by
8469      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
8470      * of an organization-owned managed profile and the package must be a system package. If called
8471      * on the parent instance, then the package is hidden or unhidden in the personal profile.
8472      *
8473      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8474      *            {@code null} if the caller is a package access delegate.
8475      * @param packageName The name of the package to hide or unhide.
8476      * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
8477      *            unhidden.
8478      * @return boolean Whether the hidden setting of the package was successfully updated.
8479      * @throws SecurityException if {@code admin} is not a device or profile owner or if called on
8480      *            the parent profile and the {@code admin} is not a profile owner of an
8481      *            organization-owned managed profile.
8482      * @throws IllegalArgumentException if called on the parent profile and the package provided
8483      *            is not a system package.
8484      * @see #setDelegatedScopes
8485      * @see #DELEGATION_PACKAGE_ACCESS
8486      */
setApplicationHidden(@onNull ComponentName admin, String packageName, boolean hidden)8487     public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
8488             boolean hidden) {
8489         if (mService != null) {
8490             try {
8491                 return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName,
8492                         hidden, mParentInstance);
8493             } catch (RemoteException e) {
8494                 throw e.rethrowFromSystemServer();
8495             }
8496         }
8497         return false;
8498     }
8499 
8500     /**
8501      * Determine if a package is hidden. This function can be called by a device owner, profile
8502      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
8503      * {@link #setDelegatedScopes}.
8504      * <p>
8505      * This method can be called on the {@link DevicePolicyManager} instance, returned by
8506      * {@link #getParentProfileInstance(ComponentName)}, where the caller must be the profile owner
8507      * of an organization-owned managed profile and the package must be a system package. If called
8508      * on the parent instance, this will determine whether the package is hidden or unhidden in the
8509      * personal profile.
8510      *
8511      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8512      *            {@code null} if the caller is a package access delegate.
8513      * @param packageName The name of the package to retrieve the hidden status of.
8514      * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
8515      * @throws SecurityException if {@code admin} is not a device or profile owner or if called on
8516      *            the parent profile and the {@code admin} is not a profile owner of an
8517      *            organization-owned managed profile.
8518      * @throws IllegalArgumentException if called on the parent profile and the package provided
8519      *            is not a system package.
8520      * @see #setDelegatedScopes
8521      * @see #DELEGATION_PACKAGE_ACCESS
8522      */
isApplicationHidden(@onNull ComponentName admin, String packageName)8523     public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
8524         if (mService != null) {
8525             try {
8526                 return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName,
8527                         mParentInstance);
8528             } catch (RemoteException e) {
8529                 throw e.rethrowFromSystemServer();
8530             }
8531         }
8532         return false;
8533     }
8534 
8535     /**
8536      * Re-enable a system app that was disabled by default when the user was initialized. This
8537      * function can be called by a device owner, profile owner, or by a delegate given the
8538      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
8539      *
8540      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8541      *            {@code null} if the caller is an enable system app delegate.
8542      * @param packageName The package to be re-enabled in the calling profile.
8543      * @throws SecurityException if {@code admin} is not a device or profile owner.
8544      * @see #setDelegatedScopes
8545      * @see #DELEGATION_PACKAGE_ACCESS
8546      */
enableSystemApp(@onNull ComponentName admin, String packageName)8547     public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
8548         throwIfParentInstance("enableSystemApp");
8549         if (mService != null) {
8550             try {
8551                 mService.enableSystemApp(admin, mContext.getPackageName(), packageName);
8552             } catch (RemoteException e) {
8553                 throw e.rethrowFromSystemServer();
8554             }
8555         }
8556     }
8557 
8558     /**
8559      * Re-enable system apps by intent that were disabled by default when the user was initialized.
8560      * This function can be called by a device owner, profile owner, or by a delegate given the
8561      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
8562      *
8563      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8564      *            {@code null} if the caller is an enable system app delegate.
8565      * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
8566      *            intent will be re-enabled in the calling profile.
8567      * @return int The number of activities that matched the intent and were installed.
8568      * @throws SecurityException if {@code admin} is not a device or profile owner.
8569      * @see #setDelegatedScopes
8570      * @see #DELEGATION_PACKAGE_ACCESS
8571      */
enableSystemApp(@onNull ComponentName admin, Intent intent)8572     public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
8573         throwIfParentInstance("enableSystemApp");
8574         if (mService != null) {
8575             try {
8576                 return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent);
8577             } catch (RemoteException e) {
8578                 throw e.rethrowFromSystemServer();
8579             }
8580         }
8581         return 0;
8582     }
8583 
8584     /**
8585      * Install an existing package that has been installed in another user, or has been kept after
8586      * removal via {@link #setKeepUninstalledPackages}.
8587      * This function can be called by a device owner, profile owner or a delegate given
8588      * the {@link #DELEGATION_INSTALL_EXISTING_PACKAGE} scope via {@link #setDelegatedScopes}.
8589      * When called in a secondary user or managed profile, the user/profile must be affiliated with
8590      * the device. See {@link #isAffiliatedUser}.
8591      *
8592      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8593      * @param packageName The package to be installed in the calling profile.
8594      * @return {@code true} if the app is installed; {@code false} otherwise.
8595      * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
8596      * an affiliated user or profile.
8597      * @see #setKeepUninstalledPackages
8598      * @see #setDelegatedScopes
8599      * @see #isAffiliatedUser
8600      * @see #DELEGATION_PACKAGE_ACCESS
8601      */
installExistingPackage(@onNull ComponentName admin, String packageName)8602     public boolean installExistingPackage(@NonNull ComponentName admin, String packageName) {
8603         throwIfParentInstance("installExistingPackage");
8604         if (mService != null) {
8605             try {
8606                 return mService.installExistingPackage(admin, mContext.getPackageName(),
8607                         packageName);
8608             } catch (RemoteException e) {
8609                 throw e.rethrowFromSystemServer();
8610             }
8611         }
8612         return false;
8613     }
8614 
8615     /**
8616      * Called by a device owner or profile owner to disable account management for a specific type
8617      * of account.
8618      * <p>
8619      * The calling device admin must be a device owner or profile owner. If it is not, a security
8620      * exception will be thrown.
8621      * <p>
8622      * When account management is disabled for an account type, adding or removing an account of
8623      * that type will not be possible.
8624      * <p>
8625      * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
8626      * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
8627      * management for a specific type is disabled.
8628      * <p>
8629      * This method may be called on the {@code DevicePolicyManager} instance returned from
8630      * {@link #getParentProfileInstance(ComponentName)} by the profile owner on an
8631      * organization-owned device, to restrict accounts that may not be managed on the primary
8632      * profile.
8633      *
8634      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8635      * @param accountType For which account management is disabled or enabled.
8636      * @param disabled The boolean indicating that account management will be disabled (true) or
8637      *            enabled (false).
8638      * @throws SecurityException if {@code admin} is not a device or profile owner.
8639      */
setAccountManagementDisabled(@onNull ComponentName admin, String accountType, boolean disabled)8640     public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
8641             boolean disabled) {
8642         if (mService != null) {
8643             try {
8644                 mService.setAccountManagementDisabled(admin, accountType, disabled,
8645                         mParentInstance);
8646             } catch (RemoteException e) {
8647                 throw e.rethrowFromSystemServer();
8648             }
8649         }
8650     }
8651 
8652     /**
8653      * Gets the array of accounts for which account management is disabled by the profile owner
8654      * or device owner.
8655      *
8656      * <p> Account management can be disabled/enabled by calling
8657      * {@link #setAccountManagementDisabled}.
8658      * <p>
8659      * This method may be called on the {@code DevicePolicyManager} instance returned from
8660      * {@link #getParentProfileInstance(ComponentName)}. Note that only a profile owner on
8661      * an organization-owned device can affect account types on the parent profile instance.
8662      *
8663      * @return a list of account types for which account management has been disabled.
8664      *
8665      * @see #setAccountManagementDisabled
8666      */
getAccountTypesWithManagementDisabled()8667     public @Nullable String[] getAccountTypesWithManagementDisabled() {
8668         return getAccountTypesWithManagementDisabledAsUser(myUserId(), mParentInstance);
8669     }
8670 
8671     /**
8672      * @see #getAccountTypesWithManagementDisabled()
8673      * Note that calling this method on the parent profile instance will return the same
8674      * value as calling it on the main {@code DevicePolicyManager} instance.
8675      * @hide
8676      */
getAccountTypesWithManagementDisabledAsUser(int userId)8677     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
8678         return getAccountTypesWithManagementDisabledAsUser(userId, false);
8679     }
8680 
8681     /**
8682      * @see #getAccountTypesWithManagementDisabled()
8683      * @hide
8684      */
getAccountTypesWithManagementDisabledAsUser( int userId, boolean parentInstance)8685     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(
8686             int userId, boolean parentInstance) {
8687         if (mService != null) {
8688             try {
8689                 return mService.getAccountTypesWithManagementDisabledAsUser(userId, parentInstance);
8690             } catch (RemoteException e) {
8691                 throw e.rethrowFromSystemServer();
8692             }
8693         }
8694 
8695         return null;
8696     }
8697 
8698     /**
8699      * Called by device owner or profile owner to set whether a secondary lockscreen needs to be
8700      * shown.
8701      *
8702      * <p>The secondary lockscreen will by displayed after the primary keyguard security screen
8703      * requirements are met. To provide the lockscreen content the DO/PO will need to provide a
8704      * service handling the {@link #ACTION_BIND_SECONDARY_LOCKSCREEN_SERVICE} intent action,
8705      * extending the {@link DevicePolicyKeyguardService} class.
8706      *
8707      * <p>Relevant interactions on the secondary lockscreen should be communicated back to the
8708      * keyguard via {@link IKeyguardCallback}, such as when the screen is ready to be dismissed.
8709      *
8710      * <p>This API, and associated APIs, can only be called by the default supervision app when it
8711      * is set as the device owner or profile owner.
8712      *
8713      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8714      * @param enabled Whether or not the lockscreen needs to be shown.
8715      * @throws SecurityException if {@code admin} is not a device or profile owner.
8716      * @see #isSecondaryLockscreenEnabled
8717      * @hide
8718      **/
8719     @SystemApi
setSecondaryLockscreenEnabled(@onNull ComponentName admin, boolean enabled)8720     public void setSecondaryLockscreenEnabled(@NonNull ComponentName admin, boolean enabled) {
8721         throwIfParentInstance("setSecondaryLockscreenEnabled");
8722         if (mService != null) {
8723             try {
8724                 mService.setSecondaryLockscreenEnabled(admin, enabled);
8725             } catch (RemoteException e) {
8726                 throw e.rethrowFromSystemServer();
8727             }
8728         }
8729     }
8730 
8731     /**
8732      * Returns whether the secondary lock screen needs to be shown.
8733      * @see #setSecondaryLockscreenEnabled
8734      * @hide
8735      */
8736     @SystemApi
isSecondaryLockscreenEnabled(@onNull UserHandle userHandle)8737     public boolean isSecondaryLockscreenEnabled(@NonNull UserHandle userHandle) {
8738         throwIfParentInstance("isSecondaryLockscreenEnabled");
8739         if (mService != null) {
8740             try {
8741                 return mService.isSecondaryLockscreenEnabled(userHandle);
8742             } catch (RemoteException e) {
8743                 throw e.rethrowFromSystemServer();
8744             }
8745         }
8746         return false;
8747     }
8748 
8749     /**
8750      * Sets which packages may enter lock task mode.
8751      * <p>
8752      * Any packages that share uid with an allowed package will also be allowed to activate lock
8753      * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
8754      * package list results in locked tasks belonging to those packages to be finished.
8755      * <p>
8756      * This function can only be called by the device owner, a profile owner of an affiliated user
8757      * or profile, or the profile owner when no device owner is set. See {@link #isAffiliatedUser}.
8758      * Any package set via this method will be cleared if the user becomes unaffiliated.
8759      *
8760      * @param packages The list of packages allowed to enter lock task mode
8761      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8762      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
8763      * affiliated user or profile, or the profile owner when no device owner is set.
8764      * @see #isAffiliatedUser
8765      * @see Activity#startLockTask()
8766      * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
8767      * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
8768      * @see UserManager#DISALLOW_CREATE_WINDOWS
8769      */
setLockTaskPackages(@onNull ComponentName admin, @NonNull String[] packages)8770     public void setLockTaskPackages(@NonNull ComponentName admin, @NonNull String[] packages)
8771             throws SecurityException {
8772         throwIfParentInstance("setLockTaskPackages");
8773         if (mService != null) {
8774             try {
8775                 mService.setLockTaskPackages(admin, packages);
8776             } catch (RemoteException e) {
8777                 throw e.rethrowFromSystemServer();
8778             }
8779         }
8780     }
8781 
8782     /**
8783      * Returns the list of packages allowed to start the lock task mode.
8784      *
8785      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
8786      * affiliated user or profile, or the profile owner when no device owner is set.
8787      * @see #isAffiliatedUser
8788      * @see #setLockTaskPackages
8789      */
getLockTaskPackages(@onNull ComponentName admin)8790     public @NonNull String[] getLockTaskPackages(@NonNull ComponentName admin) {
8791         throwIfParentInstance("getLockTaskPackages");
8792         if (mService != null) {
8793             try {
8794                 return mService.getLockTaskPackages(admin);
8795             } catch (RemoteException e) {
8796                 throw e.rethrowFromSystemServer();
8797             }
8798         }
8799         return new String[0];
8800     }
8801 
8802     /**
8803      * This function lets the caller know whether the given component is allowed to start the
8804      * lock task mode.
8805      * @param pkg The package to check
8806      */
isLockTaskPermitted(String pkg)8807     public boolean isLockTaskPermitted(String pkg) {
8808         throwIfParentInstance("isLockTaskPermitted");
8809         if (mService != null) {
8810             try {
8811                 return mService.isLockTaskPermitted(pkg);
8812             } catch (RemoteException e) {
8813                 throw e.rethrowFromSystemServer();
8814             }
8815         }
8816         return false;
8817     }
8818 
8819     /**
8820      * Sets which system features are enabled when the device runs in lock task mode. This method
8821      * doesn't affect the features when lock task mode is inactive. Any system features not included
8822      * in {@code flags} are implicitly disabled when calling this method. By default, only
8823      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS} is enabled; all the other features are disabled. To
8824      * disable the global actions dialog, call this method omitting
8825      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}.
8826      *
8827      * <p>This method can only be called by the device owner, a profile owner of an affiliated
8828      * user or profile, or the profile owner when no device owner is set. See
8829      * {@link #isAffiliatedUser}.
8830      * Any features set using this method are cleared if the user becomes unaffiliated.
8831      *
8832      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8833      * @param flags The system features enabled during lock task mode.
8834      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
8835      * affiliated user or profile, or the profile owner when no device owner is set.
8836      * @see #isAffiliatedUser
8837      **/
setLockTaskFeatures(@onNull ComponentName admin, @LockTaskFeature int flags)8838     public void setLockTaskFeatures(@NonNull ComponentName admin, @LockTaskFeature int flags) {
8839         throwIfParentInstance("setLockTaskFeatures");
8840         if (mService != null) {
8841             try {
8842                 mService.setLockTaskFeatures(admin, flags);
8843             } catch (RemoteException e) {
8844                 throw e.rethrowFromSystemServer();
8845             }
8846         }
8847     }
8848 
8849     /**
8850      * Gets which system features are enabled for LockTask mode.
8851      *
8852      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8853      * @return bitfield of flags. See {@link #setLockTaskFeatures(ComponentName, int)} for a list.
8854      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
8855      * affiliated user or profile, or the profile owner when no device owner is set.
8856      * @see #isAffiliatedUser
8857      * @see #setLockTaskFeatures
8858      */
getLockTaskFeatures(@onNull ComponentName admin)8859     public @LockTaskFeature int getLockTaskFeatures(@NonNull ComponentName admin) {
8860         throwIfParentInstance("getLockTaskFeatures");
8861         if (mService != null) {
8862             try {
8863                 return mService.getLockTaskFeatures(admin);
8864             } catch (RemoteException e) {
8865                 throw e.rethrowFromSystemServer();
8866             }
8867         }
8868         return 0;
8869     }
8870 
8871     /**
8872      * This method is mostly deprecated.
8873      * Most of the settings that still have an effect have dedicated setter methods or user
8874      * restrictions. See individual settings for details.
8875      * <p>
8876      * Called by device owner to update {@link android.provider.Settings.Global} settings.
8877      * Validation that the value of the setting is in the correct form for the setting type should
8878      * be performed by the caller.
8879      * <p>
8880      * The settings that can be updated with this method are:
8881      * <ul>
8882      * <li>{@link android.provider.Settings.Global#ADB_ENABLED} : use
8883      * {@link UserManager#DISALLOW_DEBUGGING_FEATURES} instead to restrict users from enabling
8884      * debugging features and this setting to turn adb on.</li>
8885      * <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
8886      * <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only
8887      * available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
8888      * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
8889      * <li>{@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This
8890      * setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
8891      * </ul>
8892      * <p>
8893      * The following settings used to be supported, but can be controlled in other ways:
8894      * <ul>
8895      * <li>{@link android.provider.Settings.Global#AUTO_TIME} : Use {@link #setAutoTimeEnabled} and
8896      * {@link UserManager#DISALLOW_CONFIG_DATE_TIME} instead.</li>
8897      * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE} : Use
8898      * {@link #setAutoTimeZoneEnabled} and {@link UserManager#DISALLOW_CONFIG_DATE_TIME}
8899      * instead.</li>
8900      * <li>{@link android.provider.Settings.Global#DATA_ROAMING} : Use
8901      * {@link UserManager#DISALLOW_DATA_ROAMING} instead.</li>
8902      * </ul>
8903      * <p>
8904      * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
8905      * <ul>
8906      * <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use
8907      * {@link android.bluetooth.BluetoothAdapter#enable()} and
8908      * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
8909      * <li>{@link android.provider.Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
8910      * <li>{@link android.provider.Settings.Global#MODE_RINGER}. Use
8911      * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
8912      * <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li>
8913      * <li>{@link android.provider.Settings.Global#WIFI_ON}. Use
8914      * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
8915      * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}. No longer has effect.</li>
8916      * </ul>
8917      *
8918      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8919      * @param setting The name of the setting to update.
8920      * @param value The value to update the setting to.
8921      * @throws SecurityException if {@code admin} is not a device owner.
8922      */
setGlobalSetting(@onNull ComponentName admin, String setting, String value)8923     public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
8924         throwIfParentInstance("setGlobalSetting");
8925         if (mService != null) {
8926             try {
8927                 mService.setGlobalSetting(admin, setting, value);
8928             } catch (RemoteException e) {
8929                 throw e.rethrowFromSystemServer();
8930             }
8931         }
8932     }
8933 
8934     /** @hide */
8935     @StringDef({
8936             Settings.System.SCREEN_BRIGHTNESS_MODE,
8937             Settings.System.SCREEN_BRIGHTNESS,
8938             Settings.System.SCREEN_BRIGHTNESS_FLOAT,
8939             Settings.System.SCREEN_OFF_TIMEOUT
8940     })
8941     @Retention(RetentionPolicy.SOURCE)
8942     public @interface SystemSettingsWhitelist {}
8943 
8944     /**
8945      * Called by a device or profile owner to update {@link android.provider.Settings.System}
8946      * settings. Validation that the value of the setting is in the correct form for the setting
8947      * type should be performed by the caller.
8948      * <p>
8949      * The settings that can be updated by a device owner or profile owner of secondary user with
8950      * this method are:
8951      * <ul>
8952      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS}</li>
8953      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS_MODE}</li>
8954      * <li>{@link android.provider.Settings.System#SCREEN_OFF_TIMEOUT}</li>
8955      * </ul>
8956      * <p>
8957      *
8958      * @see android.provider.Settings.System#SCREEN_OFF_TIMEOUT
8959      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8960      * @param setting The name of the setting to update.
8961      * @param value The value to update the setting to.
8962      * @throws SecurityException if {@code admin} is not a device or profile owner.
8963      */
setSystemSetting(@onNull ComponentName admin, @NonNull @SystemSettingsWhitelist String setting, String value)8964     public void setSystemSetting(@NonNull ComponentName admin,
8965             @NonNull @SystemSettingsWhitelist String setting, String value) {
8966         throwIfParentInstance("setSystemSetting");
8967         if (mService != null) {
8968             try {
8969                 mService.setSystemSetting(admin, setting, value);
8970             } catch (RemoteException e) {
8971                 throw e.rethrowFromSystemServer();
8972             }
8973         }
8974     }
8975 
8976     /**
8977      * Called by a device owner or a profile owner of an organization-owned managed profile to
8978      * control whether the user can change networks configured by the admin.
8979      * <p>
8980      * WiFi network configuration lockdown is controlled by a global settings
8981      * {@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN} and calling
8982      * this API effectively modifies the global settings. Previously device owners can also
8983      * control this directly via {@link #setGlobalSetting} but they are recommended to switch
8984      * to this API.
8985      *
8986      * @param admin             admin Which {@link DeviceAdminReceiver} this request is associated
8987      *                          with.
8988      * @param lockdown Whether the admin configured networks should be unmodifiable by the
8989      *                          user.
8990      * @throws SecurityException if caller is not a device owner or a profile owner of an
8991      *                           organization-owned managed profile.
8992      */
setConfiguredNetworksLockdownState(@onNull ComponentName admin, boolean lockdown)8993     public void setConfiguredNetworksLockdownState(@NonNull ComponentName admin, boolean lockdown) {
8994         throwIfParentInstance("setConfiguredNetworksLockdownState");
8995         if (mService != null) {
8996             try {
8997                 mService.setConfiguredNetworksLockdownState(admin, lockdown);
8998             } catch (RemoteException e) {
8999                 throw e.rethrowFromSystemServer();
9000             }
9001         }
9002     }
9003 
9004     /**
9005      * Called by a device owner or a profile owner of an organization-owned managed profile to
9006      * determine whether the user is prevented from modifying networks configured by the admin.
9007      *
9008      * @param admin             admin Which {@link DeviceAdminReceiver} this request is associated
9009      *                          with.
9010      * @throws SecurityException if caller is not a device owner or a profile owner of an
9011      *                           organization-owned managed profile.
9012      */
hasLockdownAdminConfiguredNetworks(@onNull ComponentName admin)9013     public boolean hasLockdownAdminConfiguredNetworks(@NonNull ComponentName admin) {
9014         throwIfParentInstance("hasLockdownAdminConfiguredNetworks");
9015         if (mService != null) {
9016             try {
9017                 return mService.hasLockdownAdminConfiguredNetworks(admin);
9018             } catch (RemoteException e) {
9019                 throw e.rethrowFromSystemServer();
9020             }
9021         }
9022         return false;
9023     }
9024 
9025     /**
9026      * Called by a device owner or a profile owner of an organization-owned managed
9027      * profile to set the system wall clock time. This only takes effect if called when
9028      * {@link android.provider.Settings.Global#AUTO_TIME} is 0, otherwise {@code false}
9029      * will be returned.
9030      *
9031      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
9032      * @param millis time in milliseconds since the Epoch
9033      * @return {@code true} if set time succeeded, {@code false} otherwise.
9034      * @throws SecurityException if {@code admin} is not a device owner or a profile owner
9035      * of an organization-owned managed profile.
9036      */
setTime(@onNull ComponentName admin, long millis)9037     public boolean setTime(@NonNull ComponentName admin, long millis) {
9038         throwIfParentInstance("setTime");
9039         if (mService != null) {
9040             try {
9041                 return mService.setTime(admin, millis);
9042             } catch (RemoteException e) {
9043                 throw e.rethrowFromSystemServer();
9044             }
9045         }
9046         return false;
9047     }
9048 
9049     /**
9050      * Called by a device owner or a profile owner of an organization-owned managed
9051      * profile to set the system's persistent default time zone. This only takes
9052      * effect if called when {@link android.provider.Settings.Global#AUTO_TIME_ZONE}
9053      * is 0, otherwise {@code false} will be returned.
9054      *
9055      * @see android.app.AlarmManager#setTimeZone(String)
9056      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
9057      * @param timeZone one of the Olson ids from the list returned by
9058      *     {@link java.util.TimeZone#getAvailableIDs}
9059      * @return {@code true} if set timezone succeeded, {@code false} otherwise.
9060      * @throws SecurityException if {@code admin} is not a device owner or a profile owner
9061      * of an organization-owned managed profile.
9062      */
setTimeZone(@onNull ComponentName admin, String timeZone)9063     public boolean setTimeZone(@NonNull ComponentName admin, String timeZone) {
9064         throwIfParentInstance("setTimeZone");
9065         if (mService != null) {
9066             try {
9067                 return mService.setTimeZone(admin, timeZone);
9068             } catch (RemoteException e) {
9069                 throw e.rethrowFromSystemServer();
9070             }
9071         }
9072         return false;
9073     }
9074 
9075     /**
9076      * Called by device owners to set the user's master location setting.
9077      *
9078      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
9079      * @param locationEnabled whether location should be enabled or disabled
9080      * @throws SecurityException if {@code admin} is not a device owner.
9081      */
setLocationEnabled(@onNull ComponentName admin, boolean locationEnabled)9082     public void setLocationEnabled(@NonNull ComponentName admin, boolean locationEnabled) {
9083         throwIfParentInstance("setLocationEnabled");
9084         if (mService != null) {
9085             try {
9086                 mService.setLocationEnabled(admin, locationEnabled);
9087             } catch (RemoteException e) {
9088                 throw e.rethrowFromSystemServer();
9089             }
9090         }
9091     }
9092 
9093     /**
9094      * This method is mostly deprecated.
9095      * Most of the settings that still have an effect have dedicated setter methods
9096      * (e.g. {@link #setLocationEnabled}) or user restrictions.
9097      * <p>
9098      *
9099      * Called by profile or device owners to update {@link android.provider.Settings.Secure}
9100      * settings. Validation that the value of the setting is in the correct form for the setting
9101      * type should be performed by the caller.
9102      * <p>
9103      * The settings that can be updated by a profile or device owner with this method are:
9104      * <ul>
9105      * <li>{@link android.provider.Settings.Secure#DEFAULT_INPUT_METHOD}</li>
9106      * <li>{@link android.provider.Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
9107      * </ul>
9108      * <p>
9109      * A device owner can additionally update the following settings:
9110      * <ul>
9111      * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}, but see note below.</li>
9112      * </ul>
9113      *
9114      * <strong>Note: Starting from Android O, apps should no longer call this method with the
9115      * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is
9116      * deprecated. Instead, device owners or profile owners should use the restriction
9117      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}.
9118      * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method
9119      * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS},
9120      * an {@link UnsupportedOperationException} is thrown.
9121      *
9122      * Starting from Android Q, the device and profile owner can also call
9123      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY} to restrict unknown sources for
9124      * all users.
9125      * </strong>
9126      *
9127      * <strong>Note: Starting from Android R, apps should no longer call this method with the
9128      * setting {@link android.provider.Settings.Secure#LOCATION_MODE}, which is deprecated. Instead,
9129      * device owners should call {@link #setLocationEnabled(ComponentName, boolean)}. This will be
9130      * enforced for all apps targeting Android R or above.
9131      * </strong>
9132      *
9133      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9134      * @param setting The name of the setting to update.
9135      * @param value The value to update the setting to.
9136      * @throws SecurityException if {@code admin} is not a device or profile owner.
9137      */
setSecureSetting(@onNull ComponentName admin, String setting, String value)9138     public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
9139         throwIfParentInstance("setSecureSetting");
9140 
9141         if (mService != null) {
9142             try {
9143                 mService.setSecureSetting(admin, setting, value);
9144             } catch (RemoteException e) {
9145                 throw e.rethrowFromSystemServer();
9146             }
9147         }
9148     }
9149 
9150     /**
9151      * Designates a specific service component as the provider for making permission requests of a
9152      * local or remote administrator of the user.
9153      * <p/>
9154      * Only a profile owner can designate the restrictions provider.
9155      *
9156      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9157      * @param provider The component name of the service that implements
9158      *            {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
9159      *            provider previously assigned.
9160      * @throws SecurityException if {@code admin} is not a device or profile owner.
9161      */
setRestrictionsProvider(@onNull ComponentName admin, @Nullable ComponentName provider)9162     public void setRestrictionsProvider(@NonNull ComponentName admin,
9163             @Nullable ComponentName provider) {
9164         throwIfParentInstance("setRestrictionsProvider");
9165         if (mService != null) {
9166             try {
9167                 mService.setRestrictionsProvider(admin, provider);
9168             } catch (RemoteException re) {
9169                 throw re.rethrowFromSystemServer();
9170             }
9171         }
9172     }
9173 
9174     /**
9175      * Called by profile or device owners to set the master volume mute on or off.
9176      * This has no effect when set on a managed profile.
9177      *
9178      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9179      * @param on {@code true} to mute master volume, {@code false} to turn mute off.
9180      * @throws SecurityException if {@code admin} is not a device or profile owner.
9181      */
setMasterVolumeMuted(@onNull ComponentName admin, boolean on)9182     public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
9183         throwIfParentInstance("setMasterVolumeMuted");
9184         if (mService != null) {
9185             try {
9186                 mService.setMasterVolumeMuted(admin, on);
9187             } catch (RemoteException re) {
9188                 throw re.rethrowFromSystemServer();
9189             }
9190         }
9191     }
9192 
9193     /**
9194      * Called by profile or device owners to check whether the master volume mute is on or off.
9195      *
9196      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9197      * @return {@code true} if master volume is muted, {@code false} if it's not.
9198      * @throws SecurityException if {@code admin} is not a device or profile owner.
9199      */
isMasterVolumeMuted(@onNull ComponentName admin)9200     public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
9201         throwIfParentInstance("isMasterVolumeMuted");
9202         if (mService != null) {
9203             try {
9204                 return mService.isMasterVolumeMuted(admin);
9205             } catch (RemoteException re) {
9206                 throw re.rethrowFromSystemServer();
9207             }
9208         }
9209         return false;
9210     }
9211 
9212     /**
9213      * Change whether a user can uninstall a package. This function can be called by a device owner,
9214      * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via
9215      * {@link #setDelegatedScopes}.
9216      *
9217      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9218      *             {@code null} if the caller is a block uninstall delegate.
9219      * @param packageName package to change.
9220      * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
9221      * @throws SecurityException if {@code admin} is not a device or profile owner.
9222      * @see #setDelegatedScopes
9223      * @see #DELEGATION_BLOCK_UNINSTALL
9224      */
setUninstallBlocked(@ullable ComponentName admin, String packageName, boolean uninstallBlocked)9225     public void setUninstallBlocked(@Nullable ComponentName admin, String packageName,
9226             boolean uninstallBlocked) {
9227         throwIfParentInstance("setUninstallBlocked");
9228         if (mService != null) {
9229             try {
9230                 mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName,
9231                     uninstallBlocked);
9232             } catch (RemoteException re) {
9233                 throw re.rethrowFromSystemServer();
9234             }
9235         }
9236     }
9237 
9238     /**
9239      * Check whether the user has been blocked by device policy from uninstalling a package.
9240      * Requires the caller to be the profile owner if checking a specific admin's policy.
9241      * <p>
9242      * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
9243      * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
9244      * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
9245      * will cause a NullPointerException to be raised.
9246      *
9247      * @param admin The name of the admin component whose blocking policy will be checked, or
9248      *            {@code null} to check whether any admin has blocked the uninstallation.
9249      * @param packageName package to check.
9250      * @return true if uninstallation is blocked.
9251      * @throws SecurityException if {@code admin} is not a device or profile owner.
9252      */
isUninstallBlocked(@ullable ComponentName admin, String packageName)9253     public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
9254         throwIfParentInstance("isUninstallBlocked");
9255         if (mService != null) {
9256             try {
9257                 return mService.isUninstallBlocked(admin, packageName);
9258             } catch (RemoteException re) {
9259                 throw re.rethrowFromSystemServer();
9260             }
9261         }
9262         return false;
9263     }
9264 
9265     /**
9266      * Called by the profile owner of a managed profile to enable widget providers from a given
9267      * package to be available in the parent profile. As a result the user will be able to add
9268      * widgets from the white-listed package running under the profile to a widget host which runs
9269      * under the parent profile, for example the home screen. Note that a package may have zero or
9270      * more provider components, where each component provides a different widget type.
9271      * <p>
9272      * <strong>Note:</strong> By default no widget provider package is white-listed.
9273      *
9274      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9275      * @param packageName The package from which widget providers are white-listed.
9276      * @return Whether the package was added.
9277      * @throws SecurityException if {@code admin} is not a profile owner.
9278      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
9279      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
9280      */
addCrossProfileWidgetProvider(@onNull ComponentName admin, String packageName)9281     public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
9282         throwIfParentInstance("addCrossProfileWidgetProvider");
9283         if (mService != null) {
9284             try {
9285                 return mService.addCrossProfileWidgetProvider(admin, packageName);
9286             } catch (RemoteException re) {
9287                 throw re.rethrowFromSystemServer();
9288             }
9289         }
9290         return false;
9291     }
9292 
9293     /**
9294      * Called by the profile owner of a managed profile to disable widget providers from a given
9295      * package to be available in the parent profile. For this method to take effect the package
9296      * should have been added via
9297      * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
9298      * <p>
9299      * <strong>Note:</strong> By default no widget provider package is white-listed.
9300      *
9301      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9302      * @param packageName The package from which widget providers are no longer white-listed.
9303      * @return Whether the package was removed.
9304      * @throws SecurityException if {@code admin} is not a profile owner.
9305      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
9306      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
9307      */
removeCrossProfileWidgetProvider( @onNull ComponentName admin, String packageName)9308     public boolean removeCrossProfileWidgetProvider(
9309             @NonNull ComponentName admin, String packageName) {
9310         throwIfParentInstance("removeCrossProfileWidgetProvider");
9311         if (mService != null) {
9312             try {
9313                 return mService.removeCrossProfileWidgetProvider(admin, packageName);
9314             } catch (RemoteException re) {
9315                 throw re.rethrowFromSystemServer();
9316             }
9317         }
9318         return false;
9319     }
9320 
9321     /**
9322      * Called by the profile owner of a managed profile to query providers from which packages are
9323      * available in the parent profile.
9324      *
9325      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9326      * @return The white-listed package list.
9327      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
9328      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
9329      * @throws SecurityException if {@code admin} is not a profile owner.
9330      */
getCrossProfileWidgetProviders(@onNull ComponentName admin)9331     public @NonNull List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
9332         throwIfParentInstance("getCrossProfileWidgetProviders");
9333         if (mService != null) {
9334             try {
9335                 List<String> providers = mService.getCrossProfileWidgetProviders(admin);
9336                 if (providers != null) {
9337                     return providers;
9338                 }
9339             } catch (RemoteException re) {
9340                 throw re.rethrowFromSystemServer();
9341             }
9342         }
9343         return Collections.emptyList();
9344     }
9345 
9346     /**
9347      * Called by profile or device owners to set the user's photo.
9348      *
9349      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9350      * @param icon the bitmap to set as the photo.
9351      * @throws SecurityException if {@code admin} is not a device or profile owner.
9352      */
setUserIcon(@onNull ComponentName admin, Bitmap icon)9353     public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
9354         throwIfParentInstance("setUserIcon");
9355         try {
9356             mService.setUserIcon(admin, icon);
9357         } catch (RemoteException re) {
9358             throw re.rethrowFromSystemServer();
9359         }
9360     }
9361 
9362     /**
9363      * Called by device owners or profile owners of an organization-owned managed profile to to set
9364      * a local system update policy. When a new policy is set,
9365      * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
9366      * <p>
9367      * If the supplied system update policy has freeze periods set but the freeze periods do not
9368      * meet 90-day maximum length or 60-day minimum separation requirement set out in
9369      * {@link SystemUpdatePolicy#setFreezePeriods},
9370      * {@link SystemUpdatePolicy.ValidationFailedException} will the thrown. Note that the system
9371      * keeps a record of freeze periods the device experienced previously, and combines them with
9372      * the new freeze periods to be set when checking the maximum freeze length and minimum freeze
9373      * separation constraints. As a result, freeze periods that passed validation during
9374      * {@link SystemUpdatePolicy#setFreezePeriods} might fail the additional checks here due to
9375      * the freeze period history. If this is causing issues during development,
9376      * {@code adb shell dpm clear-freeze-period-record} can be used to clear the record.
9377      *
9378      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
9379      *            components in the device owner package can set system update policies and the most
9380      *            recent policy takes effect.
9381      * @param policy the new policy, or {@code null} to clear the current policy.
9382      * @throws SecurityException if {@code admin} is not a device owner or a profile owner of an
9383      *      organization-owned managed profile.
9384      * @throws IllegalArgumentException if the policy type or maintenance window is not valid.
9385      * @throws SystemUpdatePolicy.ValidationFailedException if the policy's freeze period does not
9386      *             meet the requirement.
9387      * @see SystemUpdatePolicy
9388      * @see SystemUpdatePolicy#setFreezePeriods(List)
9389      */
setSystemUpdatePolicy(@onNull ComponentName admin, SystemUpdatePolicy policy)9390     public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
9391         throwIfParentInstance("setSystemUpdatePolicy");
9392         if (mService != null) {
9393             try {
9394                 mService.setSystemUpdatePolicy(admin, policy);
9395             } catch (RemoteException re) {
9396                 throw re.rethrowFromSystemServer();
9397             }
9398         }
9399     }
9400 
9401     /**
9402      * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
9403      *
9404      * @return The current policy object, or {@code null} if no policy is set.
9405      */
getSystemUpdatePolicy()9406     public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
9407         throwIfParentInstance("getSystemUpdatePolicy");
9408         if (mService != null) {
9409             try {
9410                 return mService.getSystemUpdatePolicy();
9411             } catch (RemoteException re) {
9412                 throw re.rethrowFromSystemServer();
9413             }
9414         }
9415         return null;
9416     }
9417 
9418     /**
9419      * Reset record of previous system update freeze period the device went through.
9420      * Only callable by ADB.
9421      * @hide
9422      */
clearSystemUpdatePolicyFreezePeriodRecord()9423     public void clearSystemUpdatePolicyFreezePeriodRecord() {
9424         throwIfParentInstance("clearSystemUpdatePolicyFreezePeriodRecord");
9425         if (mService == null) {
9426             return;
9427         }
9428         try {
9429             mService.clearSystemUpdatePolicyFreezePeriodRecord();
9430         } catch (RemoteException re) {
9431             throw re.rethrowFromSystemServer();
9432         }
9433     }
9434 
9435     /**
9436      * Called by a device owner or profile owner of secondary users that is affiliated with the
9437      * device to disable the keyguard altogether.
9438      * <p>
9439      * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
9440      * type. However, this call has no effect if a password, pin or pattern is currently set. If a
9441      * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
9442      * disabled.
9443      *
9444      * <p>
9445      * As of {@link android.os.Build.VERSION_CODES#P}, this call also dismisses the
9446      * keyguard if it is currently shown.
9447      *
9448      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9449      * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
9450      * @return {@code false} if attempting to disable the keyguard while a lock password was in
9451      *         place. {@code true} otherwise.
9452      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
9453      * secondary user that is affiliated with the device.
9454      * @see #isAffiliatedUser
9455      * @see #getSecondaryUsers
9456      */
setKeyguardDisabled(@onNull ComponentName admin, boolean disabled)9457     public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
9458         throwIfParentInstance("setKeyguardDisabled");
9459         try {
9460             return mService.setKeyguardDisabled(admin, disabled);
9461         } catch (RemoteException re) {
9462             throw re.rethrowFromSystemServer();
9463         }
9464     }
9465 
9466     /**
9467      * Called by device owner or profile owner of secondary users that is affiliated with the
9468      * device to disable the status bar. Disabling the status bar blocks notifications and quick
9469      * settings.
9470      * <p>
9471      * <strong>Note:</strong> This method has no effect for LockTask mode. The behavior of the
9472      * status bar in LockTask mode can be configured with
9473      * {@link #setLockTaskFeatures(ComponentName, int)}. Calls to this method when the device is in
9474      * LockTask mode will be registered, but will only take effect when the device leaves LockTask
9475      * mode.
9476      *
9477      * <p>This policy does not have any effect while on the lock screen, where the status bar will
9478      * not be disabled. Using LockTask instead of this method is recommended.
9479      *
9480      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9481      * @param disabled {@code true} disables the status bar, {@code false} reenables it.
9482      * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
9483      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
9484      * secondary user that is affiliated with the device.
9485      * @see #isAffiliatedUser
9486      * @see #getSecondaryUsers
9487      */
setStatusBarDisabled(@onNull ComponentName admin, boolean disabled)9488     public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
9489         throwIfParentInstance("setStatusBarDisabled");
9490         try {
9491             return mService.setStatusBarDisabled(admin, disabled);
9492         } catch (RemoteException re) {
9493             throw re.rethrowFromSystemServer();
9494         }
9495     }
9496 
9497     /**
9498      * Called by the system update service to notify device and profile owners of pending system
9499      * updates.
9500      *
9501      * This method should only be used when it is unknown whether the pending system
9502      * update is a security patch. Otherwise, use
9503      * {@link #notifyPendingSystemUpdate(long, boolean)}.
9504      *
9505      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
9506      *         indicating when the current pending update was first available. {@code -1} if no
9507      *         update is available.
9508      * @see #notifyPendingSystemUpdate(long, boolean)
9509      * @hide
9510      */
9511     @SystemApi
9512     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime)9513     public void notifyPendingSystemUpdate(long updateReceivedTime) {
9514         throwIfParentInstance("notifyPendingSystemUpdate");
9515         if (mService != null) {
9516             try {
9517                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime));
9518             } catch (RemoteException re) {
9519                 throw re.rethrowFromSystemServer();
9520             }
9521         }
9522     }
9523 
9524     /**
9525      * Called by the system update service to notify device and profile owners of pending system
9526      * updates.
9527      *
9528      * This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
9529      * when it is known whether the pending system update is a security patch.
9530      *
9531      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
9532      *         indicating when the current pending update was first available. {@code -1} if no
9533      *         update is available.
9534      * @param isSecurityPatch {@code true} if this system update is purely a security patch;
9535      *         {@code false} if not.
9536      * @see #notifyPendingSystemUpdate(long)
9537      * @hide
9538      */
9539     @SystemApi
9540     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch)9541     public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) {
9542         throwIfParentInstance("notifyPendingSystemUpdate");
9543         if (mService != null) {
9544             try {
9545                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime,
9546                         isSecurityPatch));
9547             } catch (RemoteException re) {
9548                 throw re.rethrowFromSystemServer();
9549             }
9550         }
9551     }
9552 
9553     /**
9554      * Called by device or profile owners to get information about a pending system update.
9555      *
9556      * @param admin Which profile or device owner this request is associated with.
9557      * @return Information about a pending system update or {@code null} if no update pending.
9558      * @throws SecurityException if {@code admin} is not a device or profile owner.
9559      * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long)
9560      */
getPendingSystemUpdate(@onNull ComponentName admin)9561     public @Nullable SystemUpdateInfo getPendingSystemUpdate(@NonNull ComponentName admin) {
9562         throwIfParentInstance("getPendingSystemUpdate");
9563         try {
9564             return mService.getPendingSystemUpdate(admin);
9565         } catch (RemoteException re) {
9566             throw re.rethrowFromSystemServer();
9567         }
9568     }
9569 
9570     /**
9571      * Set the default response for future runtime permission requests by applications. This
9572      * function can be called by a device owner, profile owner, or by a delegate given the
9573      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
9574      * The policy can allow for normal operation which prompts the user to grant a permission, or
9575      * can allow automatic granting or denying of runtime permission requests by an application.
9576      * This also applies to new permissions declared by app updates. When a permission is denied or
9577      * granted this way, the effect is equivalent to setting the permission * grant state via
9578      * {@link #setPermissionGrantState}.
9579      * <p/>
9580      * As this policy only acts on runtime permission requests, it only applies to applications
9581      * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
9582      *
9583      * @param admin Which profile or device owner this request is associated with.
9584      * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
9585      *            {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
9586      * @throws SecurityException if {@code admin} is not a device or profile owner.
9587      * @see #setPermissionGrantState
9588      * @see #setDelegatedScopes
9589      * @see #DELEGATION_PERMISSION_GRANT
9590      */
setPermissionPolicy(@onNull ComponentName admin, int policy)9591     public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
9592         throwIfParentInstance("setPermissionPolicy");
9593         try {
9594             mService.setPermissionPolicy(admin, mContext.getPackageName(), policy);
9595         } catch (RemoteException re) {
9596             throw re.rethrowFromSystemServer();
9597         }
9598     }
9599 
9600     /**
9601      * Returns the current runtime permission policy set by the device or profile owner. The
9602      * default is {@link #PERMISSION_POLICY_PROMPT}.
9603      *
9604      * @param admin Which profile or device owner this request is associated with.
9605      * @return the current policy for future permission requests.
9606      */
getPermissionPolicy(ComponentName admin)9607     public int getPermissionPolicy(ComponentName admin) {
9608         throwIfParentInstance("getPermissionPolicy");
9609         try {
9610             return mService.getPermissionPolicy(admin);
9611         } catch (RemoteException re) {
9612             throw re.rethrowFromSystemServer();
9613         }
9614     }
9615 
9616     /**
9617      * Sets the grant state of a runtime permission for a specific application. The state can be
9618      * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
9619      * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
9620      * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
9621      * the permission is granted and the user cannot manage it through the UI. This method can only
9622      * be called by a profile owner, device owner, or a delegate given the
9623      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
9624      * <p/>
9625      * Note that user cannot manage other permissions in the affected group through the UI
9626      * either and their granted state will be kept as the current value. Thus, it's recommended that
9627      * you set the grant state of all the permissions in the affected group.
9628      * <p/>
9629      * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
9630      * the permission. It retains the previous grant, if any.
9631      * <p/>
9632      * Device admins with a {@code targetSdkVersion} &lt; {@link android.os.Build.VERSION_CODES#Q}
9633      * cannot grant and revoke permissions for applications built with a {@code targetSdkVersion}
9634      * &lt; {@link android.os.Build.VERSION_CODES#M}.
9635      * <p/>
9636      * Admins with a {@code targetSdkVersion} &ge; {@link android.os.Build.VERSION_CODES#Q} can
9637      * grant and revoke permissions of all apps. Similar to the user revoking a permission from a
9638      * application built with a {@code targetSdkVersion} &lt;
9639      * {@link android.os.Build.VERSION_CODES#M} the app-op matching the permission is set to
9640      * {@link android.app.AppOpsManager#MODE_IGNORED}, but the permission stays granted.
9641      *
9642      * @param admin Which profile or device owner this request is associated with.
9643      * @param packageName The application to grant or revoke a permission to.
9644      * @param permission The permission to grant or revoke.
9645      * @param grantState The permission grant state which is one of
9646      *            {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
9647      *            {@link #PERMISSION_GRANT_STATE_GRANTED},
9648      * @return whether the permission was successfully granted or revoked.
9649      * @throws SecurityException if {@code admin} is not a device or profile owner.
9650      * @see #PERMISSION_GRANT_STATE_DENIED
9651      * @see #PERMISSION_GRANT_STATE_DEFAULT
9652      * @see #PERMISSION_GRANT_STATE_GRANTED
9653      * @see #setDelegatedScopes
9654      * @see #DELEGATION_PERMISSION_GRANT
9655      */
setPermissionGrantState(@onNull ComponentName admin, @NonNull String packageName, @NonNull String permission, @PermissionGrantState int grantState)9656     public boolean setPermissionGrantState(@NonNull ComponentName admin,
9657             @NonNull String packageName, @NonNull String permission,
9658             @PermissionGrantState int grantState) {
9659         throwIfParentInstance("setPermissionGrantState");
9660         try {
9661             CompletableFuture<Boolean> result = new CompletableFuture<>();
9662 
9663             mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName,
9664                     permission, grantState, new RemoteCallback((b) -> result.complete(b != null)));
9665 
9666             // Timeout
9667             BackgroundThread.getHandler().sendMessageDelayed(
9668                     obtainMessage(CompletableFuture::complete, result, false),
9669                     20_000);
9670 
9671             return result.get();
9672         } catch (RemoteException re) {
9673             throw re.rethrowFromSystemServer();
9674         } catch (InterruptedException | ExecutionException e) {
9675             throw new RuntimeException(e);
9676         }
9677     }
9678 
9679     /**
9680      * Returns the current grant state of a runtime permission for a specific application. This
9681      * function can be called by a device owner, profile owner, or by a delegate given the
9682      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
9683      *
9684      * @param admin Which profile or device owner this request is associated with, or {@code null}
9685      *            if the caller is a permission grant delegate.
9686      * @param packageName The application to check the grant state for.
9687      * @param permission The permission to check for.
9688      * @return the current grant state specified by device policy. If the profile or device owner
9689      *         has not set a grant state, the return value is
9690      *         {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
9691      *         permission is currently granted for the package.
9692      *         <p/>
9693      *         If a grant state was set by the profile or device owner, then the return value will
9694      *         be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
9695      *         {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
9696      *         currently denied or granted.
9697      * @throws SecurityException if {@code admin} is not a device or profile owner.
9698      * @see #setPermissionGrantState(ComponentName, String, String, int)
9699      * @see PackageManager#checkPermission(String, String)
9700      * @see #setDelegatedScopes
9701      * @see #DELEGATION_PERMISSION_GRANT
9702      */
getPermissionGrantState(@ullable ComponentName admin, @NonNull String packageName, @NonNull String permission)9703     public @PermissionGrantState int getPermissionGrantState(@Nullable ComponentName admin,
9704             @NonNull String packageName, @NonNull String permission) {
9705         throwIfParentInstance("getPermissionGrantState");
9706         try {
9707             return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName,
9708                     permission);
9709         } catch (RemoteException re) {
9710             throw re.rethrowFromSystemServer();
9711         }
9712     }
9713 
9714     /**
9715      * Returns whether it is possible for the caller to initiate provisioning of a managed profile
9716      * or device, setting itself as the device or profile owner.
9717      *
9718      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
9719      * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
9720      * @return whether provisioning a managed profile or device is possible.
9721      * @throws IllegalArgumentException if the supplied action is not valid.
9722      */
isProvisioningAllowed(@onNull String action)9723     public boolean isProvisioningAllowed(@NonNull String action) {
9724         throwIfParentInstance("isProvisioningAllowed");
9725         try {
9726             return mService.isProvisioningAllowed(action, mContext.getPackageName());
9727         } catch (RemoteException re) {
9728             throw re.rethrowFromSystemServer();
9729         }
9730     }
9731 
9732     /**
9733      * Checks whether it is possible to initiate provisioning a managed device,
9734      * profile or user, setting the given package as owner.
9735      *
9736      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
9737      *        {@link #ACTION_PROVISION_MANAGED_PROFILE},
9738      *        {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE},
9739      *        {@link #ACTION_PROVISION_MANAGED_USER}
9740      * @param packageName The package of the component that would be set as device, user, or profile
9741      *        owner.
9742      * @return A {@link ProvisioningPreCondition} value indicating whether provisioning is allowed.
9743      * @hide
9744      */
checkProvisioningPreCondition( String action, @NonNull String packageName)9745     public @ProvisioningPreCondition int checkProvisioningPreCondition(
9746             String action, @NonNull String packageName) {
9747         try {
9748             return mService.checkProvisioningPreCondition(action, packageName);
9749         } catch (RemoteException re) {
9750             throw re.rethrowFromSystemServer();
9751         }
9752     }
9753 
9754     /**
9755      * Return if this user is a managed profile of another user. An admin can become the profile
9756      * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
9757      * user with {@link #createAndManageUser}
9758      * @param admin Which profile owner this request is associated with.
9759      * @return if this user is a managed profile of another user.
9760      */
isManagedProfile(@onNull ComponentName admin)9761     public boolean isManagedProfile(@NonNull ComponentName admin) {
9762         throwIfParentInstance("isManagedProfile");
9763         try {
9764             return mService.isManagedProfile(admin);
9765         } catch (RemoteException re) {
9766             throw re.rethrowFromSystemServer();
9767         }
9768     }
9769 
9770     /**
9771      * @hide
9772      * Return if this user is a system-only user. An admin can manage a device from a system only
9773      * user by calling {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE}.
9774      * @param admin Which device owner this request is associated with.
9775      * @return if this user is a system-only user.
9776      */
isSystemOnlyUser(@onNull ComponentName admin)9777     public boolean isSystemOnlyUser(@NonNull ComponentName admin) {
9778         try {
9779             return mService.isSystemOnlyUser(admin);
9780         } catch (RemoteException re) {
9781             throw re.rethrowFromSystemServer();
9782         }
9783     }
9784 
9785     /**
9786      * Called by device owner, or profile owner on organization-owned device, to get the MAC
9787      * address of the Wi-Fi device.
9788      *
9789      * NOTE: The MAC address returned here should only be used for inventory management and is
9790      * not likely to be the MAC address used by the device to connect to Wi-Fi networks: MAC
9791      * addresses used for scanning and connecting to Wi-Fi networks are randomized by default.
9792      * To get the randomized MAC address used, call
9793      * {@link android.net.wifi.WifiConfiguration#getRandomizedMacAddress}.
9794      *
9795      * @param admin Which device owner this request is associated with.
9796      * @return the MAC address of the Wi-Fi device, or null when the information is not available.
9797      *         (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
9798      *         <p>
9799      *         The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
9800      * @throws SecurityException if {@code admin} is not a device owner.
9801      */
getWifiMacAddress(@onNull ComponentName admin)9802     public @Nullable String getWifiMacAddress(@NonNull ComponentName admin) {
9803         throwIfParentInstance("getWifiMacAddress");
9804         try {
9805             return mService.getWifiMacAddress(admin);
9806         } catch (RemoteException re) {
9807             throw re.rethrowFromSystemServer();
9808         }
9809     }
9810 
9811     /**
9812      * Called by device owner to reboot the device. If there is an ongoing call on the device,
9813      * throws an {@link IllegalStateException}.
9814      * @param admin Which device owner the request is associated with.
9815      * @throws IllegalStateException if device has an ongoing call.
9816      * @throws SecurityException if {@code admin} is not a device owner.
9817      * @see TelephonyManager#CALL_STATE_IDLE
9818      */
reboot(@onNull ComponentName admin)9819     public void reboot(@NonNull ComponentName admin) {
9820         throwIfParentInstance("reboot");
9821         try {
9822             mService.reboot(admin);
9823         } catch (RemoteException re) {
9824             throw re.rethrowFromSystemServer();
9825         }
9826     }
9827 
9828     /**
9829      * Called by a device admin to set the short support message. This will be displayed to the user
9830      * in settings screens where funtionality has been disabled by the admin. The message should be
9831      * limited to a short statement such as "This setting is disabled by your administrator. Contact
9832      * someone@example.com for support." If the message is longer than 200 characters it may be
9833      * truncated.
9834      * <p>
9835      * If the short support message needs to be localized, it is the responsibility of the
9836      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9837      * and set a new version of this string accordingly.
9838      *
9839      * @see #setLongSupportMessage
9840      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9841      * @param message Short message to be displayed to the user in settings or null to clear the
9842      *            existing message.
9843      * @throws SecurityException if {@code admin} is not an active administrator.
9844      */
setShortSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)9845     public void setShortSupportMessage(@NonNull ComponentName admin,
9846             @Nullable CharSequence message) {
9847         throwIfParentInstance("setShortSupportMessage");
9848         if (mService != null) {
9849             try {
9850                 mService.setShortSupportMessage(admin, message);
9851             } catch (RemoteException e) {
9852                 throw e.rethrowFromSystemServer();
9853             }
9854         }
9855     }
9856 
9857     /**
9858      * Called by a device admin to get the short support message.
9859      *
9860      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9861      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
9862      *         null if no message has been set.
9863      * @throws SecurityException if {@code admin} is not an active administrator.
9864      */
getShortSupportMessage(@onNull ComponentName admin)9865     public CharSequence getShortSupportMessage(@NonNull ComponentName admin) {
9866         throwIfParentInstance("getShortSupportMessage");
9867         if (mService != null) {
9868             try {
9869                 return mService.getShortSupportMessage(admin);
9870             } catch (RemoteException e) {
9871                 throw e.rethrowFromSystemServer();
9872             }
9873         }
9874         return null;
9875     }
9876 
9877     /**
9878      * Called by a device admin to set the long support message. This will be displayed to the user
9879      * in the device administators settings screen.
9880      * <p>
9881      * If the long support message needs to be localized, it is the responsibility of the
9882      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9883      * and set a new version of this string accordingly.
9884      *
9885      * @see #setShortSupportMessage
9886      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9887      * @param message Long message to be displayed to the user in settings or null to clear the
9888      *            existing message.
9889      * @throws SecurityException if {@code admin} is not an active administrator.
9890      */
setLongSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)9891     public void setLongSupportMessage(@NonNull ComponentName admin,
9892             @Nullable CharSequence message) {
9893         throwIfParentInstance("setLongSupportMessage");
9894         if (mService != null) {
9895             try {
9896                 mService.setLongSupportMessage(admin, message);
9897             } catch (RemoteException e) {
9898                 throw e.rethrowFromSystemServer();
9899             }
9900         }
9901     }
9902 
9903     /**
9904      * Called by a device admin to get the long support message.
9905      *
9906      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9907      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
9908      *         null if no message has been set.
9909      * @throws SecurityException if {@code admin} is not an active administrator.
9910      */
getLongSupportMessage(@onNull ComponentName admin)9911     public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
9912         throwIfParentInstance("getLongSupportMessage");
9913         if (mService != null) {
9914             try {
9915                 return mService.getLongSupportMessage(admin);
9916             } catch (RemoteException e) {
9917                 throw e.rethrowFromSystemServer();
9918             }
9919         }
9920         return null;
9921     }
9922 
9923     /**
9924      * Called by the system to get the short support message.
9925      *
9926      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9927      * @param userHandle user id the admin is running as.
9928      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
9929      *
9930      * @hide
9931      */
getShortSupportMessageForUser(@onNull ComponentName admin, int userHandle)9932     public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
9933             int userHandle) {
9934         if (mService != null) {
9935             try {
9936                 return mService.getShortSupportMessageForUser(admin, userHandle);
9937             } catch (RemoteException e) {
9938                 throw e.rethrowFromSystemServer();
9939             }
9940         }
9941         return null;
9942     }
9943 
9944 
9945     /**
9946      * Called by the system to get the long support message.
9947      *
9948      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9949      * @param userHandle user id the admin is running as.
9950      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
9951      *
9952      * @hide
9953      */
getLongSupportMessageForUser( @onNull ComponentName admin, int userHandle)9954     public @Nullable CharSequence getLongSupportMessageForUser(
9955             @NonNull ComponentName admin, int userHandle) {
9956         if (mService != null) {
9957             try {
9958                 return mService.getLongSupportMessageForUser(admin, userHandle);
9959             } catch (RemoteException e) {
9960                 throw e.rethrowFromSystemServer();
9961             }
9962         }
9963         return null;
9964     }
9965 
9966     /**
9967      * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
9968      * whose calls act on the parent profile.
9969      *
9970      * <p>The following methods are supported for the parent instance, all other methods will
9971      * throw a SecurityException when called on the parent instance:
9972      * <ul>
9973      * <li>{@link #getPasswordQuality}</li>
9974      * <li>{@link #setPasswordQuality}</li>
9975      * <li>{@link #getPasswordMinimumLength}</li>
9976      * <li>{@link #setPasswordMinimumLength}</li>
9977      * <li>{@link #getPasswordMinimumUpperCase}</li>
9978      * <li>{@link #setPasswordMinimumUpperCase}</li>
9979      * <li>{@link #getPasswordMinimumLowerCase}</li>
9980      * <li>{@link #setPasswordMinimumLowerCase}</li>
9981      * <li>{@link #getPasswordMinimumLetters}</li>
9982      * <li>{@link #setPasswordMinimumLetters}</li>
9983      * <li>{@link #getPasswordMinimumNumeric}</li>
9984      * <li>{@link #setPasswordMinimumNumeric}</li>
9985      * <li>{@link #getPasswordMinimumSymbols}</li>
9986      * <li>{@link #setPasswordMinimumSymbols}</li>
9987      * <li>{@link #getPasswordMinimumNonLetter}</li>
9988      * <li>{@link #setPasswordMinimumNonLetter}</li>
9989      * <li>{@link #getPasswordHistoryLength}</li>
9990      * <li>{@link #setPasswordHistoryLength}</li>
9991      * <li>{@link #getPasswordExpirationTimeout}</li>
9992      * <li>{@link #setPasswordExpirationTimeout}</li>
9993      * <li>{@link #getPasswordExpiration}</li>
9994      * <li>{@link #getPasswordMaximumLength}</li>
9995      * <li>{@link #isActivePasswordSufficient}</li>
9996      * <li>{@link #getCurrentFailedPasswordAttempts}</li>
9997      * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
9998      * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
9999      * <li>{@link #getMaximumTimeToLock}</li>
10000      * <li>{@link #setMaximumTimeToLock}</li>
10001      * <li>{@link #lockNow}</li>
10002      * <li>{@link #getKeyguardDisabledFeatures}</li>
10003      * <li>{@link #setKeyguardDisabledFeatures}</li>
10004      * <li>{@link #getTrustAgentConfiguration}</li>
10005      * <li>{@link #setTrustAgentConfiguration}</li>
10006      * <li>{@link #getRequiredStrongAuthTimeout}</li>
10007      * <li>{@link #setRequiredStrongAuthTimeout}</li>
10008      * <li>{@link #getAccountTypesWithManagementDisabled}</li>
10009      * </ul>
10010      * <p>
10011      * The following methods are supported for the parent instance but can only be called by the
10012      * profile owner of a managed profile that was created during the device provisioning flow:
10013      * <ul>
10014      * <li>{@link #getPasswordComplexity}</li>
10015      * <li>{@link #setCameraDisabled}</li>
10016      * <li>{@link #getCameraDisabled}</li>
10017      * <li>{@link #setAccountManagementDisabled(ComponentName, String, boolean)}</li>
10018      * </ul>
10019      *
10020      * <p>The following methods can be called by the profile owner of a managed profile
10021      * on an organization-owned device:
10022      * <ul>
10023      * <li>{@link #wipeData}</li>
10024      * </ul>
10025      *
10026      * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
10027      * @throws SecurityException if {@code admin} is not a profile owner.
10028      */
getParentProfileInstance(@onNull ComponentName admin)10029     public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
10030         throwIfParentInstance("getParentProfileInstance");
10031         try {
10032             if (!mService.isManagedProfile(admin)) {
10033                 throw new SecurityException("The current user does not have a parent profile.");
10034             }
10035             return new DevicePolicyManager(mContext, mService, true);
10036         } catch (RemoteException e) {
10037             throw e.rethrowFromSystemServer();
10038         }
10039     }
10040 
10041     /**
10042      * Called by device owner or a profile owner of an organization-owned managed profile to
10043      * control the security logging feature.
10044      *
10045      * <p> Security logs contain various information intended for security auditing purposes.
10046      * When security logging is enabled by a profile owner of
10047      * an organization-owned managed profile, certain security logs are not visible (for example
10048      * personal app launch events) or they will be redacted (for example, details of the physical
10049      * volume mount events). Please see {@link SecurityEvent} for details.
10050      *
10051      * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there
10052      * are unaffiliated secondary users or profiles on the device, regardless of whether the
10053      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
10054      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
10055      * new users as soon as possible after provisioning via {@link #setAffiliationIds}. Profile
10056      * owner of organization-owned managed profile is not subject to this restriction since all
10057      * privacy-sensitive events happening outside the managed profile would have been redacted
10058      * already.
10059      *
10060      * @param admin Which device admin this request is associated with.
10061      * @param enabled whether security logging should be enabled or not.
10062      * @throws SecurityException if {@code admin} is not allowed to control security logging.
10063      * @see #setAffiliationIds
10064      * @see #retrieveSecurityLogs
10065      */
setSecurityLoggingEnabled(@onNull ComponentName admin, boolean enabled)10066     public void setSecurityLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
10067         throwIfParentInstance("setSecurityLoggingEnabled");
10068         try {
10069             mService.setSecurityLoggingEnabled(admin, enabled);
10070         } catch (RemoteException re) {
10071             throw re.rethrowFromSystemServer();
10072         }
10073     }
10074 
10075     /**
10076      * Return whether security logging is enabled or not by the admin.
10077      *
10078      * <p>Can only be called by the device owner or a profile owner of an organization-owned
10079      * managed profile, otherwise a {@link SecurityException} will be thrown.
10080      *
10081      * @param admin Which device admin this request is associated with.
10082      * @return {@code true} if security logging is enabled by device owner, {@code false} otherwise.
10083      * @throws SecurityException if {@code admin} is not allowed to control security logging.
10084      */
isSecurityLoggingEnabled(@ullable ComponentName admin)10085     public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) {
10086         throwIfParentInstance("isSecurityLoggingEnabled");
10087         try {
10088             return mService.isSecurityLoggingEnabled(admin);
10089         } catch (RemoteException re) {
10090             throw re.rethrowFromSystemServer();
10091         }
10092     }
10093 
10094     /**
10095      * Called by device owner or profile owner of an organization-owned managed profile to retrieve
10096      * all new security logging entries since the last call to this API after device boots.
10097      *
10098      * <p> Access to the logs is rate limited and it will only return new logs after the device
10099      * owner has been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
10100      *
10101      * <p> When called by a device owner, if there is any other user or profile on the device,
10102      * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown.
10103      * See {@link #isAffiliatedUser}.
10104      *
10105      * @param admin Which device admin this request is associated with.
10106      * @return the new batch of security logs which is a list of {@link SecurityEvent},
10107      * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
10108      * @throws SecurityException if {@code admin} is not allowed to access security logging,
10109      * or there is at least one profile or secondary user that is not affiliated with the device.
10110      * @see #isAffiliatedUser
10111      * @see DeviceAdminReceiver#onSecurityLogsAvailable
10112      */
retrieveSecurityLogs(@onNull ComponentName admin)10113     public @Nullable List<SecurityEvent> retrieveSecurityLogs(@NonNull ComponentName admin) {
10114         throwIfParentInstance("retrieveSecurityLogs");
10115         try {
10116             ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(admin);
10117             if (list != null) {
10118                 return list.getList();
10119             } else {
10120                 // Rate limit exceeded.
10121                 return null;
10122             }
10123         } catch (RemoteException re) {
10124             throw re.rethrowFromSystemServer();
10125         }
10126     }
10127 
10128     /**
10129      * Makes all accumulated network logs available to DPC in a new batch.
10130      * Only callable by ADB. If throttled, returns time to wait in milliseconds, otherwise 0.
10131      * @hide
10132      */
forceNetworkLogs()10133     public long forceNetworkLogs() {
10134         if (mService == null) {
10135             return -1;
10136         }
10137         try {
10138             return mService.forceNetworkLogs();
10139         } catch (RemoteException re) {
10140             throw re.rethrowFromSystemServer();
10141         }
10142     }
10143 
10144     /**
10145      * Forces a batch of security logs to be fetched from logd and makes it available for DPC.
10146      * Only callable by ADB. If throttled, returns time to wait in milliseconds, otherwise 0.
10147      * @hide
10148      */
forceSecurityLogs()10149     public long forceSecurityLogs() {
10150         if (mService == null) {
10151             return 0;
10152         }
10153         try {
10154             return mService.forceSecurityLogs();
10155         } catch (RemoteException re) {
10156             throw re.rethrowFromSystemServer();
10157         }
10158     }
10159 
10160     /**
10161      * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
10162      * profile.
10163      *
10164      * @hide
10165      */
getParentProfileInstance(UserInfo uInfo)10166     public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
10167         mContext.checkSelfPermission(
10168                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
10169         if (!uInfo.isManagedProfile()) {
10170             throw new SecurityException("The user " + uInfo.id
10171                     + " does not have a parent profile.");
10172         }
10173         return new DevicePolicyManager(mContext, mService, true);
10174     }
10175 
10176     /**
10177      * Called by a device or profile owner to restrict packages from using metered data.
10178      *
10179      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10180      * @param packageNames the list of package names to be restricted.
10181      * @return a list of package names which could not be restricted.
10182      * @throws SecurityException if {@code admin} is not a device or profile owner.
10183      */
setMeteredDataDisabledPackages(@onNull ComponentName admin, @NonNull List<String> packageNames)10184     public @NonNull List<String> setMeteredDataDisabledPackages(@NonNull ComponentName admin,
10185             @NonNull List<String> packageNames) {
10186         throwIfParentInstance("setMeteredDataDisabled");
10187         if (mService != null) {
10188             try {
10189                 return mService.setMeteredDataDisabledPackages(admin, packageNames);
10190             } catch (RemoteException re) {
10191                 throw re.rethrowFromSystemServer();
10192             }
10193         }
10194         return packageNames;
10195     }
10196 
10197     /**
10198      * Called by a device or profile owner to retrieve the list of packages which are restricted
10199      * by the admin from using metered data.
10200      *
10201      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10202      * @return the list of restricted package names.
10203      * @throws SecurityException if {@code admin} is not a device or profile owner.
10204      */
getMeteredDataDisabledPackages(@onNull ComponentName admin)10205     public @NonNull List<String> getMeteredDataDisabledPackages(@NonNull ComponentName admin) {
10206         throwIfParentInstance("getMeteredDataDisabled");
10207         if (mService != null) {
10208             try {
10209                 return mService.getMeteredDataDisabledPackages(admin);
10210             } catch (RemoteException re) {
10211                 throw re.rethrowFromSystemServer();
10212             }
10213         }
10214         return new ArrayList<>();
10215     }
10216 
10217     /**
10218      * Called by the system to check if a package is restricted from using metered data
10219      * by {@param admin}.
10220      *
10221      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10222      * @param packageName the package whose restricted status is needed.
10223      * @param userId the user to which {@param packageName} belongs.
10224      * @return {@code true} if the package is restricted by admin, otherwise {@code false}
10225      * @throws SecurityException if the caller doesn't run with {@link Process#SYSTEM_UID}
10226      * @hide
10227      */
isMeteredDataDisabledPackageForUser(@onNull ComponentName admin, String packageName, @UserIdInt int userId)10228     public boolean isMeteredDataDisabledPackageForUser(@NonNull ComponentName admin,
10229             String packageName, @UserIdInt int userId) {
10230         throwIfParentInstance("getMeteredDataDisabledForUser");
10231         if (mService != null) {
10232             try {
10233                 return mService.isMeteredDataDisabledPackageForUser(admin, packageName, userId);
10234             } catch (RemoteException re) {
10235                 throw re.rethrowFromSystemServer();
10236             }
10237         }
10238         return false;
10239     }
10240 
10241     /**
10242      * Called by device owner or profile owner of an organization-owned managed profile to retrieve
10243      * device logs from before the device's last reboot.
10244      * <p>
10245      * <strong> This API is not supported on all devices. Calling this API on unsupported devices
10246      * will result in {@code null} being returned. The device logs are retrieved from a RAM region
10247      * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
10248      * about data corruption when parsing. </strong>
10249      *
10250      * <p> When called by a device owner, if there is any other user or profile on the device,
10251      * it must be affiliated with the device. Otherwise a {@link SecurityException} will be thrown.
10252      * See {@link #isAffiliatedUser}.
10253      *
10254      * @param admin Which device admin this request is associated with.
10255      * @return Device logs from before the latest reboot of the system, or {@code null} if this API
10256      *         is not supported on the device.
10257      * @throws SecurityException if {@code admin} is not allowed to access security logging, or
10258      * there is at least one profile or secondary user that is not affiliated with the device.
10259      * @see #isAffiliatedUser
10260      * @see #retrieveSecurityLogs
10261      */
retrievePreRebootSecurityLogs( @onNull ComponentName admin)10262     public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
10263             @NonNull ComponentName admin) {
10264         throwIfParentInstance("retrievePreRebootSecurityLogs");
10265         try {
10266             ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(admin);
10267             if (list != null) {
10268                 return list.getList();
10269             } else {
10270                 return null;
10271             }
10272         } catch (RemoteException re) {
10273             throw re.rethrowFromSystemServer();
10274         }
10275     }
10276 
10277     /**
10278      * Called by a profile owner of a managed profile to set the color used for customization. This
10279      * color is used as background color of the confirm credentials screen for that user. The
10280      * default color is teal (#00796B).
10281      * <p>
10282      * The confirm credentials screen can be created using
10283      * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
10284      * <p>
10285      * Starting from Android R, the organization color will no longer be used as the background
10286      * color of the confirm credentials screen.
10287      *
10288      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10289      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
10290      * @throws SecurityException if {@code admin} is not a profile owner.
10291      */
setOrganizationColor(@onNull ComponentName admin, int color)10292     public void setOrganizationColor(@NonNull ComponentName admin, int color) {
10293         throwIfParentInstance("setOrganizationColor");
10294         try {
10295             // always enforce alpha channel to have 100% opacity
10296             color |= 0xFF000000;
10297             mService.setOrganizationColor(admin, color);
10298         } catch (RemoteException re) {
10299             throw re.rethrowFromSystemServer();
10300         }
10301     }
10302 
10303     /**
10304      * @hide
10305      *
10306      * Sets the color used for customization.
10307      *
10308      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
10309      * @param userId which user to set the color to.
10310      * @RequiresPermission(allOf = {
10311      *       Manifest.permission.MANAGE_USERS,
10312      *       Manifest.permission.INTERACT_ACROSS_USERS_FULL})
10313      */
setOrganizationColorForUser(@olorInt int color, @UserIdInt int userId)10314     public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
10315         try {
10316             // always enforce alpha channel to have 100% opacity
10317             color |= 0xFF000000;
10318             mService.setOrganizationColorForUser(color, userId);
10319         } catch (RemoteException re) {
10320             throw re.rethrowFromSystemServer();
10321         }
10322     }
10323 
10324     /**
10325      * Called by a profile owner of a managed profile to retrieve the color used for customization.
10326      * This color is used as background color of the confirm credentials screen for that user.
10327      *
10328      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10329      * @return The 24bit (0xRRGGBB) representation of the color to be used.
10330      * @throws SecurityException if {@code admin} is not a profile owner.
10331      */
getOrganizationColor(@onNull ComponentName admin)10332     public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
10333         throwIfParentInstance("getOrganizationColor");
10334         try {
10335             return mService.getOrganizationColor(admin);
10336         } catch (RemoteException re) {
10337             throw re.rethrowFromSystemServer();
10338         }
10339     }
10340 
10341     /**
10342      * @hide
10343      * Retrieve the customization color for a given user.
10344      *
10345      * @param userHandle The user id of the user we're interested in.
10346      * @return The 24bit (0xRRGGBB) representation of the color to be used.
10347      */
getOrganizationColorForUser(int userHandle)10348     public @ColorInt int getOrganizationColorForUser(int userHandle) {
10349         try {
10350             return mService.getOrganizationColorForUser(userHandle);
10351         } catch (RemoteException re) {
10352             throw re.rethrowFromSystemServer();
10353         }
10354     }
10355 
10356     /**
10357      * Called by the device owner (since API 26) or profile owner (since API 24) to set the name of
10358      * the organization under management.
10359      *
10360      * <p>If the organization name needs to be localized, it is the responsibility of the {@link
10361      * DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast and set
10362      * a new version of this string accordingly.
10363      *
10364      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10365      * @param title The organization name or {@code null} to clear a previously set name.
10366      * @throws SecurityException if {@code admin} is not a device or profile owner.
10367      */
setOrganizationName(@onNull ComponentName admin, @Nullable CharSequence title)10368     public void setOrganizationName(@NonNull ComponentName admin, @Nullable CharSequence title) {
10369         throwIfParentInstance("setOrganizationName");
10370         try {
10371             mService.setOrganizationName(admin, title);
10372         } catch (RemoteException re) {
10373             throw re.rethrowFromSystemServer();
10374         }
10375     }
10376 
10377     /**
10378      * Called by a profile owner of a managed profile to retrieve the name of the organization under
10379      * management.
10380      *
10381      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10382      * @return The organization name or {@code null} if none is set.
10383      * @throws SecurityException if {@code admin} is not a profile owner.
10384      */
getOrganizationName(@onNull ComponentName admin)10385     public @Nullable CharSequence getOrganizationName(@NonNull ComponentName admin) {
10386         throwIfParentInstance("getOrganizationName");
10387         try {
10388             return mService.getOrganizationName(admin);
10389         } catch (RemoteException re) {
10390             throw re.rethrowFromSystemServer();
10391         }
10392     }
10393 
10394     /**
10395      * Called by the system to retrieve the name of the organization managing the device.
10396      *
10397      * @return The organization name or {@code null} if none is set.
10398      * @throws SecurityException if the caller is not the device owner, does not hold the
10399      *         MANAGE_USERS permission and is not the system.
10400      *
10401      * @hide
10402      */
10403     @SystemApi
10404     @TestApi
10405     @SuppressLint("Doclava125")
getDeviceOwnerOrganizationName()10406     public @Nullable CharSequence getDeviceOwnerOrganizationName() {
10407         try {
10408             return mService.getDeviceOwnerOrganizationName();
10409         } catch (RemoteException re) {
10410             throw re.rethrowFromSystemServer();
10411         }
10412     }
10413 
10414     /**
10415      * Retrieve the default title message used in the confirm credentials screen for a given user.
10416      *
10417      * @param userHandle The user id of the user we're interested in.
10418      * @return The organization name or {@code null} if none is set.
10419      *
10420      * @hide
10421      */
getOrganizationNameForUser(int userHandle)10422     public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
10423         try {
10424             return mService.getOrganizationNameForUser(userHandle);
10425         } catch (RemoteException re) {
10426             throw re.rethrowFromSystemServer();
10427         }
10428     }
10429 
10430     /**
10431      * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
10432      *         return {@link #STATE_USER_UNMANAGED}
10433      * @hide
10434      */
10435     @SystemApi
10436     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
10437     @UserProvisioningState
getUserProvisioningState()10438     public int getUserProvisioningState() {
10439         throwIfParentInstance("getUserProvisioningState");
10440         if (mService != null) {
10441             try {
10442                 return mService.getUserProvisioningState();
10443             } catch (RemoteException e) {
10444                 throw e.rethrowFromSystemServer();
10445             }
10446         }
10447         return STATE_USER_UNMANAGED;
10448     }
10449 
10450     /**
10451      * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
10452      *
10453      * @param state to store
10454      * @param userHandle for user
10455      * @hide
10456      */
setUserProvisioningState(@serProvisioningState int state, int userHandle)10457     public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
10458         if (mService != null) {
10459             try {
10460                 mService.setUserProvisioningState(state, userHandle);
10461             } catch (RemoteException e) {
10462                 throw e.rethrowFromSystemServer();
10463             }
10464         }
10465     }
10466 
10467     /**
10468      * Indicates the entity that controls the device. Two users are
10469      * affiliated if the set of ids set by the device owner and the admin of the secondary user.
10470      *
10471      * <p>A user that is affiliated with the device owner user is considered to be
10472      * affiliated with the device.
10473      *
10474      * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
10475      * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user
10476      * is created, until it becomes affiliated. Therefore it is recommended that the appropriate
10477      * affiliation ids are set by its owner as soon as possible after the user is
10478      * created.
10479      * <p>
10480      * Note: This method used to be available for affiliating device owner and profile
10481      * owner. However, since Android 11, this combination is not possible. This method is now
10482      * only useful for affiliating the primary user with managed secondary users.
10483      *
10484      * @param admin Which device owner, or owner of secondary user, this request is associated with.
10485      * @param ids A set of opaque non-empty affiliation ids.
10486      *
10487      * @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
10488      * @see #isAffiliatedUser
10489      */
setAffiliationIds(@onNull ComponentName admin, @NonNull Set<String> ids)10490     public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) {
10491         throwIfParentInstance("setAffiliationIds");
10492         if (ids == null) {
10493             throw new IllegalArgumentException("ids must not be null");
10494         }
10495         try {
10496             mService.setAffiliationIds(admin, new ArrayList<>(ids));
10497         } catch (RemoteException e) {
10498             throw e.rethrowFromSystemServer();
10499         }
10500     }
10501 
10502     /**
10503      * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
10504      * empty set if none have been set.
10505      */
getAffiliationIds(@onNull ComponentName admin)10506     public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
10507         throwIfParentInstance("getAffiliationIds");
10508         try {
10509             return new ArraySet<>(mService.getAffiliationIds(admin));
10510         } catch (RemoteException e) {
10511             throw e.rethrowFromSystemServer();
10512         }
10513     }
10514 
10515     /**
10516      * Returns whether this user is affiliated with the device.
10517      * <p>
10518      * By definition, the user that the device owner runs on is always affiliated with the device.
10519      * Any other user is considered affiliated with the device if the set specified by its
10520      * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
10521      * @see #setAffiliationIds
10522      */
isAffiliatedUser()10523     public boolean isAffiliatedUser() {
10524         throwIfParentInstance("isAffiliatedUser");
10525         try {
10526             return mService.isAffiliatedUser();
10527         } catch (RemoteException e) {
10528             throw e.rethrowFromSystemServer();
10529         }
10530     }
10531 
10532     /**
10533      * @hide
10534      * Returns whether the uninstall for {@code packageName} for the current user is in queue
10535      * to be started
10536      * @param packageName the package to check for
10537      * @return whether the uninstall intent for {@code packageName} is pending
10538      */
isUninstallInQueue(String packageName)10539     public boolean isUninstallInQueue(String packageName) {
10540         try {
10541             return mService.isUninstallInQueue(packageName);
10542         } catch (RemoteException re) {
10543             throw re.rethrowFromSystemServer();
10544         }
10545     }
10546 
10547     /**
10548      * @hide
10549      * @param packageName the package containing active DAs to be uninstalled
10550      */
uninstallPackageWithActiveAdmins(String packageName)10551     public void uninstallPackageWithActiveAdmins(String packageName) {
10552         try {
10553             mService.uninstallPackageWithActiveAdmins(packageName);
10554         } catch (RemoteException re) {
10555             throw re.rethrowFromSystemServer();
10556         }
10557     }
10558 
10559     /**
10560      * @hide
10561      * Remove a test admin synchronously without sending it a broadcast about being removed.
10562      * If the admin is a profile owner or device owner it will still be removed.
10563      *
10564      * @param userHandle user id to remove the admin for.
10565      * @param admin The administration compononent to remove.
10566      * @throws SecurityException if the caller is not shell / root or the admin package
10567      *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
10568      */
forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle)10569     public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
10570         try {
10571             mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
10572         } catch (RemoteException re) {
10573             throw re.rethrowFromSystemServer();
10574         }
10575     }
10576 
10577     /**
10578      * Returns whether the device has been provisioned.
10579      *
10580      * <p>Not for use by third-party applications.
10581      *
10582      * @hide
10583      */
10584     @SystemApi
10585     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioned()10586     public boolean isDeviceProvisioned() {
10587         try {
10588             return mService.isDeviceProvisioned();
10589         } catch (RemoteException re) {
10590             throw re.rethrowFromSystemServer();
10591         }
10592     }
10593 
10594     /**
10595       * Writes that the provisioning configuration has been applied.
10596       *
10597       * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
10598       * permission.
10599       *
10600       * <p>Not for use by third-party applications.
10601       *
10602       * @hide
10603       */
10604     @SystemApi
10605     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
setDeviceProvisioningConfigApplied()10606     public void setDeviceProvisioningConfigApplied() {
10607         try {
10608             mService.setDeviceProvisioningConfigApplied();
10609         } catch (RemoteException re) {
10610             throw re.rethrowFromSystemServer();
10611         }
10612     }
10613 
10614     /**
10615      * Returns whether the provisioning configuration has been applied.
10616      *
10617      * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
10618      *
10619      * <p>Not for use by third-party applications.
10620      *
10621      * @return whether the provisioning configuration has been applied.
10622      *
10623      * @hide
10624      */
10625     @SystemApi
10626     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioningConfigApplied()10627     public boolean isDeviceProvisioningConfigApplied() {
10628         try {
10629             return mService.isDeviceProvisioningConfigApplied();
10630         } catch (RemoteException re) {
10631             throw re.rethrowFromSystemServer();
10632         }
10633     }
10634 
10635     /**
10636      * @hide
10637      * Force update user setup completed status. This API has no effect on user build.
10638      * @throws {@link SecurityException} if the caller has no
10639      *         {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS} or the caller is
10640      *         not {@link UserHandle#SYSTEM_USER}
10641      */
forceUpdateUserSetupComplete()10642     public void forceUpdateUserSetupComplete() {
10643         try {
10644             mService.forceUpdateUserSetupComplete();
10645         } catch (RemoteException re) {
10646             throw re.rethrowFromSystemServer();
10647         }
10648     }
10649 
10650     @UnsupportedAppUsage
throwIfParentInstance(String functionName)10651     private void throwIfParentInstance(String functionName) {
10652         if (mParentInstance) {
10653             throw new SecurityException(functionName + " cannot be called on the parent instance");
10654         }
10655     }
10656 
10657     /**
10658      * Allows the device owner or profile owner to enable or disable the backup service.
10659      *
10660      * <p> Each user has its own backup service which manages the backup and restore mechanisms in
10661      * that user. Disabling the backup service will prevent data from being backed up or restored.
10662      *
10663      * <p> Device owner calls this API to control backup services across all users on the device.
10664      * Profile owner can use this API to enable or disable the profile's backup service. However,
10665      * for a managed profile its backup functionality is only enabled if both the device owner
10666      * and the profile owner have enabled the backup service.
10667      *
10668      * <p> By default, backup service is disabled on a device with device owner, and within a
10669      * managed profile.
10670      *
10671      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10672      * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
10673      * @throws SecurityException if {@code admin} is not a device owner or a profile owner.
10674      */
setBackupServiceEnabled(@onNull ComponentName admin, boolean enabled)10675     public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
10676         throwIfParentInstance("setBackupServiceEnabled");
10677         try {
10678             mService.setBackupServiceEnabled(admin, enabled);
10679         } catch (RemoteException re) {
10680             throw re.rethrowFromSystemServer();
10681         }
10682     }
10683 
10684     /**
10685      * Return whether the backup service is enabled by the device owner or profile owner for the
10686      * current user, as previously set by {@link #setBackupServiceEnabled(ComponentName, boolean)}.
10687      *
10688      * <p> Whether the backup functionality is actually enabled or not depends on settings from both
10689      * the current user and the device owner, please see
10690      * {@link #setBackupServiceEnabled(ComponentName, boolean)} for details.
10691      *
10692      * <p> Backup service manages all backup and restore mechanisms on the device.
10693      *
10694      * @return {@code true} if backup service is enabled, {@code false} otherwise.
10695      * @see #setBackupServiceEnabled
10696      */
isBackupServiceEnabled(@onNull ComponentName admin)10697     public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
10698         throwIfParentInstance("isBackupServiceEnabled");
10699         try {
10700             return mService.isBackupServiceEnabled(admin);
10701         } catch (RemoteException re) {
10702             throw re.rethrowFromSystemServer();
10703         }
10704     }
10705 
10706     /**
10707      * Called by a device owner or delegated app with {@link #DELEGATION_NETWORK_LOGGING} to
10708      * control the network logging feature.
10709      *
10710      * <p> Network logs contain DNS lookup and connect() library call events. The following library
10711      *     functions are recorded while network logging is active:
10712      *     <ul>
10713      *       <li>{@code getaddrinfo()}</li>
10714      *       <li>{@code gethostbyname()}</li>
10715      *       <li>{@code connect()}</li>
10716      *     </ul>
10717      *
10718      * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
10719      *     full system call logging; event reporting is enabled by default for all processes but not
10720      *     strongly enforced.
10721      *     Events from applications using alternative implementations of libc, making direct kernel
10722      *     calls, or deliberately obfuscating traffic may not be recorded.
10723      *
10724      * <p> Some common network events may not be reported. For example:
10725      *     <ul>
10726      *       <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
10727      *           an alternative system for name resolution, and so avoid calling
10728      *           {@code getaddrinfo()} or {@code gethostbyname}.</li>
10729      *       <li>Applications may use datagram sockets for performance reasons, for example
10730      *           for a game client. Calling {@code connect()} is unnecessary for this kind of
10731      *           socket, so it will not trigger a network event.</li>
10732      *     </ul>
10733      *
10734      * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
10735      *     always-on VPN service.
10736      *     See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
10737      *     and {@link android.net.VpnService} for details.
10738      *
10739      * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
10740      * are unaffiliated secondary users or profiles on the device, regardless of whether the
10741      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
10742      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
10743      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
10744      *
10745      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10746      *        {@code null} if called by a delegated app.
10747      * @param enabled whether network logging should be enabled or not.
10748      * @throws SecurityException if {@code admin} is not a device owner.
10749      * @see #setAffiliationIds
10750      * @see #retrieveNetworkLogs
10751      */
setNetworkLoggingEnabled(@ullable ComponentName admin, boolean enabled)10752     public void setNetworkLoggingEnabled(@Nullable ComponentName admin, boolean enabled) {
10753         throwIfParentInstance("setNetworkLoggingEnabled");
10754         try {
10755             mService.setNetworkLoggingEnabled(admin, mContext.getPackageName(), enabled);
10756         } catch (RemoteException re) {
10757             throw re.rethrowFromSystemServer();
10758         }
10759     }
10760 
10761     /**
10762      * Return whether network logging is enabled by a device owner.
10763      *
10764      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
10765      * be {@code null} if the caller is a delegated app with {@link #DELEGATION_NETWORK_LOGGING}
10766      * or has MANAGE_USERS permission.
10767      * @return {@code true} if network logging is enabled by device owner, {@code false} otherwise.
10768      * @throws SecurityException if {@code admin} is not a device owner and caller has
10769      * no MANAGE_USERS permission
10770      */
isNetworkLoggingEnabled(@ullable ComponentName admin)10771     public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
10772         throwIfParentInstance("isNetworkLoggingEnabled");
10773         try {
10774             return mService.isNetworkLoggingEnabled(admin, mContext.getPackageName());
10775         } catch (RemoteException re) {
10776             throw re.rethrowFromSystemServer();
10777         }
10778     }
10779 
10780     /**
10781      * Called by device owner or delegated app with {@link #DELEGATION_NETWORK_LOGGING} to retrieve
10782      * the most recent batch of network logging events.
10783      * A device owner has to provide a batchToken provided as part of
10784      * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
10785      * token of the most recent available batch of logs, {@code null} will be returned.
10786      *
10787      * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
10788      *
10789      * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
10790      *
10791      * <p> Access to the logs is rate limited and this method will only return a new batch of logs
10792      * after the device device owner has been notified via
10793      * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
10794      *
10795      * <p>If a secondary user or profile is created, calling this method will throw a
10796      * {@link SecurityException} until all users become affiliated again. It will also no longer be
10797      * possible to retrieve the network logs batch with the most recent batchToken provided
10798      * by {@link DeviceAdminReceiver#onNetworkLogsAvailable}. See
10799      * {@link DevicePolicyManager#setAffiliationIds}.
10800      *
10801      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
10802      *        {@code null} if called by a delegated app.
10803      * @param batchToken A token of the batch to retrieve
10804      * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
10805      *        {@code null} if the batch represented by batchToken is no longer available or if
10806      *        logging is disabled.
10807      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
10808      * profile or secondary user that is not affiliated with the device.
10809      * @see #setAffiliationIds
10810      * @see DeviceAdminReceiver#onNetworkLogsAvailable
10811      */
retrieveNetworkLogs(@ullable ComponentName admin, long batchToken)10812     public @Nullable List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin,
10813             long batchToken) {
10814         throwIfParentInstance("retrieveNetworkLogs");
10815         try {
10816             return mService.retrieveNetworkLogs(admin, mContext.getPackageName(), batchToken);
10817         } catch (RemoteException re) {
10818             throw re.rethrowFromSystemServer();
10819         }
10820     }
10821 
10822     /**
10823      * Called by a device owner to bind to a service from a secondary managed user or vice versa.
10824      * See {@link #getBindDeviceAdminTargetUsers} for the pre-requirements of a
10825      * device owner to bind to services of another managed user.
10826      * <p>
10827      * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
10828      * Note that the {@link Context} used to obtain this
10829      * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
10830      * to bind to the {@link android.app.Service}.
10831      * <p>
10832      * Note: This method used to be available for communication between device owner and profile
10833      * owner. However, since Android 11, this combination is not possible. This method is now
10834      * only useful for communication between device owner and managed secondary users.
10835      *
10836      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10837      * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
10838      *        explicit component name or a package name to match an
10839      *        {@link IntentFilter} published by a service.
10840      * @param conn Receives information as the service is started and stopped in main thread. This
10841      *        must be a valid {@link ServiceConnection} object; it must not be {@code null}.
10842      * @param flags Operation options for the binding operation. See
10843      *        {@link Context#bindService(Intent, ServiceConnection, int)}.
10844      * @param targetUser Which user to bind to. Must be one of the users returned by
10845      *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
10846      *        be thrown.
10847      * @return If you have successfully bound to the service, {@code true} is returned;
10848      *         {@code false} is returned if the connection is not made and you will not
10849      *         receive the service object.
10850      *
10851      * @see Context#bindService(Intent, ServiceConnection, int)
10852      * @see #getBindDeviceAdminTargetUsers(ComponentName)
10853      */
bindDeviceAdminServiceAsUser( @onNull ComponentName admin, Intent serviceIntent, @NonNull ServiceConnection conn, @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser)10854     public boolean bindDeviceAdminServiceAsUser(
10855             @NonNull ComponentName admin,  Intent serviceIntent, @NonNull ServiceConnection conn,
10856             @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser) {
10857         throwIfParentInstance("bindDeviceAdminServiceAsUser");
10858         // Keep this in sync with ContextImpl.bindServiceCommon.
10859         try {
10860             final IServiceConnection sd = mContext.getServiceDispatcher(
10861                     conn, mContext.getMainThreadHandler(), flags);
10862             serviceIntent.prepareToLeaveProcess(mContext);
10863             return mService.bindDeviceAdminServiceAsUser(admin,
10864                     mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
10865                     sd, flags, targetUser.getIdentifier());
10866         } catch (RemoteException re) {
10867             throw re.rethrowFromSystemServer();
10868         }
10869     }
10870 
10871     /**
10872      * Returns the list of target users that the calling device owner or owner of secondary user
10873      * can use when calling {@link #bindDeviceAdminServiceAsUser}.
10874      * <p>
10875      * A device owner can bind to a service from a secondary managed user and vice versa, provided
10876      * that both users are affiliated. See {@link #setAffiliationIds}.
10877      */
getBindDeviceAdminTargetUsers(@onNull ComponentName admin)10878     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
10879         throwIfParentInstance("getBindDeviceAdminTargetUsers");
10880         try {
10881             return mService.getBindDeviceAdminTargetUsers(admin);
10882         } catch (RemoteException re) {
10883             throw re.rethrowFromSystemServer();
10884         }
10885     }
10886 
10887     /**
10888      * Called by the system to get the time at which the device owner last retrieved security
10889      * logging entries.
10890      *
10891      * @return the time at which the device owner most recently retrieved security logging entries,
10892      *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
10893      * @throws SecurityException if the caller is not the device owner, does not hold the
10894      *         MANAGE_USERS permission and is not the system.
10895      *
10896      * @hide
10897      */
10898     @TestApi
getLastSecurityLogRetrievalTime()10899     public long getLastSecurityLogRetrievalTime() {
10900         try {
10901             return mService.getLastSecurityLogRetrievalTime();
10902         } catch (RemoteException re) {
10903             throw re.rethrowFromSystemServer();
10904         }
10905     }
10906 
10907     /**
10908      * Called by the system to get the time at which the device owner last requested a bug report.
10909      *
10910      * @return the time at which the device owner most recently requested a bug report, in
10911      *         milliseconds since epoch; -1 if a bug report was never requested.
10912      * @throws SecurityException if the caller is not the device owner, does not hold the
10913      *         MANAGE_USERS permission and is not the system.
10914      *
10915      * @hide
10916      */
10917     @TestApi
getLastBugReportRequestTime()10918     public long getLastBugReportRequestTime() {
10919         try {
10920             return mService.getLastBugReportRequestTime();
10921         } catch (RemoteException re) {
10922             throw re.rethrowFromSystemServer();
10923         }
10924     }
10925 
10926     /**
10927      * Called by the system to get the time at which the device owner last retrieved network logging
10928      * events.
10929      *
10930      * @return the time at which the device owner most recently retrieved network logging events, in
10931      *         milliseconds since epoch; -1 if network logging events were never retrieved.
10932      * @throws SecurityException if the caller is not the device owner, does not hold the
10933      *         MANAGE_USERS permission and is not the system.
10934      *
10935      * @hide
10936      */
10937     @TestApi
getLastNetworkLogRetrievalTime()10938     public long getLastNetworkLogRetrievalTime() {
10939         try {
10940             return mService.getLastNetworkLogRetrievalTime();
10941         } catch (RemoteException re) {
10942             throw re.rethrowFromSystemServer();
10943         }
10944     }
10945 
10946     /**
10947      * Called by the system to find out whether the current user's IME was set by the device/profile
10948      * owner or the user.
10949      *
10950      * @return {@code true} if the user's IME was set by the device or profile owner, {@code false}
10951      *         otherwise.
10952      * @throws SecurityException if the caller is not the device owner/profile owner.
10953      *
10954      * @hide
10955      */
10956     @TestApi
isCurrentInputMethodSetByOwner()10957     public boolean isCurrentInputMethodSetByOwner() {
10958         try {
10959             return mService.isCurrentInputMethodSetByOwner();
10960         } catch (RemoteException re) {
10961             throw re.rethrowFromSystemServer();
10962         }
10963     }
10964 
10965     /**
10966      * Called by the system to get a list of CA certificates that were installed by the device or
10967      * profile owner.
10968      *
10969      * <p> The caller must be the target user's device owner/profile Owner or hold the
10970      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
10971      *
10972      * @param user The user for whom to retrieve information.
10973      * @return list of aliases identifying CA certificates installed by the device or profile owner
10974      * @throws SecurityException if the caller does not have permission to retrieve information
10975      *         about the given user's CA certificates.
10976      *
10977      * @hide
10978      */
10979     @TestApi
getOwnerInstalledCaCerts(@onNull UserHandle user)10980     public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
10981         try {
10982             return mService.getOwnerInstalledCaCerts(user).getList();
10983         } catch (RemoteException re) {
10984             throw re.rethrowFromSystemServer();
10985         }
10986     }
10987 
10988     /**
10989      * Returns whether factory reset protection policy is supported on the device.
10990      *
10991      * @return {@code true} if the device support factory reset protection policy.
10992      *
10993      * @hide
10994      */
10995     @TestApi
isFactoryResetProtectionPolicySupported()10996     public boolean isFactoryResetProtectionPolicySupported() {
10997         try {
10998             return mService.isFactoryResetProtectionPolicySupported();
10999         } catch (RemoteException re) {
11000             throw re.rethrowFromSystemServer();
11001         }
11002     }
11003 
11004     /**
11005      * Called by the device owner or profile owner to clear application user data of a given
11006      * package. The behaviour of this is equivalent to the target application calling
11007      * {@link android.app.ActivityManager#clearApplicationUserData()}.
11008      *
11009      * <p><strong>Note:</strong> an application can store data outside of its application data, e.g.
11010      * external storage or user dictionary. This data will not be wiped by calling this API.
11011      *
11012      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11013      * @param packageName The name of the package which will have its user data wiped.
11014      * @param executor The executor through which the listener should be invoked.
11015      * @param listener A callback object that will inform the caller when the clearing is done.
11016      * @throws SecurityException if the caller is not the device owner/profile owner.
11017      */
clearApplicationUserData(@onNull ComponentName admin, @NonNull String packageName, @NonNull @CallbackExecutor Executor executor, @NonNull OnClearApplicationUserDataListener listener)11018     public void clearApplicationUserData(@NonNull ComponentName admin,
11019             @NonNull String packageName, @NonNull @CallbackExecutor Executor executor,
11020             @NonNull OnClearApplicationUserDataListener listener) {
11021         throwIfParentInstance("clearAppData");
11022         Objects.requireNonNull(executor);
11023         Objects.requireNonNull(listener);
11024         try {
11025             mService.clearApplicationUserData(admin, packageName,
11026                     new IPackageDataObserver.Stub() {
11027                         public void onRemoveCompleted(String pkg, boolean succeeded) {
11028                             executor.execute(() ->
11029                                     listener.onApplicationUserDataCleared(pkg, succeeded));
11030                         }
11031                     });
11032         } catch (RemoteException re) {
11033             throw re.rethrowFromSystemServer();
11034         }
11035     }
11036 
11037     /**
11038      * Called by a device owner to specify whether logout is enabled for all secondary users. The
11039      * system may show a logout button that stops the user and switches back to the primary user.
11040      *
11041      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11042      * @param enabled whether logout should be enabled or not.
11043      * @throws SecurityException if {@code admin} is not a device owner.
11044      */
setLogoutEnabled(@onNull ComponentName admin, boolean enabled)11045     public void setLogoutEnabled(@NonNull ComponentName admin, boolean enabled) {
11046         throwIfParentInstance("setLogoutEnabled");
11047         try {
11048             mService.setLogoutEnabled(admin, enabled);
11049         } catch (RemoteException re) {
11050             throw re.rethrowFromSystemServer();
11051         }
11052     }
11053 
11054     /**
11055      * Returns whether logout is enabled by a device owner.
11056      *
11057      * @return {@code true} if logout is enabled by device owner, {@code false} otherwise.
11058      */
isLogoutEnabled()11059     public boolean isLogoutEnabled() {
11060         throwIfParentInstance("isLogoutEnabled");
11061         try {
11062             return mService.isLogoutEnabled();
11063         } catch (RemoteException re) {
11064             throw re.rethrowFromSystemServer();
11065         }
11066     }
11067 
11068     /**
11069      * Callback used in {@link #clearApplicationUserData}
11070      * to indicate that the clearing of an application's user data is done.
11071      */
11072     public interface OnClearApplicationUserDataListener {
11073         /**
11074          * Method invoked when clearing the application user data has completed.
11075          *
11076          * @param packageName The name of the package which had its user data cleared.
11077          * @param succeeded Whether the clearing succeeded. Clearing fails for device administrator
11078          *                  apps and protected system packages.
11079          */
onApplicationUserDataCleared(String packageName, boolean succeeded)11080         void onApplicationUserDataCleared(String packageName, boolean succeeded);
11081     }
11082 
11083     /**
11084      * Returns set of system apps that should be removed during provisioning.
11085      *
11086      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
11087      * @param userId ID of the user to be provisioned.
11088      * @param provisioningAction action indicating type of provisioning, should be one of
11089      * {@link #ACTION_PROVISION_MANAGED_DEVICE}, {@link #ACTION_PROVISION_MANAGED_PROFILE} or
11090      * {@link #ACTION_PROVISION_MANAGED_USER}.
11091      *
11092      * @hide
11093      */
getDisallowedSystemApps(ComponentName admin, int userId, String provisioningAction)11094     public Set<String> getDisallowedSystemApps(ComponentName admin, int userId,
11095             String provisioningAction) {
11096         try {
11097             return new ArraySet<>(
11098                     mService.getDisallowedSystemApps(admin, userId, provisioningAction));
11099         } catch (RemoteException re) {
11100             throw re.rethrowFromSystemServer();
11101         }
11102     }
11103 
11104     /**
11105      * Changes the current administrator to another one. All policies from the current
11106      * administrator are migrated to the new administrator. The whole operation is atomic -
11107      * the transfer is either complete or not done at all.
11108      *
11109      * <p>Depending on the current administrator (device owner, profile owner), you have the
11110      * following expected behaviour:
11111      * <ul>
11112      *     <li>A device owner can only be transferred to a new device owner</li>
11113      *     <li>A profile owner can only be transferred to a new profile owner</li>
11114      * </ul>
11115      *
11116      * <p>Use the {@code bundle} parameter to pass data to the new administrator. The data
11117      * will be received in the
11118      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}
11119      * callback of the new administrator.
11120      *
11121      * <p>The transfer has failed if the original administrator is still the corresponding owner
11122      * after calling this method.
11123      *
11124      * <p>The incoming target administrator must have the
11125      * <code>&lt;support-transfer-ownership /&gt;</code> tag inside the
11126      * <code>&lt;device-admin&gt;&lt;/device-admin&gt;</code> tags in the xml file referenced by
11127      * {@link DeviceAdminReceiver#DEVICE_ADMIN_META_DATA}. Otherwise an
11128      * {@link IllegalArgumentException} will be thrown.
11129      *
11130      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11131      * @param target which {@link DeviceAdminReceiver} we want the new administrator to be
11132      * @param bundle data to be sent to the new administrator
11133      * @throws SecurityException if {@code admin} is not a device owner nor a profile owner
11134      * @throws IllegalArgumentException if {@code admin} or {@code target} is {@code null}, they
11135      * are components in the same package or {@code target} is not an active admin
11136      */
transferOwnership(@onNull ComponentName admin, @NonNull ComponentName target, @Nullable PersistableBundle bundle)11137     public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
11138             @Nullable PersistableBundle bundle) {
11139         throwIfParentInstance("transferOwnership");
11140         try {
11141             mService.transferOwnership(admin, target, bundle);
11142         } catch (RemoteException re) {
11143             throw re.rethrowFromSystemServer();
11144         }
11145     }
11146 
11147     /**
11148      * Called by a device owner to specify the user session start message. This may be displayed
11149      * during a user switch.
11150      * <p>
11151      * The message should be limited to a short statement or it may be truncated.
11152      * <p>
11153      * If the message needs to be localized, it is the responsibility of the
11154      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
11155      * and set a new version of this message accordingly.
11156      *
11157      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11158      * @param startUserSessionMessage message for starting user session, or {@code null} to use
11159      * system default message.
11160      * @throws SecurityException if {@code admin} is not a device owner.
11161      */
setStartUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence startUserSessionMessage)11162     public void setStartUserSessionMessage(
11163             @NonNull ComponentName admin, @Nullable CharSequence startUserSessionMessage) {
11164         throwIfParentInstance("setStartUserSessionMessage");
11165         try {
11166             mService.setStartUserSessionMessage(admin, startUserSessionMessage);
11167         } catch (RemoteException re) {
11168             throw re.rethrowFromSystemServer();
11169         }
11170     }
11171 
11172     /**
11173      * Called by a device owner to specify the user session end message. This may be displayed
11174      * during a user switch.
11175      * <p>
11176      * The message should be limited to a short statement or it may be truncated.
11177      * <p>
11178      * If the message needs to be localized, it is the responsibility of the
11179      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
11180      * and set a new version of this message accordingly.
11181      *
11182      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11183      * @param endUserSessionMessage message for ending user session, or {@code null} to use system
11184      * default message.
11185      * @throws SecurityException if {@code admin} is not a device owner.
11186      */
setEndUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence endUserSessionMessage)11187     public void setEndUserSessionMessage(
11188             @NonNull ComponentName admin, @Nullable CharSequence endUserSessionMessage) {
11189         throwIfParentInstance("setEndUserSessionMessage");
11190         try {
11191             mService.setEndUserSessionMessage(admin, endUserSessionMessage);
11192         } catch (RemoteException re) {
11193             throw re.rethrowFromSystemServer();
11194         }
11195     }
11196 
11197     /**
11198      * Returns the user session start message.
11199      *
11200      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11201      * @throws SecurityException if {@code admin} is not a device owner.
11202      */
getStartUserSessionMessage(@onNull ComponentName admin)11203     public CharSequence getStartUserSessionMessage(@NonNull ComponentName admin) {
11204         throwIfParentInstance("getStartUserSessionMessage");
11205         try {
11206             return mService.getStartUserSessionMessage(admin);
11207         } catch (RemoteException re) {
11208             throw re.rethrowFromSystemServer();
11209         }
11210     }
11211 
11212     /**
11213      * Returns the user session end message.
11214      *
11215      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11216      * @throws SecurityException if {@code admin} is not a device owner.
11217      */
getEndUserSessionMessage(@onNull ComponentName admin)11218     public CharSequence getEndUserSessionMessage(@NonNull ComponentName admin) {
11219         throwIfParentInstance("getEndUserSessionMessage");
11220         try {
11221             return mService.getEndUserSessionMessage(admin);
11222         } catch (RemoteException re) {
11223             throw re.rethrowFromSystemServer();
11224         }
11225     }
11226 
11227     /**
11228      * Called by device owner to add an override APN.
11229      *
11230      * <p>This method may returns {@code -1} if {@code apnSetting} conflicts with an existing
11231      * override APN. Update the existing conflicted APN with
11232      * {@link #updateOverrideApn(ComponentName, int, ApnSetting)} instead of adding a new entry.
11233      * <p>Two override APNs are considered to conflict when all the following APIs return
11234      * the same values on both override APNs:
11235      * <ul>
11236      *   <li>{@link ApnSetting#getOperatorNumeric()}</li>
11237      *   <li>{@link ApnSetting#getApnName()}</li>
11238      *   <li>{@link ApnSetting#getProxyAddressAsString()}</li>
11239      *   <li>{@link ApnSetting#getProxyPort()}</li>
11240      *   <li>{@link ApnSetting#getMmsProxyAddressAsString()}</li>
11241      *   <li>{@link ApnSetting#getMmsProxyPort()}</li>
11242      *   <li>{@link ApnSetting#getMmsc()}</li>
11243      *   <li>{@link ApnSetting#isEnabled()}</li>
11244      *   <li>{@link ApnSetting#getMvnoType()}</li>
11245      *   <li>{@link ApnSetting#getProtocol()}</li>
11246      *   <li>{@link ApnSetting#getRoamingProtocol()}</li>
11247      * </ul>
11248      *
11249      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11250      * @param apnSetting the override APN to insert
11251      * @return The {@code id} of inserted override APN. Or {@code -1} when failed to insert into
11252      *         the database.
11253      * @throws SecurityException if {@code admin} is not a device owner.
11254      *
11255      * @see #setOverrideApnsEnabled(ComponentName, boolean)
11256      */
addOverrideApn(@onNull ComponentName admin, @NonNull ApnSetting apnSetting)11257     public int addOverrideApn(@NonNull ComponentName admin, @NonNull ApnSetting apnSetting) {
11258         throwIfParentInstance("addOverrideApn");
11259         if (mService != null) {
11260             try {
11261                 return mService.addOverrideApn(admin, apnSetting);
11262             } catch (RemoteException e) {
11263                 throw e.rethrowFromSystemServer();
11264             }
11265         }
11266         return -1;
11267     }
11268 
11269     /**
11270      * Called by device owner to update an override APN.
11271      *
11272      * <p>This method may returns {@code false} if there is no override APN with the given
11273      * {@code apnId}.
11274      * <p>This method may also returns {@code false} if {@code apnSetting} conflicts with an
11275      * existing override APN. Update the existing conflicted APN instead.
11276      * <p>See {@link #addOverrideApn} for the definition of conflict.
11277      *
11278      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11279      * @param apnId the {@code id} of the override APN to update
11280      * @param apnSetting the override APN to update
11281      * @return {@code true} if the required override APN is successfully updated,
11282      *         {@code false} otherwise.
11283      * @throws SecurityException if {@code admin} is not a device owner.
11284      *
11285      * @see #setOverrideApnsEnabled(ComponentName, boolean)
11286      */
updateOverrideApn(@onNull ComponentName admin, int apnId, @NonNull ApnSetting apnSetting)11287     public boolean updateOverrideApn(@NonNull ComponentName admin, int apnId,
11288             @NonNull ApnSetting apnSetting) {
11289         throwIfParentInstance("updateOverrideApn");
11290         if (mService != null) {
11291             try {
11292                 return mService.updateOverrideApn(admin, apnId, apnSetting);
11293             } catch (RemoteException e) {
11294                 throw e.rethrowFromSystemServer();
11295             }
11296         }
11297         return false;
11298     }
11299 
11300     /**
11301      * Called by device owner to remove an override APN.
11302      *
11303      * <p>This method may returns {@code false} if there is no override APN with the given
11304      * {@code apnId}.
11305      *
11306      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11307      * @param apnId the {@code id} of the override APN to remove
11308      * @return {@code true} if the required override APN is successfully removed, {@code false}
11309      *         otherwise.
11310      * @throws SecurityException if {@code admin} is not a device owner.
11311      *
11312      * @see #setOverrideApnsEnabled(ComponentName, boolean)
11313      */
removeOverrideApn(@onNull ComponentName admin, int apnId)11314     public boolean removeOverrideApn(@NonNull ComponentName admin, int apnId) {
11315         throwIfParentInstance("removeOverrideApn");
11316         if (mService != null) {
11317             try {
11318                 return mService.removeOverrideApn(admin, apnId);
11319             } catch (RemoteException e) {
11320                 throw e.rethrowFromSystemServer();
11321             }
11322         }
11323         return false;
11324     }
11325 
11326     /**
11327      * Called by device owner to get all override APNs inserted by device owner.
11328      *
11329      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11330      * @return A list of override APNs inserted by device owner.
11331      * @throws SecurityException if {@code admin} is not a device owner.
11332      *
11333      * @see #setOverrideApnsEnabled(ComponentName, boolean)
11334      */
getOverrideApns(@onNull ComponentName admin)11335     public List<ApnSetting> getOverrideApns(@NonNull ComponentName admin) {
11336         throwIfParentInstance("getOverrideApns");
11337         if (mService != null) {
11338             try {
11339                 return mService.getOverrideApns(admin);
11340             } catch (RemoteException e) {
11341                 throw e.rethrowFromSystemServer();
11342             }
11343         }
11344         return Collections.emptyList();
11345     }
11346 
11347     /**
11348      * Called by device owner to set if override APNs should be enabled.
11349      * <p> Override APNs are separated from other APNs on the device, and can only be inserted or
11350      * modified by the device owner. When enabled, only override APNs are in use, any other APNs
11351      * are ignored.
11352      *
11353      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11354      * @param enabled {@code true} if override APNs should be enabled, {@code false} otherwise
11355      * @throws SecurityException if {@code admin} is not a device owner.
11356      */
setOverrideApnsEnabled(@onNull ComponentName admin, boolean enabled)11357     public void setOverrideApnsEnabled(@NonNull ComponentName admin, boolean enabled) {
11358         throwIfParentInstance("setOverrideApnEnabled");
11359         if (mService != null) {
11360             try {
11361                 mService.setOverrideApnsEnabled(admin, enabled);
11362             } catch (RemoteException e) {
11363                 throw e.rethrowFromSystemServer();
11364             }
11365         }
11366     }
11367 
11368     /**
11369      * Called by device owner to check if override APNs are currently enabled.
11370      *
11371      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11372      * @return {@code true} if override APNs are currently enabled, {@code false} otherwise.
11373      * @throws SecurityException if {@code admin} is not a device owner.
11374      *
11375      * @see #setOverrideApnsEnabled(ComponentName, boolean)
11376      */
isOverrideApnEnabled(@onNull ComponentName admin)11377     public boolean isOverrideApnEnabled(@NonNull ComponentName admin) {
11378         throwIfParentInstance("isOverrideApnEnabled");
11379         if (mService != null) {
11380             try {
11381                 return mService.isOverrideApnEnabled(admin);
11382             } catch (RemoteException e) {
11383                 throw e.rethrowFromSystemServer();
11384             }
11385         }
11386         return false;
11387     }
11388 
11389     /**
11390      * Returns the data passed from the current administrator to the new administrator during an
11391      * ownership transfer. This is the same {@code bundle} passed in
11392      * {@link #transferOwnership(ComponentName, ComponentName, PersistableBundle)}. The bundle is
11393      * persisted until the profile owner or device owner is removed.
11394      *
11395      * <p>This is the same <code>bundle</code> received in the
11396      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}.
11397      * Use this method to retrieve it after the transfer as long as the new administrator is the
11398      * active device or profile owner.
11399      *
11400      * <p>Returns <code>null</code> if no ownership transfer was started for the calling user.
11401      *
11402      * @see #transferOwnership
11403      * @see DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)
11404      * @throws SecurityException if the caller is not a device or profile owner.
11405      */
11406     @Nullable
getTransferOwnershipBundle()11407     public PersistableBundle getTransferOwnershipBundle() {
11408         throwIfParentInstance("getTransferOwnershipBundle");
11409         try {
11410             return mService.getTransferOwnershipBundle();
11411         } catch (RemoteException re) {
11412             throw re.rethrowFromSystemServer();
11413         }
11414     }
11415 
11416     /**
11417      * Sets the global Private DNS mode to opportunistic.
11418      * May only be called by the device owner.
11419      *
11420      * <p>In this mode, the DNS subsystem will attempt a TLS handshake to the network-supplied
11421      * resolver prior to attempting name resolution in cleartext.
11422      *
11423      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11424      *
11425      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully, or
11426      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set.
11427      *
11428      * @throws SecurityException if the caller is not the device owner.
11429      */
setGlobalPrivateDnsModeOpportunistic( @onNull ComponentName admin)11430     public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeOpportunistic(
11431             @NonNull ComponentName admin) {
11432         throwIfParentInstance("setGlobalPrivateDnsModeOpportunistic");
11433 
11434         if (mService == null) {
11435             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
11436         }
11437 
11438         try {
11439             return mService.setGlobalPrivateDns(admin, PRIVATE_DNS_MODE_OPPORTUNISTIC, null);
11440         } catch (RemoteException re) {
11441             throw re.rethrowFromSystemServer();
11442         }
11443     }
11444 
11445     /**
11446      * Sets the global Private DNS host to be used.
11447      * May only be called by the device owner.
11448      *
11449      * <p>Note that the method is blocking as it will perform a connectivity check to the resolver,
11450      * to ensure it is valid. Because of that, the method should not be called on any thread that
11451      * relates to user interaction, such as the UI thread.
11452      *
11453      * <p>In case a VPN is used in conjunction with Private DNS resolver, the Private DNS resolver
11454      * must be reachable both from within and outside the VPN. Otherwise, the device may lose
11455      * the ability to resolve hostnames as system traffic to the resolver may not go through the
11456      * VPN.
11457      *
11458      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11459      * @param privateDnsHost The hostname of a server that implements DNS over TLS (RFC7858).
11460      *
11461      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully,
11462      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set or
11463      *         {@code PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING} if the specified host does not
11464      *         implement RFC7858.
11465      *
11466      * @throws IllegalArgumentException if the {@code privateDnsHost} is not a valid hostname.
11467      *
11468      * @throws SecurityException if the caller is not the device owner.
11469      */
setGlobalPrivateDnsModeSpecifiedHost( @onNull ComponentName admin, @NonNull String privateDnsHost)11470     @WorkerThread public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeSpecifiedHost(
11471             @NonNull ComponentName admin, @NonNull String privateDnsHost) {
11472         throwIfParentInstance("setGlobalPrivateDnsModeSpecifiedHost");
11473         Objects.requireNonNull(privateDnsHost, "dns resolver is null");
11474 
11475         if (mService == null) {
11476             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
11477         }
11478 
11479         if (NetworkUtils.isWeaklyValidatedHostname(privateDnsHost)) {
11480             if (!PrivateDnsConnectivityChecker.canConnectToPrivateDnsServer(privateDnsHost)) {
11481                 return PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING;
11482             }
11483         }
11484 
11485         try {
11486             return mService.setGlobalPrivateDns(
11487                     admin, PRIVATE_DNS_MODE_PROVIDER_HOSTNAME, privateDnsHost);
11488         } catch (RemoteException re) {
11489             throw re.rethrowFromSystemServer();
11490         }
11491     }
11492 
11493     /**
11494      * Called by device owner or profile owner of an organization-owned managed profile to install
11495      * a system update from the given file. The device will be
11496      * rebooted in order to finish installing the update. Note that if the device is rebooted, this
11497      * doesn't necessarily mean that the update has been applied successfully. The caller should
11498      * additionally check the system version with {@link android.os.Build#FINGERPRINT} or {@link
11499      * android.os.Build.VERSION}. If an error occurs during processing the OTA before the reboot,
11500      * the caller will be notified by {@link InstallSystemUpdateCallback}. If device does not have
11501      * sufficient battery level, the installation will fail with error {@link
11502      * InstallSystemUpdateCallback#UPDATE_ERROR_BATTERY_LOW}.
11503      *
11504      * @param admin The {@link DeviceAdminReceiver} that this request is associated with.
11505      * @param updateFilePath An Uri of the file that contains the update. The file should be
11506      * readable by the calling app.
11507      * @param executor The executor through which the callback should be invoked.
11508      * @param callback A callback object that will inform the caller when installing an update
11509      * fails.
11510      */
installSystemUpdate( @onNull ComponentName admin, @NonNull Uri updateFilePath, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)11511     public void installSystemUpdate(
11512             @NonNull ComponentName admin, @NonNull Uri updateFilePath,
11513             @NonNull @CallbackExecutor Executor executor,
11514             @NonNull InstallSystemUpdateCallback callback) {
11515         throwIfParentInstance("installUpdate");
11516         if (mService == null) {
11517             return;
11518         }
11519         try (ParcelFileDescriptor fileDescriptor = mContext.getContentResolver()
11520                     .openFileDescriptor(updateFilePath, "r")) {
11521             mService.installUpdateFromFile(
11522                     admin, fileDescriptor, new StartInstallingUpdateCallback.Stub() {
11523                         @Override
11524                         public void onStartInstallingUpdateError(
11525                                 int errorCode, String errorMessage) {
11526                             executeCallback(errorCode, errorMessage, executor, callback);
11527                         }
11528                     });
11529         } catch (RemoteException e) {
11530             throw e.rethrowFromSystemServer();
11531         } catch (FileNotFoundException e) {
11532             Log.w(TAG, e);
11533             executeCallback(
11534                     InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
11535                     Log.getStackTraceString(e),
11536                     executor, callback);
11537         } catch (IOException e) {
11538             Log.w(TAG, e);
11539             executeCallback(
11540                     InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN, Log.getStackTraceString(e),
11541                     executor, callback);
11542         }
11543     }
11544 
executeCallback(int errorCode, String errorMessage, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)11545     private void executeCallback(int errorCode, String errorMessage,
11546             @NonNull @CallbackExecutor Executor executor,
11547             @NonNull InstallSystemUpdateCallback callback) {
11548         executor.execute(() -> callback.onInstallUpdateError(errorCode, errorMessage));
11549     }
11550 
11551     /**
11552      * Returns the system-wide Private DNS mode.
11553      *
11554      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11555      * @return one of {@code PRIVATE_DNS_MODE_OFF}, {@code PRIVATE_DNS_MODE_OPPORTUNISTIC},
11556      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} or {@code PRIVATE_DNS_MODE_UNKNOWN}.
11557      * @throws SecurityException if the caller is not the device owner.
11558      */
getGlobalPrivateDnsMode(@onNull ComponentName admin)11559     public int getGlobalPrivateDnsMode(@NonNull ComponentName admin) {
11560         throwIfParentInstance("setGlobalPrivateDns");
11561         if (mService == null) {
11562             return PRIVATE_DNS_MODE_UNKNOWN;
11563         }
11564 
11565         try {
11566             return mService.getGlobalPrivateDnsMode(admin);
11567         } catch (RemoteException re) {
11568             throw re.rethrowFromSystemServer();
11569         }
11570     }
11571 
11572     /**
11573      * Returns the system-wide Private DNS host.
11574      *
11575      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
11576      * @return The hostname used for Private DNS queries, null if none is set.
11577      * @throws SecurityException if the caller is not the device owner.
11578      */
getGlobalPrivateDnsHost(@onNull ComponentName admin)11579     public @Nullable String getGlobalPrivateDnsHost(@NonNull ComponentName admin) {
11580         throwIfParentInstance("setGlobalPrivateDns");
11581         if (mService == null) {
11582             return null;
11583         }
11584 
11585         try {
11586             return mService.getGlobalPrivateDnsHost(admin);
11587         } catch (RemoteException re) {
11588             throw re.rethrowFromSystemServer();
11589         }
11590     }
11591 
11592     /**
11593      * Deprecated. Use {@code markProfileOwnerOnOrganizationOwnedDevice} instead.
11594      * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#Q} or
11595      * below, will behave the same as {@link #markProfileOwnerOnOrganizationOwnedDevice}.
11596      *
11597      * When called by an app targeting SDK level {@link android.os.Build.VERSION_CODES#R}
11598      * or above, will throw an UnsupportedOperationException when called.
11599      *
11600      * @deprecated Use {@link #markProfileOwnerOnOrganizationOwnedDevice} instead.
11601      *
11602      * @hide
11603      */
11604     @Deprecated
11605     @SystemApi
11606     @RequiresPermission(value = android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS,
11607             conditional = true)
setProfileOwnerCanAccessDeviceIds(@onNull ComponentName who)11608     public void setProfileOwnerCanAccessDeviceIds(@NonNull ComponentName who) {
11609         ApplicationInfo ai = mContext.getApplicationInfo();
11610         if (ai.targetSdkVersion > Build.VERSION_CODES.Q) {
11611             throw new UnsupportedOperationException(
11612                     "This method is deprecated. use markProfileOwnerOnOrganizationOwnedDevice"
11613                     + " instead.");
11614         } else {
11615             markProfileOwnerOnOrganizationOwnedDevice(who);
11616         }
11617     }
11618 
11619     /**
11620      * Marks the profile owner of the given user as managing an organization-owned device.
11621      * That will give it access to device identifiers (such as serial number, IMEI and MEID)
11622      * as well as other privileges.
11623      *
11624      * @hide
11625      */
11626     @RequiresPermission(value = android.Manifest.permission.MARK_DEVICE_ORGANIZATION_OWNED,
11627             conditional = true)
markProfileOwnerOnOrganizationOwnedDevice(@onNull ComponentName who)11628     public void markProfileOwnerOnOrganizationOwnedDevice(@NonNull ComponentName who) {
11629         if (mService == null) {
11630             return;
11631         }
11632         try {
11633             mService.markProfileOwnerOnOrganizationOwnedDevice(who, myUserId());
11634         } catch (RemoteException re) {
11635             throw re.rethrowFromSystemServer();
11636         }
11637     }
11638 
11639     /**
11640      * Allows a set of packages to access cross-profile calendar APIs.
11641      *
11642      * <p>Called by a profile owner of a managed profile.
11643      *
11644      * <p>Calling with a {@code null} value for the set disables the restriction so that all
11645      * packages are allowed to access cross-profile calendar APIs. Calling with an empty set
11646      * disallows all packages from accessing cross-profile calendar APIs. If this method isn't
11647      * called, no package is allowed to access cross-profile calendar APIs by default.
11648      *
11649      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11650      * @param packageNames set of packages to be whitelisted
11651      * @throws SecurityException if {@code admin} is not a profile owner
11652      *
11653      * @see #getCrossProfileCalendarPackages(ComponentName)
11654      */
setCrossProfileCalendarPackages(@onNull ComponentName admin, @Nullable Set<String> packageNames)11655     public void setCrossProfileCalendarPackages(@NonNull ComponentName admin,
11656             @Nullable Set<String> packageNames) {
11657         throwIfParentInstance("setCrossProfileCalendarPackages");
11658         if (mService != null) {
11659             try {
11660                 mService.setCrossProfileCalendarPackages(admin, packageNames == null ? null
11661                         : new ArrayList<>(packageNames));
11662             } catch (RemoteException e) {
11663                 throw e.rethrowFromSystemServer();
11664             }
11665         }
11666     }
11667 
11668     /**
11669      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
11670      *
11671      * <p>Called by a profile owner of a managed profile.
11672      *
11673      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11674      * @return the set of names of packages that were previously allowed via
11675      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
11676      * empty set if none have been allowed
11677      * @throws SecurityException if {@code admin} is not a profile owner
11678      *
11679      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
11680      */
getCrossProfileCalendarPackages(@onNull ComponentName admin)11681     public @Nullable Set<String> getCrossProfileCalendarPackages(@NonNull ComponentName admin) {
11682         throwIfParentInstance("getCrossProfileCalendarPackages");
11683         if (mService != null) {
11684             try {
11685                 final List<String> packageNames = mService.getCrossProfileCalendarPackages(admin);
11686                 return packageNames == null ? null : new ArraySet<>(packageNames);
11687             } catch (RemoteException e) {
11688                 throw e.rethrowFromSystemServer();
11689             }
11690         }
11691         return Collections.emptySet();
11692     }
11693 
11694     /**
11695      * Returns if a package is allowed to access cross-profile calendar APIs.
11696      *
11697      * <p>A package is allowed to access cross-profile calendar APIs if it's allowed by
11698      * admins via {@link #setCrossProfileCalendarPackages(ComponentName, Set)} and
11699      * {@link android.provider.Settings.Secure#CROSS_PROFILE_CALENDAR_ENABLED}
11700      * is turned on in the managed profile.
11701      *
11702      * <p>To query for a specific user, use
11703      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
11704      * that user, and get a {@link DevicePolicyManager} from this context.
11705      *
11706      * @param packageName the name of the package
11707      * @return {@code true} if the package is allowed to access cross-profile calendar APIs,
11708      * {@code false} otherwise
11709      *
11710      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
11711      * @see #getCrossProfileCalendarPackages(ComponentName)
11712      * @hide
11713      */
isPackageAllowedToAccessCalendar(@onNull String packageName)11714     public boolean isPackageAllowedToAccessCalendar(@NonNull  String packageName) {
11715         throwIfParentInstance("isPackageAllowedToAccessCalendar");
11716         if (mService != null) {
11717             try {
11718                 return mService.isPackageAllowedToAccessCalendarForUser(packageName,
11719                         myUserId());
11720             } catch (RemoteException e) {
11721                 throw e.rethrowFromSystemServer();
11722             }
11723         }
11724         return false;
11725     }
11726 
11727     /**
11728      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
11729      *
11730      * <p>To query for a specific user, use
11731      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
11732      * that user, and get a {@link DevicePolicyManager} from this context.
11733      *
11734      * @return the set of names of packages that were previously allowed via
11735      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
11736      * empty set if none have been allowed
11737      *
11738      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
11739      * @see #getCrossProfileCalendarPackages(ComponentName)
11740      * @hide
11741      */
getCrossProfileCalendarPackages()11742     public @Nullable Set<String> getCrossProfileCalendarPackages() {
11743         throwIfParentInstance("getCrossProfileCalendarPackages");
11744         if (mService != null) {
11745             try {
11746                 final List<String> packageNames = mService.getCrossProfileCalendarPackagesForUser(
11747                         myUserId());
11748                 return packageNames == null ? null : new ArraySet<>(packageNames);
11749             } catch (RemoteException e) {
11750                 throw e.rethrowFromSystemServer();
11751             }
11752         }
11753         return Collections.emptySet();
11754     }
11755 
11756     /**
11757      * Sets the set of admin-whitelisted package names that are allowed to request user consent for
11758      * cross-profile communication.
11759      *
11760      * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
11761      *
11762      * <p>Previous calls are overridden by each subsequent call to this method.
11763      *
11764      * <p>Note that other apps may be able to request user consent for cross-profile communication
11765      * if they have been explicitly whitelisted by the OEM.
11766      *
11767      * <p>When previously-set cross-profile packages are missing from {@code packageNames}, the
11768      * app-op for {@code INTERACT_ACROSS_PROFILES} will be reset for those packages. This will not
11769      * occur for packages that are whitelisted by the OEM.
11770      *
11771      * @param admin the {@link DeviceAdminReceiver} this request is associated with
11772      * @param packageNames the new cross-profile package names
11773      */
setCrossProfilePackages( @onNull ComponentName admin, @NonNull Set<String> packageNames)11774     public void setCrossProfilePackages(
11775             @NonNull ComponentName admin, @NonNull Set<String> packageNames) {
11776         throwIfParentInstance("setCrossProfilePackages");
11777         if (mService != null) {
11778             try {
11779                 mService.setCrossProfilePackages(admin, new ArrayList<>(packageNames));
11780             } catch (RemoteException e) {
11781                 throw e.rethrowFromSystemServer();
11782             }
11783         }
11784     }
11785 
11786     /**
11787      * Returns the set of package names that the admin has previously set as allowed to request user
11788      * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
11789      * Set)}.
11790      *
11791      * <p>Assumes that the caller is a profile owner and is the given {@code admin}.
11792      *
11793      * <p>Note that other apps not included in the returned set may be able to request user consent
11794      * for cross-profile communication if they have been explicitly whitelisted by the OEM.
11795      *
11796      * @param admin the {@link DeviceAdminReceiver} this request is associated with
11797      * @return the set of package names the admin has previously set as allowed to request user
11798      * consent for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
11799      * Set)}
11800      */
getCrossProfilePackages(@onNull ComponentName admin)11801     public @NonNull Set<String> getCrossProfilePackages(@NonNull ComponentName admin) {
11802         throwIfParentInstance("getCrossProfilePackages");
11803         if (mService != null) {
11804             try {
11805                 return new ArraySet<>(mService.getCrossProfilePackages(admin));
11806             } catch (RemoteException e) {
11807                 throw e.rethrowFromSystemServer();
11808             }
11809         }
11810         return Collections.emptySet();
11811     }
11812 
11813     /**
11814      * Returns the combined set of the following:
11815      * <ul>
11816      * <li>The package names that the admin has previously set as allowed to request user consent
11817      * for cross-profile communication, via {@link #setCrossProfilePackages(ComponentName,
11818      * Set)}.</li>
11819      * <li>The default package names set by the OEM that are allowed to request user consent for
11820      * cross-profile communication without being explicitly enabled by the admin, via {@link
11821      * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array
11822      * #vendor_cross_profile_apps}.</li>
11823      * </ul>
11824      *
11825      * @return the combined set of whitelisted package names set via
11826      * {@link #setCrossProfilePackages(ComponentName, Set)}, {@link com.android.internal.R.array
11827      * #cross_profile_apps}, and {@link com.android.internal.R.array#vendor_cross_profile_apps}.
11828      *
11829      * @hide
11830      */
11831     @RequiresPermission(anyOf = {
11832             permission.INTERACT_ACROSS_USERS_FULL,
11833             permission.INTERACT_ACROSS_USERS,
11834             permission.INTERACT_ACROSS_PROFILES
11835     })
getAllCrossProfilePackages()11836     public @NonNull Set<String> getAllCrossProfilePackages() {
11837         throwIfParentInstance("getAllCrossProfilePackages");
11838         if (mService != null) {
11839             try {
11840                 return new ArraySet<>(mService.getAllCrossProfilePackages());
11841             } catch (RemoteException e) {
11842                 throw e.rethrowFromSystemServer();
11843             }
11844         }
11845         return Collections.emptySet();
11846     }
11847 
11848     /**
11849      * Returns the default package names set by the OEM that are allowed to request user consent for
11850      * cross-profile communication without being explicitly enabled by the admin, via {@link
11851      * com.android.internal.R.array#cross_profile_apps} and {@link com.android.internal.R.array
11852      * #vendor_cross_profile_apps}.
11853      *
11854      * @hide
11855      */
getDefaultCrossProfilePackages()11856     public @NonNull Set<String> getDefaultCrossProfilePackages() {
11857         throwIfParentInstance("getDefaultCrossProfilePackages");
11858         if (mService != null) {
11859             try {
11860                 return new ArraySet<>(mService.getDefaultCrossProfilePackages());
11861             } catch (RemoteException e) {
11862                 throw e.rethrowFromSystemServer();
11863             }
11864         }
11865         return Collections.emptySet();
11866     }
11867 
11868     /**
11869      * Returns whether the device is being used as a managed kiosk. These requirements are as
11870      * follows:
11871      * <ul>
11872      *     <li>The device is in Lock Task (therefore there is also a Device Owner app on the
11873      *     device)</li>
11874      *     <li>The Lock Task feature {@link DevicePolicyManager#LOCK_TASK_FEATURE_SYSTEM_INFO} is
11875      *     not enabled, so the system info in the status bar is not visible</li>
11876      *     <li>The device does not have a secure lock screen (e.g. it has no lock screen or has
11877      *     swipe-to-unlock)</li>
11878      *     <li>The device is not in the middle of an ephemeral user session</li>
11879      * </ul>
11880      *
11881      * <p>Publicly-accessible dedicated devices don't have the same privacy model as
11882      * personally-used devices. In particular, user consent popups don't make sense as a barrier to
11883      * accessing persistent data on these devices since the user giving consent and the user whose
11884      * data is on the device are unlikely to be the same. These consent popups prevent the true
11885      * remote management of these devices.
11886      *
11887      * <p>This condition is not sufficient to cover APIs that would access data that only lives for
11888      * the duration of the user's session, since the user has an expectation of privacy in these
11889      * conditions that more closely resembles use of a personal device. In those cases, see {@link
11890      * #isUnattendedManagedKiosk()}.
11891      *
11892      * @hide
11893      */
11894     @SystemApi
11895     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isManagedKiosk()11896     public boolean isManagedKiosk() {
11897         throwIfParentInstance("isManagedKiosk");
11898         if (mService != null) {
11899             try {
11900                 return mService.isManagedKiosk();
11901             } catch (RemoteException e) {
11902                 throw e.rethrowFromSystemServer();
11903             }
11904         }
11905         return false;
11906     }
11907 
11908     /**
11909      * Returns whether the device is being used as an unattended managed kiosk. These requirements
11910      * are as follows:
11911      * <ul>
11912      *     <li>The device is being used as a managed kiosk, as defined at {@link
11913      *     #isManagedKiosk()}</li>
11914      *     <li>The device has not received user input for at least 30 minutes</li>
11915      * </ul>
11916      *
11917      * <p>See {@link #isManagedKiosk()} for context. This is a stronger requirement that also
11918      * ensures that the device hasn't been interacted with recently, making it an appropriate check
11919      * for privacy-sensitive APIs that wouldn't be appropriate during an active user session.
11920      *
11921      * @hide
11922      */
11923     @SystemApi
11924     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isUnattendedManagedKiosk()11925     public boolean isUnattendedManagedKiosk() {
11926         throwIfParentInstance("isUnattendedManagedKiosk");
11927         if (mService != null) {
11928             try {
11929                 return mService.isUnattendedManagedKiosk();
11930             } catch (RemoteException e) {
11931                 throw e.rethrowFromSystemServer();
11932             }
11933         }
11934         return false;
11935     }
11936 
11937     /**
11938      * Starts an activity to view calendar events in the managed profile.
11939      *
11940      * @param eventId the id of the event to be viewed
11941      * @param start the start time of the event
11942      * @param end the end time of the event
11943      * @param allDay if the event is an all-day event
11944      * @param flags flags to be set for the intent
11945      * @return {@code true} if the activity is started successfully, {@code false} otherwise
11946      *
11947      * @see CalendarContract#startViewCalendarEventInManagedProfile(Context, String, long, long,
11948      * long, boolean, int)
11949      *
11950      * @hide
11951      */
startViewCalendarEventInManagedProfile(long eventId, long start, long end, boolean allDay, int flags)11952     public boolean startViewCalendarEventInManagedProfile(long eventId, long start, long end,
11953             boolean allDay, int flags) {
11954         throwIfParentInstance("startViewCalendarEventInManagedProfile");
11955         if (mService != null) {
11956             try {
11957                 return mService.startViewCalendarEventInManagedProfile(mContext.getPackageName(),
11958                         eventId, start, end, allDay, flags);
11959             } catch (RemoteException e) {
11960                 throw e.rethrowFromSystemServer();
11961             }
11962         }
11963         return false;
11964     }
11965 
11966     /**
11967      * Called by Device owner to disable user control over apps. User will not be able to clear
11968      * app data or force-stop packages.
11969      *
11970      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11971      * @param packages The package names for the apps.
11972      * @throws SecurityException if {@code admin} is not a device owner.
11973      */
setUserControlDisabledPackages(@onNull ComponentName admin, @NonNull List<String> packages)11974     public void setUserControlDisabledPackages(@NonNull ComponentName admin,
11975             @NonNull List<String> packages) {
11976         throwIfParentInstance("setUserControlDisabledPackages");
11977         if (mService != null) {
11978             try {
11979                 mService.setUserControlDisabledPackages(admin, packages);
11980             } catch (RemoteException re) {
11981                 throw re.rethrowFromSystemServer();
11982             }
11983         }
11984     }
11985 
11986     /**
11987      * Returns the list of packages over which user control is disabled by the device owner.
11988      *
11989      * @param admin which {@link DeviceAdminReceiver} this request is associated with
11990      * @throws SecurityException if {@code admin} is not a device owner.
11991      */
getUserControlDisabledPackages(@onNull ComponentName admin)11992     public @NonNull List<String> getUserControlDisabledPackages(@NonNull ComponentName admin) {
11993         throwIfParentInstance("getUserControlDisabledPackages");
11994         if (mService != null) {
11995             try {
11996                 return mService.getUserControlDisabledPackages(admin);
11997             } catch (RemoteException re) {
11998                 throw re.rethrowFromSystemServer();
11999             }
12000         }
12001         return Collections.emptyList();
12002     }
12003 
12004     /**
12005      * Called by device owner or profile owner of an organization-owned managed profile to toggle
12006      * Common Criteria mode for the device. When the device is in Common Criteria mode,
12007      * certain device functionalities are tuned to meet the higher
12008      * security level required by Common Criteria certification. For example:
12009      * <ul>
12010      * <li> Bluetooth long term key material is additionally integrity-protected with AES-GCM. </li>
12011      * <li> WiFi configuration store is additionally integrity-protected with AES-GCM. </li>
12012      * </ul>
12013      * Common Criteria mode is disabled by default.
12014      *
12015      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
12016      * @param enabled whether Common Criteria mode should be enabled or not.
12017      */
setCommonCriteriaModeEnabled(@onNull ComponentName admin, boolean enabled)12018     public void setCommonCriteriaModeEnabled(@NonNull ComponentName admin, boolean enabled) {
12019         throwIfParentInstance("setCommonCriteriaModeEnabled");
12020         if (mService != null) {
12021             try {
12022                 mService.setCommonCriteriaModeEnabled(admin, enabled);
12023             } catch (RemoteException e) {
12024                 throw e.rethrowFromSystemServer();
12025             }
12026         }
12027     }
12028 
12029     /**
12030      * Returns whether Common Criteria mode is currently enabled. Device owner and profile owner of
12031      * an organization-owned managed profile can query its own Common Criteria mode setting by
12032      * calling this method with its admin {@link ComponentName}. Any caller can obtain the
12033      * aggregated device-wide Common Criteria mode state by passing {@code null} as the
12034      * {@code admin} argument.
12035      *
12036      * @param admin which {@link DeviceAdminReceiver} this request is associated with, or
12037      *     {@code null} if the caller is not a device admin.
12038      * @return {@code true} if Common Criteria mode is enabled, {@code false} otherwise.
12039      */
isCommonCriteriaModeEnabled(@ullable ComponentName admin)12040     public boolean isCommonCriteriaModeEnabled(@Nullable ComponentName admin) {
12041         throwIfParentInstance("isCommonCriteriaModeEnabled");
12042         if (mService != null) {
12043             try {
12044                 return mService.isCommonCriteriaModeEnabled(admin);
12045             } catch (RemoteException e) {
12046                 throw e.rethrowFromSystemServer();
12047             }
12048         }
12049         return false;
12050     }
12051 
12052     /**
12053      * Called by profile owner of an organization-owned managed profile to check whether
12054      * personal apps are suspended.
12055      *
12056      * @return a bitmask of reasons for personal apps suspension or
12057      *     {@link #PERSONAL_APPS_NOT_SUSPENDED} if apps are not suspended.
12058      * @see #setPersonalAppsSuspended
12059      */
getPersonalAppsSuspendedReasons( @onNull ComponentName admin)12060     public @PersonalAppsSuspensionReason int getPersonalAppsSuspendedReasons(
12061             @NonNull ComponentName admin) {
12062         throwIfParentInstance("getPersonalAppsSuspendedReasons");
12063         if (mService != null) {
12064             try {
12065                 return mService.getPersonalAppsSuspendedReasons(admin);
12066             } catch (RemoteException re) {
12067                 throw re.rethrowFromSystemServer();
12068             }
12069         }
12070         return 0;
12071     }
12072 
12073     /**
12074      * Called by a profile owner of an organization-owned managed profile to suspend personal
12075      * apps on the device. When personal apps are suspended the device can only be used for calls.
12076      *
12077      * <p>When personal apps are suspended, an ongoing notification about that is shown to the user.
12078      * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE}
12079      * in the profile owner package. Profile owner implementation that uses personal apps suspension
12080      * must handle this intent.
12081      *
12082      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
12083      * @param suspended Whether personal apps should be suspended.
12084      * @throws IllegalStateException if the profile owner doesn't have an activity that handles
12085      *        {@link #ACTION_CHECK_POLICY_COMPLIANCE}
12086      */
setPersonalAppsSuspended(@onNull ComponentName admin, boolean suspended)12087     public void setPersonalAppsSuspended(@NonNull ComponentName admin, boolean suspended) {
12088         throwIfParentInstance("setPersonalAppsSuspended");
12089         if (mService != null) {
12090             try {
12091                 mService.setPersonalAppsSuspended(admin, suspended);
12092             } catch (RemoteException re) {
12093                 throw re.rethrowFromSystemServer();
12094             }
12095         }
12096     }
12097 
12098     /**
12099      * Called by a profile owner of an organization-owned managed profile to set maximum time
12100      * the profile is allowed to be turned off. If the profile is turned off for longer, personal
12101      * apps are suspended on the device.
12102      *
12103      * <p>When personal apps are suspended, an ongoing notification about that is shown to the user.
12104      * When the user taps the notification, system invokes {@link #ACTION_CHECK_POLICY_COMPLIANCE}
12105      * in the profile owner package. Profile owner implementation that uses personal apps suspension
12106      * must handle this intent.
12107      *
12108      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
12109      * @param timeoutMillis Maximum time the profile is allowed to be off in milliseconds or 0 if
12110      *        not limited. The minimum non-zero value corresponds to 72 hours. If an admin sets a
12111      *        smaller non-zero vaulue, 72 hours will be set instead.
12112      * @throws IllegalStateException if the profile owner doesn't have an activity that handles
12113      *        {@link #ACTION_CHECK_POLICY_COMPLIANCE}
12114      * @see #setPersonalAppsSuspended
12115      */
setManagedProfileMaximumTimeOff(@onNull ComponentName admin, long timeoutMillis)12116     public void setManagedProfileMaximumTimeOff(@NonNull ComponentName admin, long timeoutMillis) {
12117         throwIfParentInstance("setManagedProfileMaximumTimeOff");
12118         if (mService != null) {
12119             try {
12120                 mService.setManagedProfileMaximumTimeOff(admin, timeoutMillis);
12121             } catch (RemoteException re) {
12122                 throw re.rethrowFromSystemServer();
12123             }
12124         }
12125     }
12126 
12127      /**
12128      * Called by a profile owner of an organization-owned managed profile to get maximum time
12129      * the profile is allowed to be turned off.
12130      *
12131      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
12132      * @return Maximum time the profile is allowed to be off in milliseconds or 0 if not limited.
12133      * @see #setPersonalAppsSuspended
12134      */
getManagedProfileMaximumTimeOff(@onNull ComponentName admin)12135     public long getManagedProfileMaximumTimeOff(@NonNull ComponentName admin) {
12136         throwIfParentInstance("getManagedProfileMaximumTimeOff");
12137         if (mService != null) {
12138             try {
12139                 return mService.getManagedProfileMaximumTimeOff(admin);
12140             } catch (RemoteException re) {
12141                 throw re.rethrowFromSystemServer();
12142             }
12143         }
12144         return 0;
12145     }
12146 
12147     /**
12148      * Returns {@code true} when {@code userId} has a profile owner that is capable of resetting
12149      * password in RUNNING_LOCKED state. For that it should have at least one direct boot aware
12150      * component and have an active password reset token. Can only be called by the system.
12151      * @hide
12152      */
canProfileOwnerResetPasswordWhenLocked(int userId)12153     public boolean canProfileOwnerResetPasswordWhenLocked(int userId) {
12154         if (mService != null) {
12155             try {
12156                 return mService.canProfileOwnerResetPasswordWhenLocked(userId);
12157             } catch (RemoteException re) {
12158                 throw re.rethrowFromSystemServer();
12159             }
12160         }
12161         return false;
12162     }
12163 }
12164