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.UserIdInt;
37 import android.annotation.WorkerThread;
38 import android.app.Activity;
39 import android.app.IServiceConnection;
40 import android.app.KeyguardManager;
41 import android.app.admin.SecurityLog.SecurityEvent;
42 import android.compat.annotation.UnsupportedAppUsage;
43 import android.content.ComponentName;
44 import android.content.Context;
45 import android.content.Intent;
46 import android.content.IntentFilter;
47 import android.content.ServiceConnection;
48 import android.content.pm.ApplicationInfo;
49 import android.content.pm.IPackageDataObserver;
50 import android.content.pm.PackageManager;
51 import android.content.pm.PackageManager.NameNotFoundException;
52 import android.content.pm.ParceledListSlice;
53 import android.content.pm.UserInfo;
54 import android.graphics.Bitmap;
55 import android.net.NetworkUtils;
56 import android.net.PrivateDnsConnectivityChecker;
57 import android.net.ProxyInfo;
58 import android.net.Uri;
59 import android.os.Build;
60 import android.os.Bundle;
61 import android.os.ParcelFileDescriptor;
62 import android.os.Parcelable;
63 import android.os.PersistableBundle;
64 import android.os.Process;
65 import android.os.RemoteCallback;
66 import android.os.RemoteException;
67 import android.os.ServiceSpecificException;
68 import android.os.UserHandle;
69 import android.os.UserManager;
70 import android.os.UserManager.UserOperationException;
71 import android.os.UserManager.UserOperationResult;
72 import android.provider.CalendarContract;
73 import android.provider.ContactsContract.Directory;
74 import android.provider.Settings;
75 import android.security.AttestedKeyPair;
76 import android.security.Credentials;
77 import android.security.KeyChain;
78 import android.security.KeyChainException;
79 import android.security.keymaster.KeymasterCertificateChain;
80 import android.security.keystore.AttestationUtils;
81 import android.security.keystore.KeyAttestationException;
82 import android.security.keystore.KeyGenParameterSpec;
83 import android.security.keystore.ParcelableKeyGenParameterSpec;
84 import android.security.keystore.StrongBoxUnavailableException;
85 import android.service.restrictions.RestrictionsReceiver;
86 import android.telephony.TelephonyManager;
87 import android.telephony.data.ApnSetting;
88 import android.util.ArraySet;
89 import android.util.Log;
90 
91 import com.android.internal.R;
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.Set;
120 import java.util.concurrent.CompletableFuture;
121 import java.util.concurrent.ExecutionException;
122 import java.util.concurrent.Executor;
123 
124 /**
125  * Public interface for managing policies enforced on a device. Most clients of this class must be
126  * registered with the system as a <a href="{@docRoot}guide/topics/admin/device-admin.html">device
127  * administrator</a>. Additionally, a device administrator may be registered as either a profile or
128  * device owner. A given method is accessible to all device administrators unless the documentation
129  * for that method specifies that it is restricted to either device or profile owners. Any
130  * application calling an api may only pass as an argument a device administrator component it
131  * owns. Otherwise, a {@link SecurityException} will be thrown.
132  * <div class="special reference">
133  * <h3>Developer Guides</h3>
134  * <p>
135  * For more information about managing policies for device administration, read the <a href=
136  * "{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a> developer
137  * guide. </div>
138  */
139 @SystemService(Context.DEVICE_POLICY_SERVICE)
140 @RequiresFeature(PackageManager.FEATURE_DEVICE_ADMIN)
141 public class DevicePolicyManager {
142 
143     private static String TAG = "DevicePolicyManager";
144 
145     private final Context mContext;
146     private final IDevicePolicyManager mService;
147     private final boolean mParentInstance;
148 
149     /** @hide */
DevicePolicyManager(Context context, IDevicePolicyManager service)150     public DevicePolicyManager(Context context, IDevicePolicyManager service) {
151         this(context, service, false);
152     }
153 
154     /** @hide */
155     @VisibleForTesting
DevicePolicyManager(Context context, IDevicePolicyManager service, boolean parentInstance)156     protected DevicePolicyManager(Context context, IDevicePolicyManager service,
157             boolean parentInstance) {
158         mContext = context;
159         mService = service;
160         mParentInstance = parentInstance;
161     }
162 
163     /** @hide test will override it. */
164     @VisibleForTesting
myUserId()165     protected int myUserId() {
166         return mContext.getUserId();
167     }
168 
169     /**
170      * Activity action: Starts the provisioning flow which sets up a managed profile.
171      *
172      * <p>A managed profile allows data separation for example for the usage of a
173      * device as a personal and corporate device. The user which provisioning is started from and
174      * the managed profile share a launcher.
175      *
176      * <p>This intent will typically be sent by a mobile device management application (MDM).
177      * Provisioning adds a managed profile and sets the MDM as the profile owner who has full
178      * control over the profile.
179      *
180      * <p>It is possible to check if provisioning is allowed or not by querying the method
181      * {@link #isProvisioningAllowed(String)}.
182      *
183      * <p>In version {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this intent must contain the
184      * extra {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}.
185      * As of {@link android.os.Build.VERSION_CODES#M}, it should contain the extra
186      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead, although specifying only
187      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported.
188      *
189      * <p>The intent may also contain the following extras:
190      * <ul>
191      * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, optional </li>
192      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional, supported from
193      * {@link android.os.Build.VERSION_CODES#N}</li>
194      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
195      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
196      * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
197      * <li>{@link #EXTRA_PROVISIONING_SKIP_USER_CONSENT}, optional</li>
198      * <li>{@link #EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION}, optional</li>
199      * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
200      * </ul>
201      *
202      * <p>When managed provisioning has completed, broadcasts are sent to the application specified
203      * in the provisioning intent. The
204      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast is sent in the
205      * managed profile and the {@link #ACTION_MANAGED_PROFILE_PROVISIONED} broadcast is sent in
206      * the primary profile.
207      *
208      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when managed provisioning has
209      * completed, along with the above broadcast, activity intent
210      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the profile owner.
211      *
212      * <p>If provisioning fails, the managedProfile is removed so the device returns to its
213      * previous state.
214      *
215      * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
216      * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
217      * the provisioning flow was successful, although this doesn't guarantee the full flow will
218      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
219      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
220      */
221     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
222     public static final String ACTION_PROVISION_MANAGED_PROFILE
223         = "android.app.action.PROVISION_MANAGED_PROFILE";
224 
225     /**
226      * Activity action: Starts the provisioning flow which sets up a managed user.
227      *
228      * <p>This intent will typically be sent by a mobile device management application (MDM).
229      * Provisioning configures the user as managed user and sets the MDM as the profile
230      * owner who has full control over the user. Provisioning can only happen before user setup has
231      * been completed. Use {@link #isProvisioningAllowed(String)} to check if provisioning is
232      * allowed.
233      *
234      * <p>The intent contains the following extras:
235      * <ul>
236      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
237      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
238      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
239      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
240      * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
241      * </ul>
242      *
243      * <p>If provisioning fails, the device returns to its previous state.
244      *
245      * <p>If launched with {@link android.app.Activity#startActivityForResult(Intent, int)} a
246      * result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part of
247      * the provisioning flow was successful, although this doesn't guarantee the full flow will
248      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
249      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
250      *
251      * @hide
252      */
253     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
254     public static final String ACTION_PROVISION_MANAGED_USER
255         = "android.app.action.PROVISION_MANAGED_USER";
256 
257     /**
258      * Activity action: Starts the provisioning flow which sets up a managed device.
259      * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
260      *
261      * <p> During device owner provisioning a device admin app is set as the owner of the device.
262      * A device owner has full control over the device. The device owner can not be modified by the
263      * user.
264      *
265      * <p> A typical use case would be a device that is owned by a company, but used by either an
266      * employee or client.
267      *
268      * <p> An intent with this action can be sent only on an unprovisioned device.
269      * It is possible to check if provisioning is allowed or not by querying the method
270      * {@link #isProvisioningAllowed(String)}.
271      *
272      * <p>The intent contains the following extras:
273      * <ul>
274      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
275      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
276      * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
277      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
278      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
279      * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
280      * <li>{@link #EXTRA_PROVISIONING_DISCLAIMERS}, optional</li>
281      * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional</li>
282      * </ul>
283      *
284      * <p>When device owner provisioning has completed, an intent of the type
285      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
286      * device owner.
287      *
288      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
289      * completed, along with the above broadcast, activity intent
290      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
291      *
292      * <p>If provisioning fails, the device is factory reset.
293      *
294      * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
295      * of the provisioning flow was successful, although this doesn't guarantee the full flow will
296      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
297      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
298      */
299     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
300     public static final String ACTION_PROVISION_MANAGED_DEVICE
301         = "android.app.action.PROVISION_MANAGED_DEVICE";
302 
303     /**
304      * Activity action: launch when user provisioning completed, i.e.
305      * {@link #getUserProvisioningState()} returns one of the complete state.
306      *
307      * <p> Please note that the API behavior is not necessarily consistent across various releases,
308      * and devices, as it's contract between SetupWizard and ManagedProvisioning. The default
309      * implementation is that ManagedProvisioning launches SetupWizard in NFC provisioning only.
310      *
311      * <p> The activity must be protected by permission
312      * {@link android.Manifest.permission#BIND_DEVICE_ADMIN}, and the process must hold
313      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE} to be launched.
314      * Only one {@link ComponentName} in the entire system should be enabled, and the rest of the
315      * components are not started by this intent.
316      * @hide
317      */
318     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
319     @SystemApi
320     public static final String ACTION_STATE_USER_SETUP_COMPLETE =
321             "android.app.action.STATE_USER_SETUP_COMPLETE";
322 
323     /**
324      * Activity action: Starts the provisioning flow which sets up a managed device.
325      *
326      * <p>During device owner provisioning, a device admin app is downloaded and set as the owner of
327      * the device. A device owner has full control over the device. The device owner can not be
328      * modified by the user and the only way of resetting the device is via factory reset.
329      *
330      * <p>From version {@link android.os.Build.VERSION_CODES#Q}, the admin app can choose
331      * whether to set up a fully managed device or a work profile. For the admin app to support
332      * this, it must have an activity with intent filter {@link #ACTION_GET_PROVISIONING_MODE} and
333      * another one with intent filter {@link #ACTION_ADMIN_POLICY_COMPLIANCE}. For example:
334      * <pre>
335      * &lt;activity
336      *     android:name=".GetProvisioningModeActivity"
337      *     android:label="@string/app_name"
338      *     android:permission="android.permission.BIND_DEVICE_ADMIN"&gt;
339      *     &lt;intent-filter&gt;
340      *         &lt;action
341      *             android:name="android.app.action.GET_PROVISIONING_MODE" /&gt;
342      *         &lt;category android:name="android.intent.category.DEFAULT" /&gt;
343      *     &lt;/intent-filter&gt;
344      * &lt;/activity&gt;
345      *
346      * &lt;activity
347      *     android:name=".PolicyComplianceActivity"
348      *     android:label="@string/app_name"
349      *     android:permission="android.permission.BIND_DEVICE_ADMIN"&gt;
350      *     &lt;intent-filter&gt;
351      *         &lt;action
352      *             android:name="android.app.action.ADMIN_POLICY_COMPLIANCE" /&gt;
353      *         &lt;category android:name="android.intent.category.DEFAULT" /&gt;
354      *     &lt;/intent-filter&gt;
355      * &lt;/activity&gt;</pre>
356      *
357      * <p>A typical use case would be a device that is owned by a company, but used by either an
358      * employee or client.
359      *
360      * <p>The provisioning message should be sent to an unprovisioned device.
361      *
362      * <p>Unlike {@link #ACTION_PROVISION_MANAGED_DEVICE}, the provisioning message can only be sent
363      * by a privileged app with the permission
364      * {@link android.Manifest.permission#DISPATCH_PROVISIONING_MESSAGE}.
365      *
366      * <p>The provisioning intent contains the following properties:
367      * <ul>
368      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
369      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
370      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
371      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
372      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL}, optional</li>
373      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI}, optional</li>
374      * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
375      * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
376      * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
377      * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
378      * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
379      * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
380      * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
381      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
382      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
383      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
384      * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
385      * <li>{@link #EXTRA_PROVISIONING_SUPPORT_URL}, optional</li>
386      * <li>{@link #EXTRA_PROVISIONING_ORGANIZATION_NAME}, optional</li>
387      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
388      * <li>{@link #EXTRA_PROVISIONING_USE_MOBILE_DATA}, optional </li>
389      * <li>{@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS}, optional - when not used for
390      * cloud enrollment, NFC or QR provisioning</li>
391      * </ul>
392      *
393      * @hide
394      */
395     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
396     @SystemApi
397     public static final String ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE =
398             "android.app.action.PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE";
399 
400     /**
401      * Activity action: Starts the provisioning flow which sets up a managed device.
402      * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}.
403      *
404      * <p>NOTE: This is only supported on split system user devices, and puts the device into a
405      * management state that is distinct from that reached by
406      * {@link #ACTION_PROVISION_MANAGED_DEVICE} - specifically the device owner runs on the system
407      * user, and only has control over device-wide policies, not individual users and their data.
408      * The primary benefit is that multiple non-system users are supported when provisioning using
409      * this form of device management.
410      *
411      * <p>During device owner provisioning a device admin app is set as the owner of the device.
412      * A device owner has full control over the device. The device owner can not be modified by the
413      * user.
414      *
415      * <p>A typical use case would be a device that is owned by a company, but used by either an
416      * employee or client.
417      *
418      * <p>An intent with this action can be sent only on an unprovisioned device.
419      * It is possible to check if provisioning is allowed or not by querying the method
420      * {@link #isProvisioningAllowed(String)}.
421      *
422      * <p>The intent contains the following extras:
423      * <ul>
424      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li>
425      * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li>
426      * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li>
427      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional</li>
428      * <li>{@link #EXTRA_PROVISIONING_LOGO_URI}, optional</li>
429      * <li>{@link #EXTRA_PROVISIONING_MAIN_COLOR}, optional</li>
430      * </ul>
431      *
432      * <p>When device owner provisioning has completed, an intent of the type
433      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the
434      * device owner.
435      *
436      * <p>From version {@link android.os.Build.VERSION_CODES#O}, when device owner provisioning has
437      * completed, along with the above broadcast, activity intent
438      * {@link #ACTION_PROVISIONING_SUCCESSFUL} will also be sent to the device owner.
439      *
440      * <p>If provisioning fails, the device is factory reset.
441      *
442      * <p>A result code of {@link android.app.Activity#RESULT_OK} implies that the synchronous part
443      * of the provisioning flow was successful, although this doesn't guarantee the full flow will
444      * succeed. Conversely a result code of {@link android.app.Activity#RESULT_CANCELED} implies
445      * that the user backed-out of provisioning, or some precondition for provisioning wasn't met.
446      *
447      * @hide
448      */
449     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
450     public static final String ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE
451         = "android.app.action.PROVISION_MANAGED_SHAREABLE_DEVICE";
452 
453     /**
454      * Activity action: Finalizes management provisioning, should be used after user-setup
455      * has been completed and {@link #getUserProvisioningState()} returns one of:
456      * <ul>
457      * <li>{@link #STATE_USER_SETUP_INCOMPLETE}</li>
458      * <li>{@link #STATE_USER_SETUP_COMPLETE}</li>
459      * <li>{@link #STATE_USER_PROFILE_COMPLETE}</li>
460      * </ul>
461      *
462      * @hide
463      */
464     @SystemApi
465     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
466     public static final String ACTION_PROVISION_FINALIZATION
467             = "android.app.action.PROVISION_FINALIZATION";
468 
469     /**
470      * Action: Bugreport sharing with device owner has been accepted by the user.
471      *
472      * @hide
473      */
474     public static final String ACTION_BUGREPORT_SHARING_ACCEPTED =
475             "com.android.server.action.REMOTE_BUGREPORT_SHARING_ACCEPTED";
476 
477     /**
478      * Action: Bugreport sharing with device owner has been declined by the user.
479      *
480      * @hide
481      */
482     public static final String ACTION_BUGREPORT_SHARING_DECLINED =
483             "com.android.server.action.REMOTE_BUGREPORT_SHARING_DECLINED";
484 
485     /**
486      * Action: Bugreport has been collected and is dispatched to {@code DevicePolicyManagerService}.
487      *
488      * @hide
489      */
490     public static final String ACTION_REMOTE_BUGREPORT_DISPATCH =
491             "android.intent.action.REMOTE_BUGREPORT_DISPATCH";
492 
493     /**
494      * Extra for shared bugreport's SHA-256 hash.
495      *
496      * @hide
497      */
498     public static final String EXTRA_REMOTE_BUGREPORT_HASH =
499             "android.intent.extra.REMOTE_BUGREPORT_HASH";
500 
501     /**
502      * Extra for remote bugreport notification shown type.
503      *
504      * @hide
505      */
506     public static final String EXTRA_BUGREPORT_NOTIFICATION_TYPE =
507             "android.app.extra.bugreport_notification_type";
508 
509     /**
510      * Notification type for a started remote bugreport flow.
511      *
512      * @hide
513      */
514     public static final int NOTIFICATION_BUGREPORT_STARTED = 1;
515 
516     /**
517      * Notification type for a bugreport that has already been accepted to be shared, but is still
518      * being taken.
519      *
520      * @hide
521      */
522     public static final int NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED = 2;
523 
524     /**
525      * Notification type for a bugreport that has been taken and can be shared or declined.
526      *
527      * @hide
528      */
529     public static final int NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED = 3;
530 
531     /**
532      * Default and maximum timeout in milliseconds after which unlocking with weak auth times out,
533      * i.e. the user has to use a strong authentication method like password, PIN or pattern.
534      *
535      * @hide
536      */
537     public static final long DEFAULT_STRONG_AUTH_TIMEOUT_MS = 72 * 60 * 60 * 1000; // 72h
538 
539     /**
540      * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that
541      * allows a mobile device management application or NFC programmer application which starts
542      * managed provisioning to pass data to the management application instance after provisioning.
543      * <p>
544      * If used with {@link #ACTION_PROVISION_MANAGED_PROFILE} it can be used by the application that
545      * sends the intent to pass data to itself on the newly created profile.
546      * If used with {@link #ACTION_PROVISION_MANAGED_DEVICE} it allows passing data to the same
547      * instance of the app on the primary user.
548      * Starting from {@link android.os.Build.VERSION_CODES#M}, if used with
549      * {@link #MIME_TYPE_PROVISIONING_NFC} as part of NFC managed device provisioning, the NFC
550      * message should contain a stringified {@link java.util.Properties} instance, whose string
551      * properties will be converted into a {@link android.os.PersistableBundle} and passed to the
552      * management application after provisioning.
553      *
554      * <p>
555      * In both cases the application receives the data in
556      * {@link DeviceAdminReceiver#onProfileProvisioningComplete} via an intent with the action
557      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE}. The bundle is not changed
558      * during the managed provisioning.
559      */
560     public static final String EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE =
561             "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE";
562 
563     /**
564      * A String extra holding the package name of the mobile device management application that
565      * will be set as the profile owner or device owner.
566      *
567      * <p>If an application starts provisioning directly via an intent with action
568      * {@link #ACTION_PROVISION_MANAGED_PROFILE} this package has to match the package name of the
569      * application that started provisioning. The package will be set as profile owner in that case.
570      *
571      * <p>This package is set as device owner when device owner provisioning is started by an NFC
572      * message containing an NFC record with MIME type {@link #MIME_TYPE_PROVISIONING_NFC}.
573      *
574      * <p> When this extra is set, the application must have exactly one device admin receiver.
575      * This receiver will be set as the profile or device owner and active admin.
576      *
577      * @see DeviceAdminReceiver
578      * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}. This extra is still
579      * supported, but only if there is only one device admin receiver in the package that requires
580      * the permission {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
581      */
582     @Deprecated
583     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME
584         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME";
585 
586     /**
587      * A ComponentName extra indicating the device admin receiver of the mobile device management
588      * application that will be set as the profile owner or device owner and active admin.
589      *
590      * <p>If an application starts provisioning directly via an intent with action
591      * {@link #ACTION_PROVISION_MANAGED_PROFILE} or
592      * {@link #ACTION_PROVISION_MANAGED_DEVICE} the package name of this
593      * component has to match the package name of the application that started provisioning.
594      *
595      * <p>This component is set as device owner and active admin when device owner provisioning is
596      * started by an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or by an NFC
597      * message containing an NFC record with MIME type
598      * {@link #MIME_TYPE_PROVISIONING_NFC}. For the NFC record, the component name must be
599      * flattened to a string, via {@link ComponentName#flattenToShortString()}.
600      *
601      * @see DeviceAdminReceiver
602      */
603     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME
604         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME";
605 
606     /**
607      * An {@link android.accounts.Account} extra holding the account to migrate during managed
608      * profile provisioning. If the account supplied is present in the primary user, it will be
609      * copied, along with its credentials to the managed profile and removed from the primary user.
610      *
611      * Use with {@link #ACTION_PROVISION_MANAGED_PROFILE}.
612      */
613 
614     public static final String EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE
615         = "android.app.extra.PROVISIONING_ACCOUNT_TO_MIGRATE";
616 
617     /**
618      * Boolean extra to indicate that the migrated account should be kept. This is used in
619      * conjunction with {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}. If it's set to {@code true},
620      * the account will not be removed from the primary user after it is migrated to the newly
621      * created user or profile.
622      *
623      * <p> Defaults to {@code false}
624      *
625      * <p> Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} and
626      * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}
627      */
628     public static final String EXTRA_PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION
629             = "android.app.extra.PROVISIONING_KEEP_ACCOUNT_ON_MIGRATION";
630 
631     /**
632      * @deprecated From {@link android.os.Build.VERSION_CODES#O}, never used while provisioning the
633      * device.
634      */
635     @Deprecated
636     public static final String EXTRA_PROVISIONING_EMAIL_ADDRESS
637         = "android.app.extra.PROVISIONING_EMAIL_ADDRESS";
638 
639     /**
640      * A integer extra indicating the predominant color to show during the provisioning.
641      * Refer to {@link android.graphics.Color} for how the color is represented.
642      *
643      * <p>Use with {@link #ACTION_PROVISION_MANAGED_PROFILE} or
644      * {@link #ACTION_PROVISION_MANAGED_DEVICE}.
645      */
646     public static final String EXTRA_PROVISIONING_MAIN_COLOR =
647              "android.app.extra.PROVISIONING_MAIN_COLOR";
648 
649     /**
650      * A Boolean extra that can be used by the mobile device management application to skip the
651      * disabling of system apps during provisioning when set to {@code true}.
652      *
653      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
654      * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
655      */
656     public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED =
657             "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED";
658 
659     /**
660      * A String extra holding the time zone {@link android.app.AlarmManager} that the device
661      * will be set to.
662      *
663      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
664      * provisioning via an NFC bump.
665      */
666     public static final String EXTRA_PROVISIONING_TIME_ZONE
667         = "android.app.extra.PROVISIONING_TIME_ZONE";
668 
669     /**
670      * A Long extra holding the wall clock time (in milliseconds) to be set on the device's
671      * {@link android.app.AlarmManager}.
672      *
673      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
674      * provisioning via an NFC bump.
675      */
676     public static final String EXTRA_PROVISIONING_LOCAL_TIME
677         = "android.app.extra.PROVISIONING_LOCAL_TIME";
678 
679     /**
680      * A String extra holding the {@link java.util.Locale} that the device will be set to.
681      * Format: xx_yy, where xx is the language code, and yy the country code.
682      *
683      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
684      * provisioning via an NFC bump.
685      */
686     public static final String EXTRA_PROVISIONING_LOCALE
687         = "android.app.extra.PROVISIONING_LOCALE";
688 
689     /**
690      * A String extra holding the ssid of the wifi network that should be used during nfc device
691      * owner provisioning for downloading the mobile device management application.
692      *
693      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
694      * provisioning via an NFC bump.
695      */
696     public static final String EXTRA_PROVISIONING_WIFI_SSID
697         = "android.app.extra.PROVISIONING_WIFI_SSID";
698 
699     /**
700      * A boolean extra indicating whether the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
701      * is hidden or not.
702      *
703      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
704      * provisioning via an NFC bump.
705      */
706     public static final String EXTRA_PROVISIONING_WIFI_HIDDEN
707         = "android.app.extra.PROVISIONING_WIFI_HIDDEN";
708 
709     /**
710      * A String extra indicating the security type of the wifi network in
711      * {@link #EXTRA_PROVISIONING_WIFI_SSID} and could be one of {@code NONE}, {@code WPA},
712      * {@code WEP} or {@code EAP}.
713      *
714      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
715      * provisioning via an NFC bump.
716      */
717     public static final String EXTRA_PROVISIONING_WIFI_SECURITY_TYPE
718         = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE";
719 
720     /**
721      * A String extra holding the password of the wifi network in
722      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
723      *
724      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
725      * provisioning via an NFC bump.
726      */
727     public static final String EXTRA_PROVISIONING_WIFI_PASSWORD =
728             "android.app.extra.PROVISIONING_WIFI_PASSWORD";
729 
730     /**
731      * The EAP method of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
732      * and could be one of {@code PEAP}, {@code TLS}, {@code TTLS}, {@code PWD}, {@code SIM},
733      * {@code AKA} or {@code AKA_PRIME}. This is only used if the
734      * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
735      *
736      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
737      * provisioning via an NFC bump. It can also be used for QR code provisioning.
738      */
739     public static final String EXTRA_PROVISIONING_WIFI_EAP_METHOD =
740             "android.app.extra.PROVISIONING_WIFI_EAP_METHOD";
741 
742     /**
743      * The phase 2 authentication of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}
744      * and could be one of {@code NONE}, {@code PAP}, {@code MSCHAP}, {@code MSCHAPV2}, {@code GTC},
745      * {@code SIM}, {@code AKA} or {@code AKA_PRIME}. This is only used if the
746      * {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
747      *
748      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
749      * provisioning via an NFC bump. It can also be used for QR code provisioning.
750      */
751     public static final String EXTRA_PROVISIONING_WIFI_PHASE2_AUTH =
752             "android.app.extra.PROVISIONING_WIFI_PHASE2_AUTH";
753 
754     /**
755      * The CA certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This should
756      * be an X.509 certificate Base64 encoded DER format, ie. PEM representation of a certificate
757      * without header, footer and line breaks. <a href=
758      * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only
759      * used if the {@link
760      * #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
761      *
762      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
763      * provisioning via an NFC bump. It can also be used for QR code provisioning.
764      */
765     public static final String EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE =
766             "android.app.extra.PROVISIONING_WIFI_CA_CERTIFICATE";
767 
768     /**
769      * The user certificate of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This
770      * should be an X.509 certificate and private key Base64 encoded DER format, ie. PEM
771      * representation of a certificate and key without header, footer and line breaks. <a href=
772      * "https://tools.ietf.org/html/rfc7468"> More information</a> This is only
773      * used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
774      *
775      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
776      * provisioning via an NFC bump. It can also be used for QR code provisioning.
777      */
778     public static final String EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE =
779             "android.app.extra.PROVISIONING_WIFI_USER_CERTIFICATE";
780 
781     /**
782      * The identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used
783      * if the {@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_IDENTITY =
789             "android.app.extra.PROVISIONING_WIFI_IDENTITY";
790 
791     /**
792      * The anonymous identity of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is
793      * only used if the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
794      *
795      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
796      * provisioning via an NFC bump. It can also be used for QR code provisioning.
797      */
798 
799     public static final String EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY =
800             "android.app.extra.PROVISIONING_WIFI_ANONYMOUS_IDENTITY";
801     /**
802      * The domain of the wifi network in {@link #EXTRA_PROVISIONING_WIFI_SSID}. This is only used if
803      * the {@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE} is {@code EAP}.
804      *
805      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
806      * provisioning via an NFC bump. It can also be used for QR code provisioning.
807      */
808     public static final String EXTRA_PROVISIONING_WIFI_DOMAIN =
809             "android.app.extra.PROVISIONING_WIFI_DOMAIN";
810 
811     /**
812      * A String extra holding the proxy host for the wifi network in
813      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
814      *
815      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
816      * provisioning via an NFC bump.
817      */
818     public static final String EXTRA_PROVISIONING_WIFI_PROXY_HOST
819         = "android.app.extra.PROVISIONING_WIFI_PROXY_HOST";
820 
821     /**
822      * An int extra holding the proxy port for the wifi network in
823      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
824      *
825      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
826      * provisioning via an NFC bump.
827      */
828     public static final String EXTRA_PROVISIONING_WIFI_PROXY_PORT
829         = "android.app.extra.PROVISIONING_WIFI_PROXY_PORT";
830 
831     /**
832      * A String extra holding the proxy bypass for the wifi network in
833      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
834      *
835      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
836      * provisioning via an NFC bump.
837      */
838     public static final String EXTRA_PROVISIONING_WIFI_PROXY_BYPASS
839         = "android.app.extra.PROVISIONING_WIFI_PROXY_BYPASS";
840 
841     /**
842      * A String extra holding the proxy auto-config (PAC) URL for the wifi network in
843      * {@link #EXTRA_PROVISIONING_WIFI_SSID}.
844      *
845      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
846      * provisioning via an NFC bump.
847      */
848     public static final String EXTRA_PROVISIONING_WIFI_PAC_URL
849         = "android.app.extra.PROVISIONING_WIFI_PAC_URL";
850 
851     /**
852      * A String extra holding a url that specifies the download location of the device admin
853      * package. When not provided it is assumed that the device admin package is already installed.
854      *
855      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
856      * provisioning via an NFC bump.
857      */
858     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION
859         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION";
860 
861     /**
862      * A String extra holding the localized name of the organization under management.
863      *
864      * The name is displayed only during provisioning.
865      *
866      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
867      *
868      * @hide
869      */
870     @SystemApi
871     public static final String EXTRA_PROVISIONING_ORGANIZATION_NAME =
872             "android.app.extra.PROVISIONING_ORGANIZATION_NAME";
873 
874     /**
875      * A String extra holding a url to the website of the device provider so the user can open it
876      * during provisioning. If the url is not HTTPS, an error will be shown.
877      *
878      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
879      *
880      * @hide
881      */
882     @SystemApi
883     public static final String EXTRA_PROVISIONING_SUPPORT_URL =
884             "android.app.extra.PROVISIONING_SUPPORT_URL";
885 
886     /**
887      * A String extra holding the localized name of the device admin package. It should be the same
888      * as the app label of the package.
889      *
890      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
891      *
892      * @hide
893      */
894     @SystemApi
895     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL =
896             "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_LABEL";
897 
898     /**
899      * A {@link Uri} extra pointing to the app icon of device admin package. This image will be
900      * shown during the provisioning.
901      * <h5>The following URI schemes are accepted:</h5>
902      * <ul>
903      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
904      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
905      * </ul>
906      *
907      * <p> It is the responsibility of the caller to provide an image with a reasonable
908      * pixel density for the device.
909      *
910      * <p> If a content: URI is passed, the intent should have the flag
911      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
912      * {@link android.content.ClipData} of the intent too.
913      *
914      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}
915      *
916      * @hide
917      */
918     @SystemApi
919     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI =
920             "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_ICON_URI";
921 
922     /**
923      * An int extra holding a minimum required version code for the device admin package. If the
924      * device admin is already installed on the device, it will only be re-downloaded from
925      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION} if the version of the
926      * installed package is less than this version code.
927      *
928      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
929      * provisioning via an NFC bump.
930      */
931     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE
932         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_MINIMUM_VERSION_CODE";
933 
934     /**
935      * A String extra holding a http cookie header which should be used in the http request to the
936      * url specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
937      *
938      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
939      * provisioning via an NFC bump.
940      */
941     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER
942         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER";
943 
944     /**
945      * A String extra holding the URL-safe base64 encoded SHA-256 hash of the file at download
946      * location specified in {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
947      *
948      * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM} must be
949      * present. The provided checksum must match the checksum of the file at the download
950      * location. If the checksum doesn't match an error will be shown to the user and the user will
951      * be asked to factory reset the device.
952      *
953      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
954      * provisioning via an NFC bump.
955      *
956      * <p><strong>Note:</strong> for devices running {@link android.os.Build.VERSION_CODES#LOLLIPOP}
957      * and {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} only SHA-1 hash is supported.
958      * Starting from {@link android.os.Build.VERSION_CODES#M}, this parameter accepts SHA-256 in
959      * addition to SHA-1. From {@link android.os.Build.VERSION_CODES#Q}, only SHA-256 hash is
960      * supported.
961      */
962     public static final String EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM
963         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM";
964 
965     /**
966      * A String extra holding the URL-safe base64 encoded SHA-256 checksum of any signature of the
967      * android package archive at the download location specified in {@link
968      * #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}.
969      *
970      * <p>The signatures of an android package archive can be obtained using
971      * {@link android.content.pm.PackageManager#getPackageArchiveInfo} with flag
972      * {@link android.content.pm.PackageManager#GET_SIGNATURES}.
973      *
974      * <p>Either this extra or {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM} must be
975      * present. The provided checksum must match the checksum of any signature of the file at
976      * the download location. If the checksum does not match an error will be shown to the user and
977      * the user will be asked to factory reset the device.
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_SIGNATURE_CHECKSUM
983         = "android.app.extra.PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM";
984 
985     /**
986      * Broadcast Action: This broadcast is sent to indicate that provisioning of a managed profile
987      * has completed successfully.
988      *
989      * <p>The broadcast is limited to the primary profile, to the app specified in the provisioning
990      * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
991      *
992      * <p>This intent will contain the following extras
993      * <ul>
994      * <li>{@link Intent#EXTRA_USER}, corresponds to the {@link UserHandle} of the managed
995      * profile.</li>
996      * <li>{@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE}, corresponds to the account requested to
997      * be migrated at provisioning time, if any.</li>
998      * </ul>
999      */
1000     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1001     public static final String ACTION_MANAGED_PROFILE_PROVISIONED
1002         = "android.app.action.MANAGED_PROFILE_PROVISIONED";
1003 
1004     /**
1005      * Activity action: This activity action is sent to indicate that provisioning of a managed
1006      * profile or managed device has completed successfully. It'll be sent at the same time as
1007      * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} broadcast but this will be
1008      * delivered faster as it's an activity intent.
1009      *
1010      * <p>The intent is only sent to the new device or profile owner.
1011      *
1012      * @see #ACTION_PROVISION_MANAGED_PROFILE
1013      * @see #ACTION_PROVISION_MANAGED_DEVICE
1014      */
1015     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1016     public static final String ACTION_PROVISIONING_SUCCESSFUL =
1017             "android.app.action.PROVISIONING_SUCCESSFUL";
1018 
1019     /**
1020      * A boolean extra indicating whether device encryption can be skipped as part of device owner
1021      * or managed profile provisioning.
1022      *
1023      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action
1024      * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning.
1025      *
1026      * <p>From {@link android.os.Build.VERSION_CODES#N} onwards, this is also supported for an
1027      * intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE}.
1028      */
1029     public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION =
1030              "android.app.extra.PROVISIONING_SKIP_ENCRYPTION";
1031 
1032     /**
1033      * A {@link Uri} extra pointing to a logo image. This image will be shown during the
1034      * provisioning. If this extra is not passed, a default image will be shown.
1035      * <h5>The following URI schemes are accepted:</h5>
1036      * <ul>
1037      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1038      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1039      * </ul>
1040      *
1041      * <p> It is the responsibility of the caller to provide an image with a reasonable
1042      * pixel density for the device.
1043      *
1044      * <p> If a content: URI is passed, the intent should have the flag
1045      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1046      * {@link android.content.ClipData} of the intent too.
1047      *
1048      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1049      * {@link #ACTION_PROVISION_MANAGED_DEVICE}
1050      */
1051     public static final String EXTRA_PROVISIONING_LOGO_URI =
1052             "android.app.extra.PROVISIONING_LOGO_URI";
1053 
1054     /**
1055      * A {@link Bundle}[] extra consisting of list of disclaimer headers and disclaimer contents.
1056      * Each {@link Bundle} must have both {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}
1057      * as disclaimer header, and {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT} as disclaimer
1058      * content.
1059      *
1060      * <p> The extra typically contains one disclaimer from the company of mobile device
1061      * management application (MDM), and one disclaimer from the organization.
1062      *
1063      * <p> Call {@link Bundle#putParcelableArray(String, Parcelable[])} to put the {@link Bundle}[]
1064      *
1065      * <p> Maximum 3 key-value pairs can be specified. The rest will be ignored.
1066      *
1067      * <p> Use in an intent with action {@link #ACTION_PROVISION_MANAGED_PROFILE} or
1068      * {@link #ACTION_PROVISION_MANAGED_DEVICE}
1069      */
1070     public static final String EXTRA_PROVISIONING_DISCLAIMERS =
1071             "android.app.extra.PROVISIONING_DISCLAIMERS";
1072 
1073     /**
1074      * A String extra of localized disclaimer header.
1075      *
1076      * <p> The extra is typically the company name of mobile device management application (MDM)
1077      * or the organization name.
1078      *
1079      * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
1080      *
1081      * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
1082      * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
1083      * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_CONTENT}. Here is the example:
1084      *
1085      * <pre>
1086      *  &lt;meta-data
1087      *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_HEADER"
1088      *      android:resource="@string/disclaimer_header"
1089      * /&gt;</pre>
1090      */
1091     public static final String EXTRA_PROVISIONING_DISCLAIMER_HEADER =
1092             "android.app.extra.PROVISIONING_DISCLAIMER_HEADER";
1093 
1094     /**
1095      * A {@link Uri} extra pointing to disclaimer content.
1096      *
1097      * <h5>The following URI schemes are accepted:</h5>
1098      * <ul>
1099      * <li>content ({@link android.content.ContentResolver#SCHEME_CONTENT})</li>
1100      * <li>android.resource ({@link android.content.ContentResolver#SCHEME_ANDROID_RESOURCE})</li>
1101      * </ul>
1102      *
1103      * <p> Styled text is supported in the disclaimer content. The content is parsed by
1104      * {@link android.text.Html#fromHtml(String)} and displayed in a
1105      * {@link android.widget.TextView}.
1106      *
1107      * <p> If a <code>content:</code> URI is passed, URI is passed, the intent should have the flag
1108      * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and the uri should be added to the
1109      * {@link android.content.ClipData} of the intent too.
1110      *
1111      * <p> Use in Bundle {@link #EXTRA_PROVISIONING_DISCLAIMERS}
1112      *
1113      * <p> System app, i.e. application with {@link ApplicationInfo#FLAG_SYSTEM}, can also insert a
1114      * disclaimer by declaring an application-level meta-data in {@code AndroidManifest.xml}.
1115      * Must use it with {@link #EXTRA_PROVISIONING_DISCLAIMER_HEADER}. Here is the example:
1116      *
1117      * <pre>
1118      *  &lt;meta-data
1119      *      android:name="android.app.extra.PROVISIONING_DISCLAIMER_CONTENT"
1120      *      android:resource="@string/disclaimer_content"
1121      * /&gt;</pre>
1122      */
1123     public static final String EXTRA_PROVISIONING_DISCLAIMER_CONTENT =
1124             "android.app.extra.PROVISIONING_DISCLAIMER_CONTENT";
1125 
1126     /**
1127      * A boolean extra indicating if user setup should be skipped, for when provisioning is started
1128      * during setup-wizard.
1129      *
1130      * <p>If unspecified, defaults to {@code true} to match the behavior in
1131      * {@link android.os.Build.VERSION_CODES#M} and earlier.
1132      *
1133      * <p>Use in an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or
1134      * {@link #ACTION_PROVISION_MANAGED_USER}.
1135      *
1136      * @hide
1137      */
1138     public static final String EXTRA_PROVISIONING_SKIP_USER_SETUP =
1139             "android.app.extra.PROVISIONING_SKIP_USER_SETUP";
1140 
1141     /**
1142      * A boolean extra indicating if the user consent steps from the provisioning flow should be
1143      * skipped. If unspecified, defaults to {@code false}.
1144      *
1145      * It can only be used by an existing device owner trying to create a managed profile via
1146      * {@link #ACTION_PROVISION_MANAGED_PROFILE}. Otherwise it is ignored.
1147      */
1148     public static final String EXTRA_PROVISIONING_SKIP_USER_CONSENT =
1149             "android.app.extra.PROVISIONING_SKIP_USER_CONSENT";
1150 
1151     /**
1152      * A boolean extra indicating if the education screens from the provisioning flow should be
1153      * skipped. If unspecified, defaults to {@code false}.
1154      *
1155      * <p>This extra can be set in the following ways:
1156      * <ul>
1157      * <li>By the admin app when performing the admin-integrated
1158      * provisioning flow as a result of the {@link #ACTION_GET_PROVISIONING_MODE} activity</li>
1159      * <li>With intent action {@link #ACTION_PROVISION_MANAGED_DEVICE}</li>
1160      * </ul>
1161      *
1162      * <p>If the education screens are skipped, it is the admin application's responsibility
1163      * to display its own user education screens.
1164      */
1165     public static final String EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS =
1166             "android.app.extra.PROVISIONING_SKIP_EDUCATION_SCREENS";
1167 
1168     /**
1169      * A boolean extra indicating if mobile data should be used during NFC device owner provisioning
1170      * for downloading the mobile device management application. If {@link
1171      * #EXTRA_PROVISIONING_WIFI_SSID} is also specified, wifi network will be used instead.
1172      *
1173      * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner
1174      * provisioning via an NFC bump.
1175      *
1176      * @hide
1177      */
1178     public static final String EXTRA_PROVISIONING_USE_MOBILE_DATA =
1179             "android.app.extra.PROVISIONING_USE_MOBILE_DATA";
1180 
1181     /**
1182      * A String extra holding the provisioning trigger. It could be one of
1183      * {@link #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT}, {@link #PROVISIONING_TRIGGER_QR_CODE},
1184      * {@link #PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER} or {@link
1185      * #PROVISIONING_TRIGGER_UNSPECIFIED}.
1186      *
1187      * <p>Use in an intent with action {@link
1188      * #ACTION_PROVISION_MANAGED_DEVICE_FROM_TRUSTED_SOURCE}.
1189      * @hide
1190      */
1191     @SystemApi
1192     public static final String EXTRA_PROVISIONING_TRIGGER =
1193             "android.app.extra.PROVISIONING_TRIGGER";
1194 
1195     /**
1196      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1197      * trigger has not been specified.
1198      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1199      * @see #PROVISIONING_TRIGGER_QR_CODE
1200      * @see #PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER
1201      * @hide
1202      */
1203     @SystemApi
1204     public static final int PROVISIONING_TRIGGER_UNSPECIFIED = 0;
1205 
1206     /**
1207      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1208      * trigger is cloud enrollment.
1209      * @see #PROVISIONING_TRIGGER_QR_CODE
1210      * @see #PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER
1211      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1212      * @hide
1213      */
1214     @SystemApi
1215     public static final int PROVISIONING_TRIGGER_CLOUD_ENROLLMENT = 1;
1216 
1217     /**
1218      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1219      * trigger is the QR code scanner.
1220      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1221      * @see #PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER
1222      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1223      * @hide
1224      */
1225     @SystemApi
1226     public static final int PROVISIONING_TRIGGER_QR_CODE = 2;
1227 
1228     /**
1229      * A value for {@link #EXTRA_PROVISIONING_TRIGGER} indicating that the provisioning
1230      * trigger is persistent device owner enrollment.
1231      * @see #PROVISIONING_TRIGGER_CLOUD_ENROLLMENT
1232      * @see #PROVISIONING_TRIGGER_QR_CODE
1233      * @see #PROVISIONING_TRIGGER_UNSPECIFIED
1234      * @hide
1235      */
1236     @SystemApi
1237     public static final int PROVISIONING_TRIGGER_PERSISTENT_DEVICE_OWNER = 3;
1238 
1239     /**
1240      * This MIME type is used for starting the device owner provisioning.
1241      *
1242      * <p>During device owner provisioning a device admin app is set as the owner of the device.
1243      * A device owner has full control over the device. The device owner can not be modified by the
1244      * user and the only way of resetting the device is if the device owner app calls a factory
1245      * reset.
1246      *
1247      * <p> A typical use case would be a device that is owned by a company, but used by either an
1248      * employee or client.
1249      *
1250      * <p> The NFC message must be sent to an unprovisioned device.
1251      *
1252      * <p>The NFC record must contain a serialized {@link java.util.Properties} object which
1253      * contains the following properties:
1254      * <ul>
1255      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}</li>
1256      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION}, optional</li>
1257      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_COOKIE_HEADER}, optional</li>
1258      * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM}, optional</li>
1259      * <li>{@link #EXTRA_PROVISIONING_LOCAL_TIME} (convert to String), optional</li>
1260      * <li>{@link #EXTRA_PROVISIONING_TIME_ZONE}, optional</li>
1261      * <li>{@link #EXTRA_PROVISIONING_LOCALE}, optional</li>
1262      * <li>{@link #EXTRA_PROVISIONING_WIFI_SSID}, optional</li>
1263      * <li>{@link #EXTRA_PROVISIONING_WIFI_HIDDEN} (convert to String), optional</li>
1264      * <li>{@link #EXTRA_PROVISIONING_WIFI_SECURITY_TYPE}, optional</li>
1265      * <li>{@link #EXTRA_PROVISIONING_WIFI_PASSWORD}, optional</li>
1266      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_HOST}, optional</li>
1267      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_PORT} (convert to String), optional</li>
1268      * <li>{@link #EXTRA_PROVISIONING_WIFI_PROXY_BYPASS}, optional</li>
1269      * <li>{@link #EXTRA_PROVISIONING_WIFI_PAC_URL}, optional</li>
1270      * <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}, optional, supported from {@link
1271      * android.os.Build.VERSION_CODES#M} </li>
1272      * <li>{@link #EXTRA_PROVISIONING_WIFI_EAP_METHOD}, optional, supported from {@link
1273      * android.os.Build.VERSION_CODES#Q}</li>
1274      * <li>{@link #EXTRA_PROVISIONING_WIFI_PHASE2_AUTH}, optional, supported from {@link
1275      * android.os.Build.VERSION_CODES#Q}</li>
1276      * <li>{@link #EXTRA_PROVISIONING_WIFI_CA_CERTIFICATE}, optional, supported from {@link
1277      * android.os.Build.VERSION_CODES#Q}</li>
1278      * <li>{@link #EXTRA_PROVISIONING_WIFI_USER_CERTIFICATE}, optional, supported from {@link
1279      * android.os.Build.VERSION_CODES#Q}</li>
1280      * <li>{@link #EXTRA_PROVISIONING_WIFI_IDENTITY}, optional, supported from {@link
1281      * android.os.Build.VERSION_CODES#Q}</li>
1282      * <li>{@link #EXTRA_PROVISIONING_WIFI_ANONYMOUS_IDENTITY}, optional, supported from {@link
1283      * android.os.Build.VERSION_CODES#Q}</li>
1284      * <li>{@link #EXTRA_PROVISIONING_WIFI_DOMAIN}, optional, supported from {@link
1285      * android.os.Build.VERSION_CODES#Q}</li></ul>
1286      *
1287      * <p>
1288      * As of {@link android.os.Build.VERSION_CODES#M}, the properties should contain
1289      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME} instead of
1290      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME}, (although specifying only
1291      * {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME} is still supported).
1292      */
1293     public static final String MIME_TYPE_PROVISIONING_NFC
1294         = "application/com.android.managedprovisioning";
1295 
1296     /**
1297      * Activity action: ask the user to add a new device administrator to the system.
1298      * The desired policy is the ComponentName of the policy in the
1299      * {@link #EXTRA_DEVICE_ADMIN} extra field.  This will invoke a UI to
1300      * bring the user through adding the device administrator to the system (or
1301      * allowing them to reject it).
1302      *
1303      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1304      * field to provide the user with additional explanation (in addition
1305      * to your component's description) about what is being added.
1306      *
1307      * <p>If your administrator is already active, this will ordinarily return immediately (without
1308      * user intervention).  However, if your administrator has been updated and is requesting
1309      * additional uses-policy flags, the user will be presented with the new list.  New policies
1310      * will not be available to the updated administrator until the user has accepted the new list.
1311      */
1312     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1313     public static final String ACTION_ADD_DEVICE_ADMIN
1314             = "android.app.action.ADD_DEVICE_ADMIN";
1315 
1316     /**
1317      * @hide
1318      * Activity action: ask the user to add a new device administrator as the profile owner
1319      * for this user. Only system apps can launch this intent.
1320      *
1321      * <p>The ComponentName of the profile owner admin is passed in the {@link #EXTRA_DEVICE_ADMIN}
1322      * extra field. This will invoke a UI to bring the user through adding the profile owner admin
1323      * to remotely control restrictions on the user.
1324      *
1325      * <p>The intent must be invoked via {@link Activity#startActivityForResult} to receive the
1326      * result of whether or not the user approved the action. If approved, the result will
1327      * be {@link Activity#RESULT_OK} and the component will be set as an active admin as well
1328      * as a profile owner.
1329      *
1330      * <p>You can optionally include the {@link #EXTRA_ADD_EXPLANATION}
1331      * field to provide the user with additional explanation (in addition
1332      * to your component's description) about what is being added.
1333      *
1334      * <p>If there is already a profile owner active or the caller is not a system app, the
1335      * operation will return a failure result.
1336      */
1337     @SystemApi
1338     public static final String ACTION_SET_PROFILE_OWNER
1339             = "android.app.action.SET_PROFILE_OWNER";
1340 
1341     /**
1342      * @hide
1343      * Name of the profile owner admin that controls the user.
1344      */
1345     @SystemApi
1346     public static final String EXTRA_PROFILE_OWNER_NAME
1347             = "android.app.extra.PROFILE_OWNER_NAME";
1348 
1349     /**
1350      * Broadcast action: send when any policy admin changes a policy.
1351      * This is generally used to find out when a new policy is in effect.
1352      *
1353      * @hide
1354      */
1355     @UnsupportedAppUsage
1356     public static final String ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED
1357             = "android.app.action.DEVICE_POLICY_MANAGER_STATE_CHANGED";
1358 
1359     /**
1360      * Broadcast action: sent when the device owner is set, changed or cleared.
1361      *
1362      * This broadcast is sent only to the primary user.
1363      * @see #ACTION_PROVISION_MANAGED_DEVICE
1364      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
1365      */
1366     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1367     public static final String ACTION_DEVICE_OWNER_CHANGED
1368             = "android.app.action.DEVICE_OWNER_CHANGED";
1369 
1370     /**
1371      * The ComponentName of the administrator component.
1372      *
1373      * @see #ACTION_ADD_DEVICE_ADMIN
1374      */
1375     public static final String EXTRA_DEVICE_ADMIN = "android.app.extra.DEVICE_ADMIN";
1376 
1377     /**
1378      * An optional CharSequence providing additional explanation for why the
1379      * admin is being added.
1380      *
1381      * @see #ACTION_ADD_DEVICE_ADMIN
1382      */
1383     public static final String EXTRA_ADD_EXPLANATION = "android.app.extra.ADD_EXPLANATION";
1384 
1385     /**
1386      * Constant to indicate the feature of disabling the camera. Used as argument to
1387      * {@link #createAdminSupportIntent(String)}.
1388      * @see #setCameraDisabled(ComponentName, boolean)
1389      */
1390     public static final String POLICY_DISABLE_CAMERA = "policy_disable_camera";
1391 
1392     /**
1393      * Constant to indicate the feature of disabling screen captures. Used as argument to
1394      * {@link #createAdminSupportIntent(String)}.
1395      * @see #setScreenCaptureDisabled(ComponentName, boolean)
1396      */
1397     public static final String POLICY_DISABLE_SCREEN_CAPTURE = "policy_disable_screen_capture";
1398 
1399     /**
1400      * Constant to indicate the feature of suspending app. Use it as the value of
1401      * {@link #EXTRA_RESTRICTION}.
1402      * @hide
1403      */
1404     public static final String POLICY_SUSPEND_PACKAGES = "policy_suspend_packages";
1405 
1406     /**
1407      * A String indicating a specific restricted feature. Can be a user restriction from the
1408      * {@link UserManager}, e.g. {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the values
1409      * {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
1410      * @see #createAdminSupportIntent(String)
1411      * @hide
1412      */
1413     @TestApi @SystemApi
1414     public static final String EXTRA_RESTRICTION = "android.app.extra.RESTRICTION";
1415 
1416     /**
1417      * Activity action: have the user enter a new password.
1418      *
1419      * <p>For admin apps, this activity should be launched after using {@link
1420      * #setPasswordQuality(ComponentName, int)}, or {@link
1421      * #setPasswordMinimumLength(ComponentName, int)} to have the user enter a new password that
1422      * meets the current requirements. You can use {@link #isActivePasswordSufficient()} to
1423      * determine whether you need to have the user select a new password in order to meet the
1424      * current constraints. Upon being resumed from this activity, you can check the new
1425      * password characteristics to see if they are sufficient.
1426      *
1427      * <p>Non-admin apps can use {@link #getPasswordComplexity()} to check the current screen lock
1428      * complexity, and use this activity with extra {@link #EXTRA_PASSWORD_COMPLEXITY} to suggest
1429      * to users how complex the app wants the new screen lock to be. Note that both {@link
1430      * #getPasswordComplexity()} and the extra {@link #EXTRA_PASSWORD_COMPLEXITY} require the
1431      * calling app to have the permission {@link permission#REQUEST_PASSWORD_COMPLEXITY}.
1432      *
1433      * <p>If the intent is launched from within a managed profile with a profile
1434      * owner built against {@link android.os.Build.VERSION_CODES#M} or before,
1435      * this will trigger entering a new password for the parent of the profile.
1436      * For all other cases it will trigger entering a new password for the user
1437      * or profile it is launched from.
1438      *
1439      * @see #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1440      */
1441     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1442     public static final String ACTION_SET_NEW_PASSWORD
1443             = "android.app.action.SET_NEW_PASSWORD";
1444 
1445     /**
1446      * An integer indicating the complexity level of the new password an app would like the user to
1447      * set when launching the action {@link #ACTION_SET_NEW_PASSWORD}.
1448      *
1449      * <p>Must be one of
1450      * <ul>
1451      *     <li>{@link #PASSWORD_COMPLEXITY_HIGH}
1452      *     <li>{@link #PASSWORD_COMPLEXITY_MEDIUM}
1453      *     <li>{@link #PASSWORD_COMPLEXITY_LOW}
1454      *     <li>{@link #PASSWORD_COMPLEXITY_NONE}
1455      * </ul>
1456      *
1457      * <p>If an invalid value is used, it will be treated as {@link #PASSWORD_COMPLEXITY_NONE}.
1458      */
1459     @RequiresPermission(android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY)
1460     public static final String EXTRA_PASSWORD_COMPLEXITY =
1461             "android.app.extra.PASSWORD_COMPLEXITY";
1462 
1463     /**
1464      * Constant for {@link #getPasswordComplexity()}: no password.
1465      *
1466      * <p>Note that these complexity constants are ordered so that higher values are more complex.
1467      */
1468     public static final int PASSWORD_COMPLEXITY_NONE = 0;
1469 
1470     /**
1471      * Constant for {@link #getPasswordComplexity()}: password satisfies one of the following:
1472      * <ul>
1473      * <li>pattern
1474      * <li>PIN with repeating (4444) or ordered (1234, 4321, 2468) sequences
1475      * </ul>
1476      *
1477      * <p>Note that these complexity constants are ordered so that higher values are more complex.
1478      *
1479      * @see #PASSWORD_QUALITY_SOMETHING
1480      * @see #PASSWORD_QUALITY_NUMERIC
1481      */
1482     public static final int PASSWORD_COMPLEXITY_LOW = 0x10000;
1483 
1484     /**
1485      * Constant for {@link #getPasswordComplexity()}: password satisfies one of the following:
1486      * <ul>
1487      * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
1488      * least 4
1489      * <li>alphabetic, length at least 4
1490      * <li>alphanumeric, length at least 4
1491      * </ul>
1492      *
1493      * <p>Note that these complexity constants are ordered so that higher values are more complex.
1494      *
1495      * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX
1496      * @see #PASSWORD_QUALITY_ALPHABETIC
1497      * @see #PASSWORD_QUALITY_ALPHANUMERIC
1498      */
1499     public static final int PASSWORD_COMPLEXITY_MEDIUM = 0x30000;
1500 
1501     /**
1502      * Constant for {@link #getPasswordComplexity()}: password satisfies one of the following:
1503      * <ul>
1504      * <li>PIN with <b>no</b> repeating (4444) or ordered (1234, 4321, 2468) sequences, length at
1505      * least 8
1506      * <li>alphabetic, length at least 6
1507      * <li>alphanumeric, length at least 6
1508      * </ul>
1509      *
1510      * <p>Note that these complexity constants are ordered so that higher values are more complex.
1511      *
1512      * @see #PASSWORD_QUALITY_NUMERIC_COMPLEX
1513      * @see #PASSWORD_QUALITY_ALPHABETIC
1514      * @see #PASSWORD_QUALITY_ALPHANUMERIC
1515      */
1516     public static final int PASSWORD_COMPLEXITY_HIGH = 0x50000;
1517 
1518     /**
1519      * @hide
1520      */
1521     @Retention(RetentionPolicy.SOURCE)
1522     @IntDef(prefix = {"PASSWORD_COMPLEXITY_"}, value = {
1523             PASSWORD_COMPLEXITY_NONE,
1524             PASSWORD_COMPLEXITY_LOW,
1525             PASSWORD_COMPLEXITY_MEDIUM,
1526             PASSWORD_COMPLEXITY_HIGH,
1527     })
1528     public @interface PasswordComplexity {}
1529 
1530     /**
1531      * Activity action: have the user enter a new password for the parent profile.
1532      * If the intent is launched from within a managed profile, this will trigger
1533      * entering a new password for the parent of the profile. In all other cases
1534      * the behaviour is identical to {@link #ACTION_SET_NEW_PASSWORD}.
1535      */
1536     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
1537     public static final String ACTION_SET_NEW_PARENT_PROFILE_PASSWORD
1538             = "android.app.action.SET_NEW_PARENT_PROFILE_PASSWORD";
1539 
1540     /**
1541      * Broadcast action: Tell the status bar to open the device monitoring dialog, e.g. when
1542      * Network logging was enabled and the user tapped the notification.
1543      * <p class="note">This is a protected intent that can only be sent by the system.</p>
1544      * @hide
1545      */
1546     public static final String ACTION_SHOW_DEVICE_MONITORING_DIALOG
1547             = "android.app.action.SHOW_DEVICE_MONITORING_DIALOG";
1548 
1549     /**
1550      * Broadcast Action: Sent after application delegation scopes are changed. The new delegation
1551      * scopes will be sent in an {@code ArrayList<String>} extra identified by the
1552      * {@link #EXTRA_DELEGATION_SCOPES} key.
1553      *
1554      * <p class="note"><b>Note:</b> This is a protected intent that can only be sent by the
1555      * system.</p>
1556      */
1557     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1558     public static final String ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED =
1559             "android.app.action.APPLICATION_DELEGATION_SCOPES_CHANGED";
1560 
1561     /**
1562      * An {@code ArrayList<String>} corresponding to the delegation scopes given to an app in the
1563      * {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} broadcast.
1564      */
1565     public static final String EXTRA_DELEGATION_SCOPES = "android.app.extra.DELEGATION_SCOPES";
1566 
1567     /**
1568      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1569      * the parent profile to access intents sent from the managed profile.
1570      * That is, when an app in the managed profile calls
1571      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1572      * matching activity in the parent profile.
1573      */
1574     public static final int FLAG_PARENT_CAN_ACCESS_MANAGED = 0x0001;
1575 
1576     /**
1577      * Flag used by {@link #addCrossProfileIntentFilter} to allow activities in
1578      * the managed profile to access intents sent from the parent profile.
1579      * That is, when an app in the parent profile calls
1580      * {@link Activity#startActivity(Intent)}, the intent can be resolved by a
1581      * matching activity in the managed profile.
1582      */
1583     public static final int FLAG_MANAGED_CAN_ACCESS_PARENT = 0x0002;
1584 
1585     /**
1586      * Broadcast action: notify that a new local system update policy has been set by the device
1587      * owner. The new policy can be retrieved by {@link #getSystemUpdatePolicy()}.
1588      */
1589     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1590     public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
1591             = "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
1592 
1593     /**
1594      * Broadcast action to notify ManagedProvisioning that
1595      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has changed.
1596      * @hide
1597      */
1598     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1599     public static final String ACTION_DATA_SHARING_RESTRICTION_CHANGED =
1600             "android.app.action.DATA_SHARING_RESTRICTION_CHANGED";
1601 
1602     /**
1603      * Broadcast action from ManagedProvisioning to notify that the latest change to
1604      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE} restriction has been successfully
1605      * applied (cross profile intent filters updated). Only usesd for CTS tests.
1606      * @hide
1607      */
1608     @TestApi
1609     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1610     public static final String ACTION_DATA_SHARING_RESTRICTION_APPLIED =
1611             "android.app.action.DATA_SHARING_RESTRICTION_APPLIED";
1612 
1613     /**
1614      * Permission policy to prompt user for new permission requests for runtime permissions.
1615      * Already granted or denied permissions are not affected by this.
1616      */
1617     public static final int PERMISSION_POLICY_PROMPT = 0;
1618 
1619     /**
1620      * Permission policy to always grant new permission requests for runtime permissions.
1621      * Already granted or denied permissions are not affected by this.
1622      */
1623     public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
1624 
1625     /**
1626      * Permission policy to always deny new permission requests for runtime permissions.
1627      * Already granted or denied permissions are not affected by this.
1628      */
1629     public static final int PERMISSION_POLICY_AUTO_DENY = 2;
1630 
1631     /**
1632      * Possible policy values for permissions.
1633      *
1634      * @hide
1635      */
1636     @IntDef(prefix = { "PERMISSION_GRANT_STATE_" }, value = {
1637             PERMISSION_GRANT_STATE_DEFAULT,
1638             PERMISSION_GRANT_STATE_GRANTED,
1639             PERMISSION_GRANT_STATE_DENIED
1640     })
1641     @Retention(RetentionPolicy.SOURCE)
1642     public @interface PermissionGrantState {}
1643 
1644     /**
1645      * Runtime permission state: The user can manage the permission
1646      * through the UI.
1647      */
1648     public static final int PERMISSION_GRANT_STATE_DEFAULT = 0;
1649 
1650     /**
1651      * Runtime permission state: The permission is granted to the app
1652      * and the user cannot manage the permission through the UI.
1653      */
1654     public static final int PERMISSION_GRANT_STATE_GRANTED = 1;
1655 
1656     /**
1657      * Runtime permission state: The permission is denied to the app
1658      * and the user cannot manage the permission through the UI.
1659      */
1660     public static final int PERMISSION_GRANT_STATE_DENIED = 2;
1661 
1662     /**
1663      * Delegation of certificate installation and management. This scope grants access to the
1664      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
1665      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair} APIs.
1666      */
1667     public static final String DELEGATION_CERT_INSTALL = "delegation-cert-install";
1668 
1669     /**
1670      * Delegation of application restrictions management. This scope grants access to the
1671      * {@link #setApplicationRestrictions} and {@link #getApplicationRestrictions} APIs.
1672      */
1673     public static final String DELEGATION_APP_RESTRICTIONS = "delegation-app-restrictions";
1674 
1675     /**
1676      * Delegation of application uninstall block. This scope grants access to the
1677      * {@link #setUninstallBlocked} API.
1678      */
1679     public static final String DELEGATION_BLOCK_UNINSTALL = "delegation-block-uninstall";
1680 
1681     /**
1682      * Delegation of permission policy and permission grant state. This scope grants access to the
1683      * {@link #setPermissionPolicy}, {@link #getPermissionGrantState},
1684      * and {@link #setPermissionGrantState} APIs.
1685      */
1686     public static final String DELEGATION_PERMISSION_GRANT = "delegation-permission-grant";
1687 
1688     /**
1689      * Delegation of package access state. This scope grants access to the
1690      * {@link #isApplicationHidden}, {@link #setApplicationHidden}, {@link #isPackageSuspended}, and
1691      * {@link #setPackagesSuspended} APIs.
1692      */
1693     public static final String DELEGATION_PACKAGE_ACCESS = "delegation-package-access";
1694 
1695     /**
1696      * Delegation for enabling system apps. This scope grants access to the {@link #enableSystemApp}
1697      * API.
1698      */
1699     public static final String DELEGATION_ENABLE_SYSTEM_APP = "delegation-enable-system-app";
1700 
1701     /**
1702      * Delegation for installing existing packages. This scope grants access to the
1703      * {@link #installExistingPackage} API.
1704      */
1705     public static final String DELEGATION_INSTALL_EXISTING_PACKAGE =
1706             "delegation-install-existing-package";
1707 
1708     /**
1709      * Delegation of management of uninstalled packages. This scope grants access to the
1710      * {@link #setKeepUninstalledPackages} and {@link #getKeepUninstalledPackages} APIs.
1711      */
1712     public static final String DELEGATION_KEEP_UNINSTALLED_PACKAGES =
1713             "delegation-keep-uninstalled-packages";
1714 
1715     /**
1716      * Grants access to {@link #setNetworkLoggingEnabled}, {@link #isNetworkLoggingEnabled} and
1717      * {@link #retrieveNetworkLogs}. Once granted the delegated app will start receiving
1718      * DelegatedAdminReceiver.onNetworkLogsAvailable() callback, and Device owner will no longer
1719      * receive the DeviceAdminReceiver.onNetworkLogsAvailable() callback.
1720      * There can be at most one app that has this delegation.
1721      * If another app already had delegated network logging access,
1722      * it will lose the delegation when a new app is delegated.
1723      *
1724      * <p> Can only be granted by Device Owner.
1725      */
1726     public static final String DELEGATION_NETWORK_LOGGING = "delegation-network-logging";
1727 
1728     /**
1729      * Grants access to selection of KeyChain certificates on behalf of requesting apps.
1730      * Once granted the app will start receiving
1731      * DelegatedAdminReceiver.onChoosePrivateKeyAlias. The caller (PO/DO) will
1732      * no longer receive {@link DeviceAdminReceiver#onChoosePrivateKeyAlias}.
1733      * There can be at most one app that has this delegation.
1734      * If another app already had delegated certificate selection access,
1735      * it will lose the delegation when a new app is delegated.
1736      *
1737      * <p> Can be granted by Device Owner or Profile Owner.
1738      */
1739     public static final String DELEGATION_CERT_SELECTION = "delegation-cert-selection";
1740 
1741     /**
1742      * No management for current user in-effect. This is the default.
1743      * @hide
1744      */
1745     @SystemApi
1746     public static final int STATE_USER_UNMANAGED = 0;
1747 
1748     /**
1749      * Management partially setup, user setup needs to be completed.
1750      * @hide
1751      */
1752     @SystemApi
1753     public static final int STATE_USER_SETUP_INCOMPLETE = 1;
1754 
1755     /**
1756      * Management partially setup, user setup completed.
1757      * @hide
1758      */
1759     @SystemApi
1760     public static final int STATE_USER_SETUP_COMPLETE = 2;
1761 
1762     /**
1763      * Management setup and active on current user.
1764      * @hide
1765      */
1766     @SystemApi
1767     public static final int STATE_USER_SETUP_FINALIZED = 3;
1768 
1769     /**
1770      * Management partially setup on a managed profile.
1771      * @hide
1772      */
1773     @SystemApi
1774     public static final int STATE_USER_PROFILE_COMPLETE = 4;
1775 
1776     /**
1777      * @hide
1778      */
1779     @IntDef(prefix = { "STATE_USER_" }, value = {
1780             STATE_USER_UNMANAGED,
1781             STATE_USER_SETUP_INCOMPLETE,
1782             STATE_USER_SETUP_COMPLETE,
1783             STATE_USER_SETUP_FINALIZED,
1784             STATE_USER_PROFILE_COMPLETE
1785     })
1786     @Retention(RetentionPolicy.SOURCE)
1787     public @interface UserProvisioningState {}
1788 
1789     /**
1790      * Result code for {@link #checkProvisioningPreCondition}.
1791      *
1792      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1793      * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1794      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when provisioning is allowed.
1795      *
1796      * @hide
1797      */
1798     public static final int CODE_OK = 0;
1799 
1800     /**
1801      * Result code for {@link #checkProvisioningPreCondition}.
1802      *
1803      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1804      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the device already has a device
1805      * owner.
1806      *
1807      * @hide
1808      */
1809     public static final int CODE_HAS_DEVICE_OWNER = 1;
1810 
1811     /**
1812      * Result code for {@link #checkProvisioningPreCondition}.
1813      *
1814      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1815      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user has a profile owner and for
1816      * {@link #ACTION_PROVISION_MANAGED_PROFILE} when the profile owner is already set.
1817      *
1818      * @hide
1819      */
1820     public static final int CODE_USER_HAS_PROFILE_OWNER = 2;
1821 
1822     /**
1823      * Result code for {@link #checkProvisioningPreCondition}.
1824      *
1825      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1826      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} when the user isn't running.
1827      *
1828      * @hide
1829      */
1830     public static final int CODE_USER_NOT_RUNNING = 3;
1831 
1832     /**
1833      * Result code for {@link #checkProvisioningPreCondition}.
1834      *
1835      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1836      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the device has already been setup and
1837      * for {@link #ACTION_PROVISION_MANAGED_USER} if the user has already been setup.
1838      *
1839      * @hide
1840      */
1841     public static final int CODE_USER_SETUP_COMPLETED = 4;
1842 
1843     /**
1844      * Code used to indicate that the device also has a user other than the system user.
1845      *
1846      * @hide
1847      */
1848     public static final int CODE_NONSYSTEM_USER_EXISTS = 5;
1849 
1850     /**
1851      * Code used to indicate that device has an account that prevents provisioning.
1852      *
1853      * @hide
1854      */
1855     public static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
1856 
1857     /**
1858      * Result code for {@link #checkProvisioningPreCondition}.
1859      *
1860      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE} and
1861      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} if the user is not a system user.
1862      *
1863      * @hide
1864      */
1865     public static final int CODE_NOT_SYSTEM_USER = 7;
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} and {@link #ACTION_PROVISION_MANAGED_USER}
1872      * when the device is a watch and is already paired.
1873      *
1874      * @hide
1875      */
1876     public static final int CODE_HAS_PAIRED = 8;
1877 
1878     /**
1879      * Result code for {@link #checkProvisioningPreCondition}.
1880      *
1881      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} and
1882      * {@link #ACTION_PROVISION_MANAGED_USER} on devices which do not support managed users.
1883      *
1884      * @see {@link PackageManager#FEATURE_MANAGED_USERS}
1885      * @hide
1886      */
1887     public static final int CODE_MANAGED_USERS_NOT_SUPPORTED = 9;
1888 
1889     /**
1890      * Result code for {@link #checkProvisioningPreCondition}.
1891      *
1892      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} if the user is a system user.
1893      *
1894      * @hide
1895      */
1896     public static final int CODE_SYSTEM_USER = 10;
1897 
1898     /**
1899      * Result code for {@link #checkProvisioningPreCondition}.
1900      *
1901      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the user cannot have more
1902      * managed profiles.
1903      *
1904      * @hide
1905      */
1906     public static final int CODE_CANNOT_ADD_MANAGED_PROFILE = 11;
1907 
1908     /**
1909      * Result code for {@link #checkProvisioningPreCondition}.
1910      *
1911      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_USER} and
1912      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices not running with split system
1913      * user.
1914      *
1915      * @hide
1916      */
1917     public static final int CODE_NOT_SYSTEM_USER_SPLIT = 12;
1918 
1919     /**
1920      * Result code for {@link #checkProvisioningPreCondition}.
1921      *
1922      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_DEVICE},
1923      * {@link #ACTION_PROVISION_MANAGED_PROFILE}, {@link #ACTION_PROVISION_MANAGED_USER} and
1924      * {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE} on devices which do no support device
1925      * admins.
1926      *
1927      * @hide
1928      */
1929     public static final int CODE_DEVICE_ADMIN_NOT_SUPPORTED = 13;
1930 
1931     /**
1932      * Result code for {@link #checkProvisioningPreCondition}.
1933      *
1934      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when the device the user is a
1935      * system user on a split system user device.
1936      *
1937      * @hide
1938      */
1939     public static final int CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER = 14;
1940 
1941     /**
1942      * Result code for {@link #checkProvisioningPreCondition}.
1943      *
1944      * <p>Returned for {@link #ACTION_PROVISION_MANAGED_PROFILE} when adding a managed profile is
1945      * disallowed by {@link UserManager#DISALLOW_ADD_MANAGED_PROFILE}.
1946      *
1947      * @hide
1948      */
1949     public static final int CODE_ADD_MANAGED_PROFILE_DISALLOWED = 15;
1950 
1951     /**
1952      * Result codes for {@link #checkProvisioningPreCondition} indicating all the provisioning pre
1953      * conditions.
1954      *
1955      * @hide
1956      */
1957     @Retention(RetentionPolicy.SOURCE)
1958     @IntDef(prefix = { "CODE_" }, value = {
1959             CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
1960             CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER, CODE_HAS_PAIRED,
1961             CODE_MANAGED_USERS_NOT_SUPPORTED, CODE_SYSTEM_USER, CODE_CANNOT_ADD_MANAGED_PROFILE,
1962             CODE_NOT_SYSTEM_USER_SPLIT, CODE_DEVICE_ADMIN_NOT_SUPPORTED,
1963             CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER, CODE_ADD_MANAGED_PROFILE_DISALLOWED
1964     })
1965     public @interface ProvisioningPreCondition {}
1966 
1967     /**
1968      * Disable all configurable SystemUI features during LockTask mode. This includes,
1969      * <ul>
1970      *     <li>system info area in the status bar (connectivity icons, clock, etc.)
1971      *     <li>notifications (including alerts, icons, and the notification shade)
1972      *     <li>Home button
1973      *     <li>Recents button and UI
1974      *     <li>global actions menu (i.e. power button menu)
1975      *     <li>keyguard
1976      * </ul>
1977      *
1978      * @see #setLockTaskFeatures(ComponentName, int)
1979      */
1980     public static final int LOCK_TASK_FEATURE_NONE = 0;
1981 
1982     /**
1983      * Enable the system info area in the status bar during LockTask mode. The system info area
1984      * usually occupies the right side of the status bar (although this can differ across OEMs). It
1985      * includes all system information indicators, such as date and time, connectivity, battery,
1986      * vibration mode, etc.
1987      *
1988      * @see #setLockTaskFeatures(ComponentName, int)
1989      */
1990     public static final int LOCK_TASK_FEATURE_SYSTEM_INFO = 1;
1991 
1992     /**
1993      * Enable notifications during LockTask mode. This includes notification icons on the status
1994      * bar, heads-up notifications, and the expandable notification shade. Note that the Quick
1995      * Settings panel remains disabled. This feature flag can only be used in combination with
1996      * {@link #LOCK_TASK_FEATURE_HOME}. {@link #setLockTaskFeatures(ComponentName, int)}
1997      * throws an {@link IllegalArgumentException} if this feature flag is defined without
1998      * {@link #LOCK_TASK_FEATURE_HOME}.
1999      *
2000      * @see #setLockTaskFeatures(ComponentName, int)
2001      */
2002     public static final int LOCK_TASK_FEATURE_NOTIFICATIONS = 1 << 1;
2003 
2004     /**
2005      * Enable the Home button during LockTask mode. Note that if a custom launcher is used, it has
2006      * to be registered as the default launcher with
2007      * {@link #addPersistentPreferredActivity(ComponentName, IntentFilter, ComponentName)}, and its
2008      * package needs to be whitelisted for LockTask with
2009      * {@link #setLockTaskPackages(ComponentName, String[])}.
2010      *
2011      * @see #setLockTaskFeatures(ComponentName, int)
2012      */
2013     public static final int LOCK_TASK_FEATURE_HOME = 1 << 2;
2014 
2015     /**
2016      * Enable the Overview button and the Overview screen during LockTask mode. This feature flag
2017      * can only be used in combination with {@link #LOCK_TASK_FEATURE_HOME}, and
2018      * {@link #setLockTaskFeatures(ComponentName, int)} will throw an
2019      * {@link IllegalArgumentException} if this feature flag is defined without
2020      * {@link #LOCK_TASK_FEATURE_HOME}.
2021      *
2022      * @see #setLockTaskFeatures(ComponentName, int)
2023      */
2024     public static final int LOCK_TASK_FEATURE_OVERVIEW = 1 << 3;
2025 
2026     /**
2027      * Enable the global actions dialog during LockTask mode. This is the dialog that shows up when
2028      * the user long-presses the power button, for example. Note that the user may not be able to
2029      * power off the device if this flag is not set.
2030      *
2031      * <p>This flag is enabled by default until {@link #setLockTaskFeatures(ComponentName, int)} is
2032      * called for the first time.
2033      *
2034      * @see #setLockTaskFeatures(ComponentName, int)
2035      */
2036     public static final int LOCK_TASK_FEATURE_GLOBAL_ACTIONS = 1 << 4;
2037 
2038     /**
2039      * Enable the keyguard during LockTask mode. Note that if the keyguard is already disabled with
2040      * {@link #setKeyguardDisabled(ComponentName, boolean)}, setting this flag will have no effect.
2041      * If this flag is not set, the keyguard will not be shown even if the user has a lock screen
2042      * credential.
2043      *
2044      * @see #setLockTaskFeatures(ComponentName, int)
2045      */
2046     public static final int LOCK_TASK_FEATURE_KEYGUARD = 1 << 5;
2047 
2048     /**
2049      * Flags supplied to {@link #setLockTaskFeatures(ComponentName, int)}.
2050      *
2051      * @hide
2052      */
2053     @Retention(RetentionPolicy.SOURCE)
2054     @IntDef(flag = true, prefix = { "LOCK_TASK_FEATURE_" }, value = {
2055             LOCK_TASK_FEATURE_NONE,
2056             LOCK_TASK_FEATURE_SYSTEM_INFO,
2057             LOCK_TASK_FEATURE_NOTIFICATIONS,
2058             LOCK_TASK_FEATURE_HOME,
2059             LOCK_TASK_FEATURE_OVERVIEW,
2060             LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
2061             LOCK_TASK_FEATURE_KEYGUARD
2062     })
2063     public @interface LockTaskFeature {}
2064 
2065     /**
2066      * Service action: Action for a service that device owner and profile owner can optionally
2067      * own.  If a device owner or a profile owner has such a service, the system tries to keep
2068      * a bound connection to it, in order to keep their process always running.
2069      * The service must be protected with the {@link android.Manifest.permission#BIND_DEVICE_ADMIN}
2070      * permission.
2071      */
2072     @SdkConstant(SdkConstantType.SERVICE_ACTION)
2073     public static final String ACTION_DEVICE_ADMIN_SERVICE
2074             = "android.app.action.DEVICE_ADMIN_SERVICE";
2075 
2076     /** @hide */
2077     @Retention(RetentionPolicy.SOURCE)
2078     @IntDef(flag = true, prefix = {"ID_TYPE_"}, value = {
2079         ID_TYPE_BASE_INFO,
2080         ID_TYPE_SERIAL,
2081         ID_TYPE_IMEI,
2082         ID_TYPE_MEID
2083     })
2084     public @interface AttestationIdType {}
2085 
2086     /**
2087      * Specifies that the device should attest its manufacturer details. For use with
2088      * {@link #generateKeyPair}.
2089      *
2090      * @see #generateKeyPair
2091      */
2092     public static final int ID_TYPE_BASE_INFO = 1;
2093 
2094     /**
2095      * Specifies that the device should attest its serial number. For use with
2096      * {@link #generateKeyPair}.
2097      *
2098      * @see #generateKeyPair
2099      */
2100     public static final int ID_TYPE_SERIAL = 2;
2101 
2102     /**
2103      * Specifies that the device should attest its IMEI. For use with {@link #generateKeyPair}.
2104      *
2105      * @see #generateKeyPair
2106      */
2107     public static final int ID_TYPE_IMEI = 4;
2108 
2109     /**
2110      * Specifies that the device should attest its MEID. For use with {@link #generateKeyPair}.
2111      *
2112      * @see #generateKeyPair
2113      */
2114     public static final int ID_TYPE_MEID = 8;
2115 
2116     /**
2117      * Service-specific error code for {@link #generateKeyPair}:
2118      * Indicates the call has failed due to StrongBox unavailability.
2119      * @hide
2120      */
2121     public static final int KEY_GEN_STRONGBOX_UNAVAILABLE = 1;
2122 
2123     /**
2124      * Specifies that the calling app should be granted access to the installed credentials
2125      * immediately. Otherwise, access to the credentials will be gated by user approval.
2126      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
2127      *
2128      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
2129      */
2130     public static final int INSTALLKEY_REQUEST_CREDENTIALS_ACCESS = 1;
2131 
2132     /**
2133      * Specifies that a user can select the key via the Certificate Selection prompt.
2134      * If this flag is not set when calling {@link #installKeyPair}, the key can only be granted
2135      * access by implementing {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
2136      * For use with {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)}
2137      *
2138      * @see #installKeyPair(ComponentName, PrivateKey, Certificate[], String, int)
2139      */
2140     public static final int INSTALLKEY_SET_USER_SELECTABLE = 2;
2141 
2142     /**
2143      * Broadcast action: sent when the profile owner is set, changed or cleared.
2144      *
2145      * This broadcast is sent only to the user managed by the new profile owner.
2146      * @see DevicePolicyManager#transferOwnership(ComponentName, ComponentName, PersistableBundle)
2147      */
2148     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
2149     public static final String ACTION_PROFILE_OWNER_CHANGED =
2150             "android.app.action.PROFILE_OWNER_CHANGED";
2151 
2152     /** @hide */
2153     @Retention(RetentionPolicy.SOURCE)
2154     @IntDef(flag = true, prefix = {"PRIVATE_DNS_MODE_"}, value = {
2155             PRIVATE_DNS_MODE_UNKNOWN,
2156             PRIVATE_DNS_MODE_OFF,
2157             PRIVATE_DNS_MODE_OPPORTUNISTIC,
2158             PRIVATE_DNS_MODE_PROVIDER_HOSTNAME
2159     })
2160     public @interface PrivateDnsMode {}
2161 
2162     /**
2163      * Specifies that the Private DNS setting is in an unknown state.
2164      */
2165     public static final int PRIVATE_DNS_MODE_UNKNOWN = 0;
2166 
2167     /**
2168      * Specifies that Private DNS was turned off completely.
2169      */
2170     public static final int PRIVATE_DNS_MODE_OFF = 1;
2171 
2172     /**
2173      * Specifies that the device owner requested opportunistic DNS over TLS
2174      */
2175     public static final int PRIVATE_DNS_MODE_OPPORTUNISTIC = 2;
2176 
2177     /**
2178      * Specifies that the device owner configured a specific host to use for Private DNS.
2179      */
2180     public static final int PRIVATE_DNS_MODE_PROVIDER_HOSTNAME = 3;
2181 
2182     /**
2183      * Callback used in {@link #installSystemUpdate} to indicate that there was an error while
2184      * trying to install an update.
2185      */
2186     public abstract static class InstallSystemUpdateCallback {
2187         /** Represents an unknown error while trying to install an update. */
2188         public static final int UPDATE_ERROR_UNKNOWN = 1;
2189 
2190         /** Represents the update file being intended for different OS version. */
2191         public static final int UPDATE_ERROR_INCORRECT_OS_VERSION = 2;
2192 
2193         /**
2194          * Represents the update file being wrong; e.g. payloads are mismatched, or the wrong
2195          * compression method is used.
2196          */
2197         public static final int UPDATE_ERROR_UPDATE_FILE_INVALID = 3;
2198 
2199         /** Represents that the file could not be found. */
2200         public static final int UPDATE_ERROR_FILE_NOT_FOUND = 4;
2201 
2202         /** Represents the battery being too low to apply an update. */
2203         public static final int UPDATE_ERROR_BATTERY_LOW = 5;
2204 
2205         /**
2206          * Method invoked when there was an error while installing an update.
2207          *
2208          * <p>The given error message is not intended to be user-facing. It is intended to be
2209          * reported back to the IT admin to be read.
2210          */
onInstallUpdateError( @nstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage)2211         public void onInstallUpdateError(
2212                 @InstallUpdateCallbackErrorConstants int errorCode, @NonNull String errorMessage) {
2213         }
2214     }
2215 
2216     /**
2217      * @hide
2218      */
2219     @IntDef(prefix = { "UPDATE_ERROR_" }, value = {
2220             InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN,
2221             InstallSystemUpdateCallback.UPDATE_ERROR_INCORRECT_OS_VERSION,
2222             InstallSystemUpdateCallback.UPDATE_ERROR_UPDATE_FILE_INVALID,
2223             InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
2224             InstallSystemUpdateCallback.UPDATE_ERROR_BATTERY_LOW
2225     })
2226     @Retention(RetentionPolicy.SOURCE)
2227     public @interface InstallUpdateCallbackErrorConstants {}
2228 
2229     /**
2230      * The selected mode has been set successfully. If the mode is
2231      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} then it implies the supplied host is valid
2232      * and reachable.
2233      */
2234     public static final int PRIVATE_DNS_SET_NO_ERROR = 0;
2235 
2236     /**
2237      * If the {@code privateDnsHost} provided was of a valid hostname but that host was found
2238      * to not support DNS-over-TLS.
2239      */
2240     public static final int PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING = 1;
2241 
2242     /**
2243      * General failure to set the Private DNS mode, not due to one of the reasons listed above.
2244      */
2245     public static final int PRIVATE_DNS_SET_ERROR_FAILURE_SETTING = 2;
2246 
2247     /**
2248      * @hide
2249      */
2250     @IntDef(prefix = {"PRIVATE_DNS_SET_"}, value = {
2251             PRIVATE_DNS_SET_NO_ERROR,
2252             PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING,
2253             PRIVATE_DNS_SET_ERROR_FAILURE_SETTING
2254     })
2255     @Retention(RetentionPolicy.SOURCE)
2256     public @interface PrivateDnsModeErrorCodes {}
2257 
2258     /**
2259      * Activity action: Starts the administrator to get the mode for the provisioning.
2260      * This intent may contain the following extras:
2261      * <ul>
2262      *     <li>{@link #EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE}</li>
2263      *     <li>{@link #EXTRA_PROVISIONING_IMEI}</li>
2264      *     <li>{@link #EXTRA_PROVISIONING_SERIAL_NUMBER}</li>
2265      * </ul>
2266      *
2267      * <p>The target activity should return one of the following values in
2268      * {@link #EXTRA_PROVISIONING_MODE} as result:
2269      * <ul>
2270      *     <li>{@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}</li>
2271      *     <li>{@link #PROVISIONING_MODE_MANAGED_PROFILE}</li>
2272      * </ul>
2273      *
2274      * <p>If performing fully-managed device provisioning and the admin app desires to show its
2275      * own education screens, the target activity can additionally return
2276      * {@link #EXTRA_PROVISIONING_SKIP_EDUCATION_SCREENS} set to <code>true</code>.
2277      *
2278      * <p>The target activity may also return the account that needs to be migrated from primary
2279      * user to managed profile in case of a profile owner provisioning in
2280      * {@link #EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE} as result.
2281      */
2282     public static final String ACTION_GET_PROVISIONING_MODE =
2283             "android.app.action.GET_PROVISIONING_MODE";
2284 
2285     /**
2286      * A string extra holding the IMEI (International Mobile Equipment Identity) of the device.
2287      */
2288     public static final String EXTRA_PROVISIONING_IMEI = "android.app.extra.PROVISIONING_IMEI";
2289 
2290     /**
2291      * A string extra holding the serial number of the device.
2292      */
2293     public static final String EXTRA_PROVISIONING_SERIAL_NUMBER =
2294             "android.app.extra.PROVISIONING_SERIAL_NUMBER";
2295 
2296     /**
2297      * An intent extra holding the provisioning mode returned by the administrator.
2298      * The value for this extra should be one of the following:
2299      * <ul>
2300      *     <li>{@link #PROVISIONING_MODE_FULLY_MANAGED_DEVICE}</li>
2301      *     <li>{@link #PROVISIONING_MODE_MANAGED_PROFILE}</li>
2302      * </ul>
2303      */
2304     public static final String EXTRA_PROVISIONING_MODE =
2305             "android.app.extra.PROVISIONING_MODE";
2306 
2307     /**
2308      * The provisioning mode for fully managed device.
2309      */
2310     public static final int PROVISIONING_MODE_FULLY_MANAGED_DEVICE = 1;
2311 
2312     /**
2313      * The provisioning mode for managed profile.
2314      */
2315     public static final int PROVISIONING_MODE_MANAGED_PROFILE = 2;
2316 
2317     /**
2318      * Activity action: Starts the administrator to show policy compliance for the provisioning.
2319      */
2320     public static final String ACTION_ADMIN_POLICY_COMPLIANCE =
2321             "android.app.action.ADMIN_POLICY_COMPLIANCE";
2322 
2323     /**
2324      * Return true if the given administrator component is currently active (enabled) in the system.
2325      *
2326      * @param admin The administrator component to check for.
2327      * @return {@code true} if {@code admin} is currently enabled in the system, {@code false}
2328      *         otherwise
2329      */
isAdminActive(@onNull ComponentName admin)2330     public boolean isAdminActive(@NonNull ComponentName admin) {
2331         throwIfParentInstance("isAdminActive");
2332         return isAdminActiveAsUser(admin, myUserId());
2333     }
2334 
2335     /**
2336      * @see #isAdminActive(ComponentName)
2337      * @hide
2338      */
isAdminActiveAsUser(@onNull ComponentName admin, int userId)2339     public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) {
2340         if (mService != null) {
2341             try {
2342                 return mService.isAdminActive(admin, userId);
2343             } catch (RemoteException e) {
2344                 throw e.rethrowFromSystemServer();
2345             }
2346         }
2347         return false;
2348     }
2349 
2350     /**
2351      * Return true if the given administrator component is currently being removed
2352      * for the user.
2353      * @hide
2354      */
isRemovingAdmin(@onNull ComponentName admin, int userId)2355     public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) {
2356         if (mService != null) {
2357             try {
2358                 return mService.isRemovingAdmin(admin, userId);
2359             } catch (RemoteException e) {
2360                 throw e.rethrowFromSystemServer();
2361             }
2362         }
2363         return false;
2364     }
2365 
2366     /**
2367      * Return a list of all currently active device administrators' component
2368      * names.  If there are no administrators {@code null} may be
2369      * returned.
2370      */
getActiveAdmins()2371     public @Nullable List<ComponentName> getActiveAdmins() {
2372         throwIfParentInstance("getActiveAdmins");
2373         return getActiveAdminsAsUser(myUserId());
2374     }
2375 
2376     /**
2377      * @see #getActiveAdmins()
2378      * @hide
2379      */
2380     @UnsupportedAppUsage
getActiveAdminsAsUser(int userId)2381     public @Nullable List<ComponentName> getActiveAdminsAsUser(int userId) {
2382         if (mService != null) {
2383             try {
2384                 return mService.getActiveAdmins(userId);
2385             } catch (RemoteException e) {
2386                 throw e.rethrowFromSystemServer();
2387             }
2388         }
2389         return null;
2390     }
2391 
2392     /**
2393      * Used by package administration code to determine if a package can be stopped
2394      * or uninstalled.
2395      * @hide
2396      */
2397     @SystemApi
2398     @RequiresPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
packageHasActiveAdmins(String packageName)2399     public boolean packageHasActiveAdmins(String packageName) {
2400         return packageHasActiveAdmins(packageName, myUserId());
2401     }
2402 
2403     /**
2404      * Used by package administration code to determine if a package can be stopped
2405      * or uninstalled.
2406      * @hide
2407      */
2408     @UnsupportedAppUsage
packageHasActiveAdmins(String packageName, int userId)2409     public boolean packageHasActiveAdmins(String packageName, int userId) {
2410         if (mService != null) {
2411             try {
2412                 return mService.packageHasActiveAdmins(packageName, userId);
2413             } catch (RemoteException e) {
2414                 throw e.rethrowFromSystemServer();
2415             }
2416         }
2417         return false;
2418     }
2419 
2420     /**
2421      * Remove a current administration component.  This can only be called
2422      * by the application that owns the administration component; if you
2423      * try to remove someone else's component, a security exception will be
2424      * thrown.
2425      *
2426      * <p>Note that the operation is not synchronous and the admin might still be active (as
2427      * indicated by {@link #getActiveAdmins()}) by the time this method returns.
2428      *
2429      * @param admin The administration compononent to remove.
2430      * @throws SecurityException if the caller is not in the owner application of {@code admin}.
2431      */
removeActiveAdmin(@onNull ComponentName admin)2432     public void removeActiveAdmin(@NonNull ComponentName admin) {
2433         throwIfParentInstance("removeActiveAdmin");
2434         if (mService != null) {
2435             try {
2436                 mService.removeActiveAdmin(admin, myUserId());
2437             } catch (RemoteException e) {
2438                 throw e.rethrowFromSystemServer();
2439             }
2440         }
2441     }
2442 
2443     /**
2444      * Returns true if an administrator has been granted a particular device policy. This can be
2445      * used to check whether the administrator was activated under an earlier set of policies, but
2446      * requires additional policies after an upgrade.
2447      *
2448      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be an
2449      *            active administrator, or an exception will be thrown.
2450      * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}.
2451      * @throws SecurityException if {@code admin} is not an active administrator.
2452      */
hasGrantedPolicy(@onNull ComponentName admin, int usesPolicy)2453     public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) {
2454         throwIfParentInstance("hasGrantedPolicy");
2455         if (mService != null) {
2456             try {
2457                 return mService.hasGrantedPolicy(admin, usesPolicy, myUserId());
2458             } catch (RemoteException e) {
2459                 throw e.rethrowFromSystemServer();
2460             }
2461         }
2462         return false;
2463     }
2464 
2465     /**
2466      * Returns true if the Profile Challenge is available to use for the given profile user.
2467      *
2468      * @hide
2469      */
isSeparateProfileChallengeAllowed(int userHandle)2470     public boolean isSeparateProfileChallengeAllowed(int userHandle) {
2471         if (mService != null) {
2472             try {
2473                 return mService.isSeparateProfileChallengeAllowed(userHandle);
2474             } catch (RemoteException e) {
2475                 throw e.rethrowFromSystemServer();
2476             }
2477         }
2478         return false;
2479     }
2480 
2481     /**
2482      * Constant for {@link #setPasswordQuality}: the policy has no requirements
2483      * for the password.  Note that quality constants are ordered so that higher
2484      * values are more restrictive.
2485      */
2486     public static final int PASSWORD_QUALITY_UNSPECIFIED = 0;
2487 
2488     /**
2489      * Constant for {@link #setPasswordQuality}: the policy allows for low-security biometric
2490      * recognition technology.  This implies technologies that can recognize the identity of
2491      * an individual to about a 3 digit PIN (false detection is less than 1 in 1,000).
2492      * Note that quality constants are ordered so that higher values are more restrictive.
2493      */
2494     public static final int PASSWORD_QUALITY_BIOMETRIC_WEAK = 0x8000;
2495 
2496     /**
2497      * Constant for {@link #setPasswordQuality}: the policy requires some kind
2498      * of password or pattern, but doesn't care what it is. Note that quality constants
2499      * are ordered so that higher values are more restrictive.
2500      */
2501     public static final int PASSWORD_QUALITY_SOMETHING = 0x10000;
2502 
2503     /**
2504      * Constant for {@link #setPasswordQuality}: the user must have entered a
2505      * password containing at least numeric characters.  Note that quality
2506      * constants are ordered so that higher values are more restrictive.
2507      */
2508     public static final int PASSWORD_QUALITY_NUMERIC = 0x20000;
2509 
2510     /**
2511      * Constant for {@link #setPasswordQuality}: the user must have entered a
2512      * password containing at least numeric characters with no repeating (4444)
2513      * or ordered (1234, 4321, 2468) sequences.  Note that quality
2514      * constants are ordered so that higher values are more restrictive.
2515      */
2516     public static final int PASSWORD_QUALITY_NUMERIC_COMPLEX = 0x30000;
2517 
2518     /**
2519      * Constant for {@link #setPasswordQuality}: the user must have entered a
2520      * password containing at least alphabetic (or other symbol) characters.
2521      * Note that quality constants are ordered so that higher values are more
2522      * restrictive.
2523      */
2524     public static final int PASSWORD_QUALITY_ALPHABETIC = 0x40000;
2525 
2526     /**
2527      * Constant for {@link #setPasswordQuality}: the user must have entered a
2528      * password containing at least <em>both></em> numeric <em>and</em>
2529      * alphabetic (or other symbol) characters.  Note that quality constants are
2530      * ordered so that higher values are more restrictive.
2531      */
2532     public static final int PASSWORD_QUALITY_ALPHANUMERIC = 0x50000;
2533 
2534     /**
2535      * Constant for {@link #setPasswordQuality}: the user must have entered a
2536      * password containing at least a letter, a numerical digit and a special
2537      * symbol, by default. With this password quality, passwords can be
2538      * restricted to contain various sets of characters, like at least an
2539      * uppercase letter, etc. These are specified using various methods,
2540      * like {@link #setPasswordMinimumLowerCase(ComponentName, int)}. Note
2541      * that quality constants are ordered so that higher values are more
2542      * restrictive.
2543      */
2544     public static final int PASSWORD_QUALITY_COMPLEX = 0x60000;
2545 
2546     /**
2547      * Constant for {@link #setPasswordQuality}: the user is not allowed to
2548      * modify password. In case this password quality is set, the password is
2549      * managed by a profile owner. The profile owner can set any password,
2550      * as if {@link #PASSWORD_QUALITY_UNSPECIFIED} is used. Note
2551      * that quality constants are ordered so that higher values are more
2552      * restrictive. The value of {@link #PASSWORD_QUALITY_MANAGED} is
2553      * the highest.
2554      * @hide
2555      */
2556     public static final int PASSWORD_QUALITY_MANAGED = 0x80000;
2557 
2558     /**
2559      * @hide
2560      *
2561      * adb shell dpm set-{device,profile}-owner will normally not allow installing an owner to
2562      * a user with accounts.  {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED}
2563      * and {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} are the account features
2564      * used by authenticator to exempt their accounts from this:
2565      *
2566      * <ul>
2567      *     <li>Non-test-only DO/PO still can't be installed when there are accounts.
2568      *     <p>In order to make an apk test-only, add android:testOnly="true" to the
2569      *     &lt;application&gt; tag in the manifest.
2570      *
2571      *     <li>Test-only DO/PO can be installed even when there are accounts, as long as all the
2572      *     accounts have the {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} feature.
2573      *     Some authenticators claim to have any features, so to detect it, we also check
2574      *     {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED} and disallow installing
2575      *     if any of the accounts have it.
2576      * </ul>
2577      */
2578     @SystemApi
2579     @TestApi
2580     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED =
2581             "android.account.DEVICE_OR_PROFILE_OWNER_ALLOWED";
2582 
2583     /** @hide See {@link #ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED} */
2584     @SystemApi
2585     @TestApi
2586     public static final String ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED =
2587             "android.account.DEVICE_OR_PROFILE_OWNER_DISALLOWED";
2588 
2589     /**
2590      * Called by an application that is administering the device to set the password restrictions it
2591      * is imposing. After setting this, the user will not be able to enter a new password that is
2592      * not at least as restrictive as what has been set. Note that the current password will remain
2593      * until the user has set a new one, so the change does not take place immediately. To prompt
2594      * the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2595      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after calling this method.
2596      * <p>
2597      * Quality constants are ordered so that higher values are more restrictive; thus the highest
2598      * requested quality constant (between the policy set here, the user's preference, and any other
2599      * considerations) is the one that is in effect.
2600      * <p>
2601      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2602      * password is always treated as empty.
2603      * <p>
2604      * The calling device admin must have requested
2605      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2606      * not, a security exception will be thrown.
2607      * <p>
2608      * This method can be called on the {@link DevicePolicyManager} instance returned by
2609      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2610      * profile.
2611      *
2612      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2613      * @param quality The new desired quality. One of {@link #PASSWORD_QUALITY_UNSPECIFIED},
2614      *            {@link #PASSWORD_QUALITY_BIOMETRIC_WEAK},
2615      *            {@link #PASSWORD_QUALITY_SOMETHING}, {@link #PASSWORD_QUALITY_NUMERIC},
2616      *            {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
2617      *            {@link #PASSWORD_QUALITY_ALPHANUMERIC} or {@link #PASSWORD_QUALITY_COMPLEX}.
2618      * @throws SecurityException if {@code admin} is not an active administrator or if {@code admin}
2619      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2620      */
setPasswordQuality(@onNull ComponentName admin, int quality)2621     public void setPasswordQuality(@NonNull ComponentName admin, int quality) {
2622         if (mService != null) {
2623             try {
2624                 mService.setPasswordQuality(admin, quality, mParentInstance);
2625             } catch (RemoteException e) {
2626                 throw e.rethrowFromSystemServer();
2627             }
2628         }
2629     }
2630 
2631     /**
2632      * Retrieve the current minimum password quality for a particular admin or all admins that set
2633      * restrictions on this user and its participating profiles. Restrictions on profiles that have
2634      * a separate challenge are not taken into account.
2635      *
2636      * <p>This method can be called on the {@link DevicePolicyManager} instance
2637      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2638      * restrictions on the parent profile.
2639      *
2640      * <p>Note: on devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
2641      * the password is always treated as empty.
2642      *
2643      * @param admin The name of the admin component to check, or {@code null} to aggregate
2644      * all admins.
2645      */
getPasswordQuality(@ullable ComponentName admin)2646     public int getPasswordQuality(@Nullable ComponentName admin) {
2647         return getPasswordQuality(admin, myUserId());
2648     }
2649 
2650     /** @hide per-user version */
2651     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordQuality(@ullable ComponentName admin, int userHandle)2652     public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) {
2653         if (mService != null) {
2654             try {
2655                 return mService.getPasswordQuality(admin, userHandle, mParentInstance);
2656             } catch (RemoteException e) {
2657                 throw e.rethrowFromSystemServer();
2658             }
2659         }
2660         return PASSWORD_QUALITY_UNSPECIFIED;
2661     }
2662 
2663     /**
2664      * Called by an application that is administering the device to set the minimum allowed password
2665      * length. After setting this, the user will not be able to enter a new password that is not at
2666      * least as restrictive as what has been set. Note that the current password will remain until
2667      * the user has set a new one, so the change does not take place immediately. To prompt the user
2668      * for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2669      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2670      * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
2671      * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX}, {@link #PASSWORD_QUALITY_ALPHABETIC},
2672      * {@link #PASSWORD_QUALITY_ALPHANUMERIC}, or {@link #PASSWORD_QUALITY_COMPLEX} with
2673      * {@link #setPasswordQuality}.
2674      * <p>
2675      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2676      * password is always treated as empty.
2677      * <p>
2678      * The calling device admin must have requested
2679      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2680      * not, a security exception will be thrown.
2681      * <p>
2682      * This method can be called on the {@link DevicePolicyManager} instance returned by
2683      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2684      * profile.
2685      *
2686      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2687      * @param length The new desired minimum password length. A value of 0 means there is no
2688      *            restriction.
2689      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2690      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2691      */
setPasswordMinimumLength(@onNull ComponentName admin, int length)2692     public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) {
2693         if (mService != null) {
2694             try {
2695                 mService.setPasswordMinimumLength(admin, length, mParentInstance);
2696             } catch (RemoteException e) {
2697                 throw e.rethrowFromSystemServer();
2698             }
2699         }
2700     }
2701 
2702     /**
2703      * Retrieve the current minimum password length for a particular admin or all admins that set
2704      * restrictions on this user and its participating profiles. Restrictions on profiles that have
2705      * a separate challenge are not taken into account.
2706      *
2707      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2708      * password is always treated as empty.
2709      *
2710      * <p>This method can be called on the {@link DevicePolicyManager} instance
2711      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2712      * restrictions on the parent profile.
2713      *
2714      * @param admin The name of the admin component to check, or {@code null} to aggregate
2715      * all admins.
2716      */
getPasswordMinimumLength(@ullable ComponentName admin)2717     public int getPasswordMinimumLength(@Nullable ComponentName admin) {
2718         return getPasswordMinimumLength(admin, myUserId());
2719     }
2720 
2721     /** @hide per-user version */
2722     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLength(@ullable ComponentName admin, int userHandle)2723     public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) {
2724         if (mService != null) {
2725             try {
2726                 return mService.getPasswordMinimumLength(admin, userHandle, mParentInstance);
2727             } catch (RemoteException e) {
2728                 throw e.rethrowFromSystemServer();
2729             }
2730         }
2731         return 0;
2732     }
2733 
2734     /**
2735      * Called by an application that is administering the device to set the minimum number of upper
2736      * case letters required in the password. After setting this, the user will not be able to enter
2737      * a new password that is not at least as restrictive as what has been set. Note that the
2738      * current password will remain until the user has set a new one, so the change does not take
2739      * place immediately. To prompt the user for a new password, use
2740      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2741      * setting this value. This constraint is only imposed if the administrator has also requested
2742      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2743      * <p>
2744      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2745      * password is always treated as empty.
2746      * <p>
2747      * The calling device admin must have requested
2748      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2749      * not, a security exception will be thrown.
2750      * <p>
2751      * This method can be called on the {@link DevicePolicyManager} instance returned by
2752      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2753      * profile.
2754      *
2755      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2756      * @param length The new desired minimum number of upper case letters required in the password.
2757      *            A value of 0 means there is no restriction.
2758      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2759      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2760      */
setPasswordMinimumUpperCase(@onNull ComponentName admin, int length)2761     public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) {
2762         if (mService != null) {
2763             try {
2764                 mService.setPasswordMinimumUpperCase(admin, length, mParentInstance);
2765             } catch (RemoteException e) {
2766                 throw e.rethrowFromSystemServer();
2767             }
2768         }
2769     }
2770 
2771     /**
2772      * Retrieve the current number of upper case letters required in the password
2773      * for a particular admin or all admins that set restrictions on this user and
2774      * its participating profiles. Restrictions on profiles that have a separate challenge
2775      * are not taken into account.
2776      * This is the same value as set by
2777      * {@link #setPasswordMinimumUpperCase(ComponentName, int)}
2778      * and only applies when the password quality is
2779      * {@link #PASSWORD_QUALITY_COMPLEX}.
2780      *
2781      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2782      * password is always treated as empty.
2783      *
2784      * <p>This method can be called on the {@link DevicePolicyManager} instance
2785      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2786      * restrictions on the parent profile.
2787      *
2788      * @param admin The name of the admin component to check, or {@code null} to
2789      *            aggregate all admins.
2790      * @return The minimum number of upper case letters required in the
2791      *         password.
2792      */
getPasswordMinimumUpperCase(@ullable ComponentName admin)2793     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) {
2794         return getPasswordMinimumUpperCase(admin, myUserId());
2795     }
2796 
2797     /** @hide per-user version */
2798     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumUpperCase(@ullable ComponentName admin, int userHandle)2799     public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) {
2800         if (mService != null) {
2801             try {
2802                 return mService.getPasswordMinimumUpperCase(admin, userHandle, mParentInstance);
2803             } catch (RemoteException e) {
2804                 throw e.rethrowFromSystemServer();
2805             }
2806         }
2807         return 0;
2808     }
2809 
2810     /**
2811      * Called by an application that is administering the device to set the minimum number of lower
2812      * case letters required in the password. After setting this, the user will not be able to enter
2813      * a new password that is not at least as restrictive as what has been set. Note that the
2814      * current password will remain until the user has set a new one, so the change does not take
2815      * place immediately. To prompt the user for a new password, use
2816      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2817      * setting this value. This constraint is only imposed if the administrator has also requested
2818      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
2819      * <p>
2820      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2821      * password is always treated as empty.
2822      * <p>
2823      * The calling device admin must have requested
2824      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2825      * not, a security exception will be thrown.
2826      * <p>
2827      * This method can be called on the {@link DevicePolicyManager} instance returned by
2828      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2829      * profile.
2830      *
2831      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2832      * @param length The new desired minimum number of lower case letters required in the password.
2833      *            A value of 0 means there is no restriction.
2834      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2835      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2836      */
setPasswordMinimumLowerCase(@onNull ComponentName admin, int length)2837     public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) {
2838         if (mService != null) {
2839             try {
2840                 mService.setPasswordMinimumLowerCase(admin, length, mParentInstance);
2841             } catch (RemoteException e) {
2842                 throw e.rethrowFromSystemServer();
2843             }
2844         }
2845     }
2846 
2847     /**
2848      * Retrieve the current number of lower case letters required in the password
2849      * for a particular admin or all admins that set restrictions on this user
2850      * and its participating profiles. Restrictions on profiles that have
2851      * a separate challenge are not taken into account.
2852      * This is the same value as set by
2853      * {@link #setPasswordMinimumLowerCase(ComponentName, int)}
2854      * and only applies when the password quality is
2855      * {@link #PASSWORD_QUALITY_COMPLEX}.
2856      *
2857      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2858      * password is always treated as empty.
2859      *
2860      * <p>This method can be called on the {@link DevicePolicyManager} instance
2861      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2862      * restrictions on the parent profile.
2863      *
2864      * @param admin The name of the admin component to check, or {@code null} to
2865      *            aggregate all admins.
2866      * @return The minimum number of lower case letters required in the
2867      *         password.
2868      */
getPasswordMinimumLowerCase(@ullable ComponentName admin)2869     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) {
2870         return getPasswordMinimumLowerCase(admin, myUserId());
2871     }
2872 
2873     /** @hide per-user version */
2874     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLowerCase(@ullable ComponentName admin, int userHandle)2875     public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) {
2876         if (mService != null) {
2877             try {
2878                 return mService.getPasswordMinimumLowerCase(admin, userHandle, mParentInstance);
2879             } catch (RemoteException e) {
2880                 throw e.rethrowFromSystemServer();
2881             }
2882         }
2883         return 0;
2884     }
2885 
2886     /**
2887      * Called by an application that is administering the device to set the minimum number of
2888      * letters required in the password. After setting this, the user will not be able to enter a
2889      * new password that is not at least as restrictive as what has been set. Note that the current
2890      * password will remain until the user has set a new one, so the change does not take place
2891      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
2892      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
2893      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
2894      * {@link #setPasswordQuality}. The default value is 1.
2895      * <p>
2896      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2897      * password is always treated as empty.
2898      * <p>
2899      * The calling device admin must have requested
2900      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2901      * not, a security exception will be thrown.
2902      * <p>
2903      * This method can be called on the {@link DevicePolicyManager} instance returned by
2904      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2905      * profile.
2906      *
2907      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2908      * @param length The new desired minimum number of letters required in the password. A value of
2909      *            0 means there is no restriction.
2910      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2911      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2912      */
setPasswordMinimumLetters(@onNull ComponentName admin, int length)2913     public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) {
2914         if (mService != null) {
2915             try {
2916                 mService.setPasswordMinimumLetters(admin, length, mParentInstance);
2917             } catch (RemoteException e) {
2918                 throw e.rethrowFromSystemServer();
2919             }
2920         }
2921     }
2922 
2923     /**
2924      * Retrieve the current number of letters required in the password
2925      * for a particular admin or all admins that set restrictions on this user
2926      * and its participating profiles. Restrictions on profiles that have
2927      * a separate challenge are not taken into account.
2928      * This is the same value as set by
2929      * {@link #setPasswordMinimumLetters(ComponentName, int)}
2930      * and only applies when the password quality is
2931      * {@link #PASSWORD_QUALITY_COMPLEX}.
2932      *
2933      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2934      * password is always treated as empty.
2935      *
2936      * <p>This method can be called on the {@link DevicePolicyManager} instance
2937      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
2938      * restrictions on the parent profile.
2939      *
2940      * @param admin The name of the admin component to check, or {@code null} to
2941      *            aggregate all admins.
2942      * @return The minimum number of letters required in the password.
2943      */
getPasswordMinimumLetters(@ullable ComponentName admin)2944     public int getPasswordMinimumLetters(@Nullable ComponentName admin) {
2945         return getPasswordMinimumLetters(admin, myUserId());
2946     }
2947 
2948     /** @hide per-user version */
2949     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumLetters(@ullable ComponentName admin, int userHandle)2950     public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) {
2951         if (mService != null) {
2952             try {
2953                 return mService.getPasswordMinimumLetters(admin, userHandle, mParentInstance);
2954             } catch (RemoteException e) {
2955                 throw e.rethrowFromSystemServer();
2956             }
2957         }
2958         return 0;
2959     }
2960 
2961     /**
2962      * Called by an application that is administering the device to set the minimum number of
2963      * numerical digits required in the password. After setting this, the user will not be able to
2964      * enter a new password that is not at least as restrictive as what has been set. Note that the
2965      * current password will remain until the user has set a new one, so the change does not take
2966      * place immediately. To prompt the user for a new password, use
2967      * {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
2968      * setting this value. This constraint is only imposed if the administrator has also requested
2969      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 1.
2970      * <p>
2971      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
2972      * password is always treated as empty.
2973      * <p>
2974      * The calling device admin must have requested
2975      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
2976      * not, a security exception will be thrown.
2977      * <p>
2978      * This method can be called on the {@link DevicePolicyManager} instance returned by
2979      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
2980      * profile.
2981      *
2982      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
2983      * @param length The new desired minimum number of numerical digits required in the password. A
2984      *            value of 0 means there is no restriction.
2985      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
2986      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
2987      */
setPasswordMinimumNumeric(@onNull ComponentName admin, int length)2988     public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) {
2989         if (mService != null) {
2990             try {
2991                 mService.setPasswordMinimumNumeric(admin, length, mParentInstance);
2992             } catch (RemoteException e) {
2993                 throw e.rethrowFromSystemServer();
2994             }
2995         }
2996     }
2997 
2998     /**
2999      * Retrieve the current number of numerical digits required in the password
3000      * for a particular admin or all admins that set restrictions on this user
3001      * and its participating profiles. Restrictions on profiles that have
3002      * a separate challenge are not taken into account.
3003      * This is the same value as set by
3004      * {@link #setPasswordMinimumNumeric(ComponentName, int)}
3005      * and only applies when the password quality is
3006      * {@link #PASSWORD_QUALITY_COMPLEX}.
3007      *
3008      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3009      * password is always treated as empty.
3010      *
3011      * <p>This method can be called on the {@link DevicePolicyManager} instance
3012      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3013      * restrictions on the parent profile.
3014      *
3015      * @param admin The name of the admin component to check, or {@code null} to
3016      *            aggregate all admins.
3017      * @return The minimum number of numerical digits required in the password.
3018      */
getPasswordMinimumNumeric(@ullable ComponentName admin)3019     public int getPasswordMinimumNumeric(@Nullable ComponentName admin) {
3020         return getPasswordMinimumNumeric(admin, myUserId());
3021     }
3022 
3023     /** @hide per-user version */
3024     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumNumeric(@ullable ComponentName admin, int userHandle)3025     public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) {
3026         if (mService != null) {
3027             try {
3028                 return mService.getPasswordMinimumNumeric(admin, userHandle, mParentInstance);
3029             } catch (RemoteException e) {
3030                 throw e.rethrowFromSystemServer();
3031             }
3032         }
3033         return 0;
3034     }
3035 
3036     /**
3037      * Called by an application that is administering the device to set the minimum number of
3038      * symbols required in the password. After setting this, the user will not be able to enter a
3039      * new password that is not at least as restrictive as what has been set. Note that the current
3040      * password will remain until the user has set a new one, so the change does not take place
3041      * immediately. To prompt the user for a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
3042      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
3043      * only imposed if the administrator has also requested {@link #PASSWORD_QUALITY_COMPLEX} with
3044      * {@link #setPasswordQuality}. The default value is 1.
3045      * <p>
3046      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3047      * password is always treated as empty.
3048      * <p>
3049      * The calling device admin must have requested
3050      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3051      * not, a security exception will be thrown.
3052      * <p>
3053      * This method can be called on the {@link DevicePolicyManager} instance returned by
3054      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3055      * profile.
3056      *
3057      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3058      * @param length The new desired minimum number of symbols required in the password. A value of
3059      *            0 means there is no restriction.
3060      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3061      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3062      */
setPasswordMinimumSymbols(@onNull ComponentName admin, int length)3063     public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) {
3064         if (mService != null) {
3065             try {
3066                 mService.setPasswordMinimumSymbols(admin, length, mParentInstance);
3067             } catch (RemoteException e) {
3068                 throw e.rethrowFromSystemServer();
3069             }
3070         }
3071     }
3072 
3073     /**
3074      * Retrieve the current number of symbols required in the password
3075      * for a particular admin or all admins that set restrictions on this user
3076      * and its participating profiles. Restrictions on profiles that have
3077      * a separate challenge are not taken into account. This is the same value as
3078      * set by {@link #setPasswordMinimumSymbols(ComponentName, int)}
3079      * and only applies when the password quality is
3080      * {@link #PASSWORD_QUALITY_COMPLEX}.
3081      *
3082      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3083      * password is always treated as empty.
3084      *
3085      * <p>This method can be called on the {@link DevicePolicyManager} instance
3086      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3087      * restrictions on the parent profile.
3088      *
3089      * @param admin The name of the admin component to check, or {@code null} to
3090      *            aggregate all admins.
3091      * @return The minimum number of symbols required in the password.
3092      */
getPasswordMinimumSymbols(@ullable ComponentName admin)3093     public int getPasswordMinimumSymbols(@Nullable ComponentName admin) {
3094         return getPasswordMinimumSymbols(admin, myUserId());
3095     }
3096 
3097     /** @hide per-user version */
3098     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumSymbols(@ullable ComponentName admin, int userHandle)3099     public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) {
3100         if (mService != null) {
3101             try {
3102                 return mService.getPasswordMinimumSymbols(admin, userHandle, mParentInstance);
3103             } catch (RemoteException e) {
3104                 throw e.rethrowFromSystemServer();
3105             }
3106         }
3107         return 0;
3108     }
3109 
3110     /**
3111      * Called by an application that is administering the device to set the minimum number of
3112      * non-letter characters (numerical digits or symbols) required in the password. After setting
3113      * this, the user will not be able to enter a new password that is not at least as restrictive
3114      * as what has been set. Note that the current password will remain until the user has set a new
3115      * one, so the change does not take place immediately. To prompt the user for a new password,
3116      * use {@link #ACTION_SET_NEW_PASSWORD} or {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after
3117      * setting this value. This constraint is only imposed if the administrator has also requested
3118      * {@link #PASSWORD_QUALITY_COMPLEX} with {@link #setPasswordQuality}. The default value is 0.
3119      * <p>
3120      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3121      * password is always treated as empty.
3122      * <p>
3123      * The calling device admin must have requested
3124      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3125      * not, a security exception will be thrown.
3126      * <p>
3127      * This method can be called on the {@link DevicePolicyManager} instance returned by
3128      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3129      * profile.
3130      *
3131      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3132      * @param length The new desired minimum number of letters required in the password. A value of
3133      *            0 means there is no restriction.
3134      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3135      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3136      */
setPasswordMinimumNonLetter(@onNull ComponentName admin, int length)3137     public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) {
3138         if (mService != null) {
3139             try {
3140                 mService.setPasswordMinimumNonLetter(admin, length, mParentInstance);
3141             } catch (RemoteException e) {
3142                 throw e.rethrowFromSystemServer();
3143             }
3144         }
3145     }
3146 
3147     /**
3148      * Retrieve the current number of non-letter characters required in the password
3149      * for a particular admin or all admins that set restrictions on this user
3150      * and its participating profiles. Restrictions on profiles that have
3151      * a separate challenge are not taken into account.
3152      * This is the same value as set by
3153      * {@link #setPasswordMinimumNonLetter(ComponentName, int)}
3154      * and only applies when the password quality is
3155      * {@link #PASSWORD_QUALITY_COMPLEX}.
3156      *
3157      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3158      * password is always treated as empty.
3159      *
3160      * <p>This method can be called on the {@link DevicePolicyManager} instance
3161      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3162      * restrictions on the parent profile.
3163      *
3164      * @param admin The name of the admin component to check, or {@code null} to
3165      *            aggregate all admins.
3166      * @return The minimum number of letters required in the password.
3167      */
getPasswordMinimumNonLetter(@ullable ComponentName admin)3168     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) {
3169         return getPasswordMinimumNonLetter(admin, myUserId());
3170     }
3171 
3172     /** @hide per-user version */
3173     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
getPasswordMinimumNonLetter(@ullable ComponentName admin, int userHandle)3174     public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) {
3175         if (mService != null) {
3176             try {
3177                 return mService.getPasswordMinimumNonLetter(admin, userHandle, mParentInstance);
3178             } catch (RemoteException e) {
3179                 throw e.rethrowFromSystemServer();
3180             }
3181         }
3182         return 0;
3183     }
3184 
3185     /**
3186      * Called by an application that is administering the device to set the length of the password
3187      * history. After setting this, the user will not be able to enter a new password that is the
3188      * same as any password in the history. Note that the current password will remain until the
3189      * user has set a new one, so the change does not take place immediately. To prompt the user for
3190      * a new password, use {@link #ACTION_SET_NEW_PASSWORD} or
3191      * {@link #ACTION_SET_NEW_PARENT_PROFILE_PASSWORD} after setting this value. This constraint is
3192      * only imposed if the administrator has also requested either {@link #PASSWORD_QUALITY_NUMERIC}
3193      * , {@link #PASSWORD_QUALITY_NUMERIC_COMPLEX} {@link #PASSWORD_QUALITY_ALPHABETIC}, or
3194      * {@link #PASSWORD_QUALITY_ALPHANUMERIC} with {@link #setPasswordQuality}.
3195      * <p>
3196      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3197      * password history length is always 0.
3198      * <p>
3199      * The calling device admin must have requested
3200      * {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} to be able to call this method; if it has
3201      * not, a security exception will be thrown.
3202      * <p>
3203      * This method can be called on the {@link DevicePolicyManager} instance returned by
3204      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3205      * profile.
3206      *
3207      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3208      * @param length The new desired length of password history. A value of 0 means there is no
3209      *            restriction.
3210      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3211      *             does not use {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3212      */
3213     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setPasswordHistoryLength(@onNull ComponentName admin, int length)3214     public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) {
3215         if (mService != null) {
3216             try {
3217                 mService.setPasswordHistoryLength(admin, length, mParentInstance);
3218             } catch (RemoteException e) {
3219                 throw e.rethrowFromSystemServer();
3220             }
3221         }
3222     }
3223 
3224     /**
3225      * Called by a device admin to set the password expiration timeout. Calling this method will
3226      * restart the countdown for password expiration for the given admin, as will changing the
3227      * device password (for all admins).
3228      * <p>
3229      * The provided timeout is the time delta in ms and will be added to the current time. For
3230      * example, to have the password expire 5 days from now, timeout would be 5 * 86400 * 1000 =
3231      * 432000000 ms for timeout.
3232      * <p>
3233      * To disable password expiration, a value of 0 may be used for timeout.
3234      * <p>
3235      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3236      * password expiration is always disabled.
3237      * <p>
3238      * The calling device admin must have requested
3239      * {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD} to be able to call this method; if it has
3240      * not, a security exception will be thrown.
3241      * <p>
3242      * Note that setting the password will automatically reset the expiration time for all active
3243      * admins. Active admins do not need to explicitly call this method in that case.
3244      * <p>
3245      * This method can be called on the {@link DevicePolicyManager} instance returned by
3246      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3247      * profile.
3248      *
3249      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3250      * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 means
3251      *            there is no restriction (unlimited).
3252      * @throws SecurityException if {@code admin} is not an active administrator or {@code admin}
3253      *             does not use {@link DeviceAdminInfo#USES_POLICY_EXPIRE_PASSWORD}
3254      */
3255     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setPasswordExpirationTimeout(@onNull ComponentName admin, long timeout)3256     public void setPasswordExpirationTimeout(@NonNull ComponentName admin, long timeout) {
3257         if (mService != null) {
3258             try {
3259                 mService.setPasswordExpirationTimeout(admin, timeout, mParentInstance);
3260             } catch (RemoteException e) {
3261                 throw e.rethrowFromSystemServer();
3262             }
3263         }
3264     }
3265 
3266     /**
3267      * Get the password expiration timeout for the given admin. The expiration timeout is the
3268      * recurring expiration timeout provided in the call to
3269      * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the
3270      * aggregate of all participating policy administrators if {@code admin} is null. Admins that
3271      * have set restrictions on profiles that have a separate challenge are not taken into account.
3272      *
3273      * <p>This method can be called on the {@link DevicePolicyManager} instance
3274      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3275      * restrictions on the parent profile.
3276      *
3277      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3278      * password expiration is always disabled and this method always returns 0.
3279      *
3280      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
3281      * @return The timeout for the given admin or the minimum of all timeouts
3282      */
3283     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordExpirationTimeout(@ullable ComponentName admin)3284     public long getPasswordExpirationTimeout(@Nullable ComponentName admin) {
3285         if (mService != null) {
3286             try {
3287                 return mService.getPasswordExpirationTimeout(admin, myUserId(), mParentInstance);
3288             } catch (RemoteException e) {
3289                 throw e.rethrowFromSystemServer();
3290             }
3291         }
3292         return 0;
3293     }
3294 
3295     /**
3296      * Get the current password expiration time for a particular admin or all admins that set
3297      * restrictions on this user and its participating profiles. Restrictions on profiles that have
3298      * a separate challenge are not taken into account. If admin is {@code null}, then a composite
3299      * of all expiration times is returned - which will be the minimum of all of them.
3300      *
3301      * <p>This method can be called on the {@link DevicePolicyManager} instance
3302      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3303      * the password expiration for the parent profile.
3304      *
3305      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3306      * password expiration is always disabled and this method always returns 0.
3307      *
3308      * @param admin The name of the admin component to check, or {@code null} to aggregate all admins.
3309      * @return The password expiration time, in milliseconds since epoch.
3310      */
3311     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordExpiration(@ullable ComponentName admin)3312     public long getPasswordExpiration(@Nullable ComponentName admin) {
3313         if (mService != null) {
3314             try {
3315                 return mService.getPasswordExpiration(admin, myUserId(), mParentInstance);
3316             } catch (RemoteException e) {
3317                 throw e.rethrowFromSystemServer();
3318             }
3319         }
3320         return 0;
3321     }
3322 
3323     /**
3324      * Retrieve the current password history length for a particular admin or all admins that
3325      * set restrictions on this user and its participating profiles. Restrictions on profiles that
3326      * have a separate challenge are not taken into account.
3327      *
3328      * <p>This method can be called on the {@link DevicePolicyManager} instance
3329      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3330      * restrictions on the parent profile.
3331      *
3332      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3333      * password history length is always 0.
3334      *
3335      * @param admin The name of the admin component to check, or {@code null} to aggregate
3336      * all admins.
3337      * @return The length of the password history
3338      */
3339     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordHistoryLength(@ullable ComponentName admin)3340     public int getPasswordHistoryLength(@Nullable ComponentName admin) {
3341         return getPasswordHistoryLength(admin, myUserId());
3342     }
3343 
3344     /** @hide per-user version */
3345     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
3346     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getPasswordHistoryLength(@ullable ComponentName admin, int userHandle)3347     public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) {
3348         if (mService != null) {
3349             try {
3350                 return mService.getPasswordHistoryLength(admin, userHandle, mParentInstance);
3351             } catch (RemoteException e) {
3352                 throw e.rethrowFromSystemServer();
3353             }
3354         }
3355         return 0;
3356     }
3357 
3358     /**
3359      * Return the maximum password length that the device supports for a
3360      * particular password quality.
3361      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3362      * password is always empty and this method always returns 0.
3363      * @param quality The quality being interrogated.
3364      * @return Returns the maximum length that the user can enter.
3365      */
getPasswordMaximumLength(int quality)3366     public int getPasswordMaximumLength(int quality) {
3367         PackageManager pm = mContext.getPackageManager();
3368         if (!pm.hasSystemFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)) {
3369             return 0;
3370         }
3371         // Kind-of arbitrary.
3372         return 16;
3373     }
3374 
3375     /**
3376      * Determines whether the calling user's current password meets policy requirements
3377      * (e.g. quality, minimum length). The user must be unlocked to perform this check.
3378      *
3379      * <p>Policy requirements which affect this check can be set by admins of the user, but also
3380      * by the admin of a managed profile associated with the calling user (when the managed profile
3381      * doesn't have a separate work challenge). When a managed profile has a separate work
3382      * challenge, its policy requirements only affect the managed profile.
3383      *
3384      * <p>Depending on the user, this method checks the policy requirement against one of the
3385      * following passwords:
3386      * <ul>
3387      * <li>For the primary user or secondary users: the personal keyguard password.
3388      * <li>For managed profiles: a work challenge if set, otherwise the parent user's personal
3389      *     keyguard password.
3390      * <ul/>
3391      * In other words, it's always checking the requirement against the password that is protecting
3392      * the calling user.
3393      *
3394      * <p>Note that this method considers all policy requirements targeting the password in
3395      * question. For example a profile owner might set a requirement on the parent profile i.e.
3396      * personal keyguard but not on the profile itself. When the device has a weak personal keyguard
3397      * password and no separate work challenge, calling this method will return {@code false}
3398      * despite the profile owner not setting a policy on the profile itself. This is because the
3399      * profile's current password is the personal keyguard password, and it does not meet all policy
3400      * requirements.
3401      *
3402      * <p>Device admins must request {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD} before
3403      * calling this method. Note, this policy type is deprecated for device admins in Android 9.0
3404      * (API level 28) or higher.
3405      *
3406      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
3407      * {@link #getParentProfileInstance(ComponentName)} in order to determine if the password set on
3408      * the parent profile is sufficient.
3409      *
3410      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3411      * password is always treated as empty - i.e. this method will always return false on such
3412      * devices, provided any password requirements were set.
3413      *
3414      * @return {@code true} if the password meets the policy requirements, {@code false} otherwise
3415      * @throws SecurityException if the calling application isn't an active admin that uses
3416      *     {@link DeviceAdminInfo#USES_POLICY_LIMIT_PASSWORD}
3417      * @throws IllegalStateException if the user isn't unlocked
3418      */
isActivePasswordSufficient()3419     public boolean isActivePasswordSufficient() {
3420         if (mService != null) {
3421             try {
3422                 return mService.isActivePasswordSufficient(myUserId(), mParentInstance);
3423             } catch (RemoteException e) {
3424                 throw e.rethrowFromSystemServer();
3425             }
3426         }
3427         return false;
3428     }
3429 
3430     /**
3431      * Returns how complex the current user's screen lock is.
3432      *
3433      * <p>Note that when called from a profile which uses an unified challenge with its parent, the
3434      * screen lock complexity of the parent will be returned. However, this API does not support
3435      * explicitly querying the parent profile screen lock complexity via {@link
3436      * #getParentProfileInstance}.
3437      *
3438      * @throws IllegalStateException if the user is not unlocked.
3439      * @throws SecurityException if the calling application does not have the permission
3440      *                           {@link permission#REQUEST_PASSWORD_COMPLEXITY}
3441      */
3442     @PasswordComplexity
3443     @RequiresPermission(android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY)
getPasswordComplexity()3444     public int getPasswordComplexity() {
3445         throwIfParentInstance("getPasswordComplexity");
3446         if (mService == null) {
3447             return PASSWORD_COMPLEXITY_NONE;
3448         }
3449 
3450         try {
3451             return mService.getPasswordComplexity();
3452         } catch (RemoteException e) {
3453             throw e.rethrowFromSystemServer();
3454         }
3455     }
3456 
3457     /**
3458      * When called by a profile owner of a managed profile returns true if the profile uses unified
3459      * challenge with its parent user.
3460      *
3461      * <strong>Note</strong>: This method is not concerned with password quality and will return
3462      * false if the profile has empty password as a separate challenge.
3463      *
3464      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3465      * @throws SecurityException if {@code admin} is not a profile owner of a managed profile.
3466      * @see UserManager#DISALLOW_UNIFIED_PASSWORD
3467      */
isUsingUnifiedPassword(@onNull ComponentName admin)3468     public boolean isUsingUnifiedPassword(@NonNull ComponentName admin) {
3469         throwIfParentInstance("isUsingUnifiedPassword");
3470         if (mService != null) {
3471             try {
3472                 return mService.isUsingUnifiedPassword(admin);
3473             } catch (RemoteException e) {
3474                 throw e.rethrowFromSystemServer();
3475             }
3476         }
3477         return true;
3478     }
3479 
3480     /**
3481      * Determine whether the current profile password the user has set is sufficient
3482      * to meet the policy requirements (e.g. quality, minimum length) that have been
3483      * requested by the admins of the parent user and its profiles.
3484      *
3485      * @param userHandle the userId of the profile to check the password for.
3486      * @return Returns true if the password would meet the current requirements, else false.
3487      * @throws SecurityException if {@code userHandle} is not a managed profile.
3488      * @hide
3489      */
isProfileActivePasswordSufficientForParent(int userHandle)3490     public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3491         if (mService != null) {
3492             try {
3493                 return mService.isProfileActivePasswordSufficientForParent(userHandle);
3494             } catch (RemoteException e) {
3495                 throw e.rethrowFromSystemServer();
3496             }
3497         }
3498         return false;
3499     }
3500 
3501     /**
3502      * Retrieve the number of times the user has failed at entering a password since that last
3503      * successful password entry.
3504      * <p>
3505      * This method can be called on the {@link DevicePolicyManager} instance returned by
3506      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the number of failed
3507      * password attemts for the parent user.
3508      * <p>
3509      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
3510      * to be able to call this method; if it has not, a security exception will be thrown.
3511      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3512      * password is always empty and this method always returns 0.
3513      *
3514      * @return The number of times user has entered an incorrect password since the last correct
3515      *         password entry.
3516      * @throws SecurityException if the calling application does not own an active administrator
3517      *             that uses {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN}
3518      */
3519     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getCurrentFailedPasswordAttempts()3520     public int getCurrentFailedPasswordAttempts() {
3521         return getCurrentFailedPasswordAttempts(myUserId());
3522     }
3523 
3524     /**
3525      * Retrieve the number of times the given user has failed at entering a
3526      * password since that last successful password entry.
3527      *
3528      * <p>The calling device admin must have requested
3529      * {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} to be able to call this method; if it has
3530      * not and it is not the system uid, a security exception will be thrown.
3531      *
3532      * @hide
3533      */
3534     @UnsupportedAppUsage
getCurrentFailedPasswordAttempts(int userHandle)3535     public int getCurrentFailedPasswordAttempts(int userHandle) {
3536         if (mService != null) {
3537             try {
3538                 return mService.getCurrentFailedPasswordAttempts(userHandle, mParentInstance);
3539             } catch (RemoteException e) {
3540                 throw e.rethrowFromSystemServer();
3541             }
3542         }
3543         return -1;
3544     }
3545 
3546     /**
3547      * Queries whether {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT} flag is set.
3548      *
3549      * @return true if RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT flag is set.
3550      * @hide
3551      */
getDoNotAskCredentialsOnBoot()3552     public boolean getDoNotAskCredentialsOnBoot() {
3553         if (mService != null) {
3554             try {
3555                 return mService.getDoNotAskCredentialsOnBoot();
3556             } catch (RemoteException e) {
3557                 throw e.rethrowFromSystemServer();
3558             }
3559         }
3560         return false;
3561     }
3562 
3563     /**
3564      * Setting this to a value greater than zero enables a built-in policy that will perform a
3565      * device or profile wipe after too many incorrect device-unlock passwords have been entered.
3566      * This built-in policy combines watching for failed passwords and wiping the device, and
3567      * requires that you request both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
3568      * {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}}.
3569      * <p>
3570      * To implement any other policy (e.g. wiping data for a particular application only, erasing or
3571      * revoking credentials, or reporting the failure to a server), you should implement
3572      * {@link DeviceAdminReceiver#onPasswordFailed(Context, android.content.Intent)} instead. Do not
3573      * use this API, because if the maximum count is reached, the device or profile will be wiped
3574      * immediately, and your callback will not be invoked.
3575      * <p>
3576      * This method can be called on the {@link DevicePolicyManager} instance returned by
3577      * {@link #getParentProfileInstance(ComponentName)} in order to set a value on the parent
3578      * profile.
3579      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3580      * password is always empty and this method has no effect - i.e. the policy is not set.
3581      *
3582      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3583      * @param num The number of failed password attempts at which point the device or profile will
3584      *            be wiped.
3585      * @throws SecurityException if {@code admin} is not an active administrator or does not use
3586      *             both {@link DeviceAdminInfo#USES_POLICY_WATCH_LOGIN} and
3587      *             {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}.
3588      */
3589     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setMaximumFailedPasswordsForWipe(@onNull ComponentName admin, int num)3590     public void setMaximumFailedPasswordsForWipe(@NonNull ComponentName admin, int num) {
3591         if (mService != null) {
3592             try {
3593                 mService.setMaximumFailedPasswordsForWipe(admin, num, mParentInstance);
3594             } catch (RemoteException e) {
3595                 throw e.rethrowFromSystemServer();
3596             }
3597         }
3598     }
3599 
3600     /**
3601      * Retrieve the current maximum number of login attempts that are allowed before the device
3602      * or profile is wiped, for a particular admin or all admins that set restrictions on this user
3603      * and its participating profiles. Restrictions on profiles that have a separate challenge are
3604      * not taken into account.
3605      *
3606      * <p>This method can be called on the {@link DevicePolicyManager} instance
3607      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3608      * the value for the parent profile.
3609      *
3610      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3611      * password is always empty and this method returns a default value (0) indicating that the
3612      * policy is not set.
3613      *
3614      * @param admin The name of the admin component to check, or {@code null} to aggregate
3615      * all admins.
3616      */
3617     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin)3618     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) {
3619         return getMaximumFailedPasswordsForWipe(admin, myUserId());
3620     }
3621 
3622     /** @hide per-user version */
3623     @UnsupportedAppUsage
3624     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getMaximumFailedPasswordsForWipe(@ullable ComponentName admin, int userHandle)3625     public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) {
3626         if (mService != null) {
3627             try {
3628                 return mService.getMaximumFailedPasswordsForWipe(
3629                         admin, userHandle, mParentInstance);
3630             } catch (RemoteException e) {
3631                 throw e.rethrowFromSystemServer();
3632             }
3633         }
3634         return 0;
3635     }
3636 
3637     /**
3638      * Returns the profile with the smallest maximum failed passwords for wipe,
3639      * for the given user. So for primary user, it might return the primary or
3640      * a managed profile. For a secondary user, it would be the same as the
3641      * user passed in.
3642      * @hide Used only by Keyguard
3643      */
3644     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getProfileWithMinimumFailedPasswordsForWipe(int userHandle)3645     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
3646         if (mService != null) {
3647             try {
3648                 return mService.getProfileWithMinimumFailedPasswordsForWipe(
3649                         userHandle, mParentInstance);
3650             } catch (RemoteException e) {
3651                 throw e.rethrowFromSystemServer();
3652             }
3653         }
3654         return UserHandle.USER_NULL;
3655     }
3656 
3657     /**
3658      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't allow other admins
3659      * to change the password again until the user has entered it.
3660      */
3661     public static final int RESET_PASSWORD_REQUIRE_ENTRY = 0x0001;
3662 
3663     /**
3664      * Flag for {@link #resetPasswordWithToken} and {@link #resetPassword}: don't ask for user
3665      * credentials on device boot.
3666      * If the flag is set, the device can be booted without asking for user password.
3667      * The absence of this flag does not change the current boot requirements. This flag
3668      * can be set by the device owner only. If the app is not the device owner, the flag
3669      * is ignored. Once the flag is set, it cannot be reverted back without resetting the
3670      * device to factory defaults.
3671      */
3672     public static final int RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT = 0x0002;
3673 
3674     /**
3675      * Force a new password for device unlock (the password needed to access the entire device) or
3676      * the work profile challenge on the current user. This takes effect immediately.
3677      * <p>
3678      * <em>For device owner and profile owners targeting SDK level
3679      * {@link android.os.Build.VERSION_CODES#O} or above, this API is no longer available and will
3680      * throw {@link SecurityException}. Please use the new API {@link #resetPasswordWithToken}
3681      * instead. </em>
3682      * <p>
3683      * <em>Note: This API has been limited as of {@link android.os.Build.VERSION_CODES#N} for
3684      * device admins that are not device owner and not profile owner.
3685      * The password can now only be changed if there is currently no password set.  Device owner
3686      * and profile owner can still do this when user is unlocked and does not have a managed
3687      * profile.</em>
3688      * <p>
3689      * The given password must be sufficient for the current password quality and length constraints
3690      * as returned by {@link #getPasswordQuality(ComponentName)} and
3691      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
3692      * it will be rejected and false returned. Note that the password may be a stronger quality
3693      * (containing alphanumeric characters when the requested quality is only numeric), in which
3694      * case the currently active quality will be increased to match.
3695      * <p>
3696      * Calling with a null or empty password will clear any existing PIN, pattern or password if the
3697      * current password constraints allow it. <em>Note: This will not work in
3698      * {@link android.os.Build.VERSION_CODES#N} and later for managed profiles, or for device admins
3699      * that are not device owner or profile owner.  Once set, the password cannot be changed to null
3700      * or empty except by these admins.</em>
3701      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
3702      * methods does nothing.
3703      * <p>
3704      * The calling device admin must have requested
3705      * {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD} to be able to call this method; if it has
3706      * not, a security exception will be thrown.
3707      *
3708      * @param password The new password for the user. Null or empty clears the password.
3709      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
3710      *            {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
3711      * @return Returns true if the password was applied, or false if it is not acceptable for the
3712      *         current constraints or if the user has not been decrypted yet.
3713      * @throws SecurityException if the calling application does not own an active administrator
3714      *             that uses {@link DeviceAdminInfo#USES_POLICY_RESET_PASSWORD}
3715      * @throws IllegalStateException if the calling user is locked or has a managed profile.
3716      */
3717     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
resetPassword(String password, int flags)3718     public boolean resetPassword(String password, int flags) {
3719         throwIfParentInstance("resetPassword");
3720         if (mService != null) {
3721             try {
3722                 return mService.resetPassword(password, flags);
3723             } catch (RemoteException e) {
3724                 throw e.rethrowFromSystemServer();
3725             }
3726         }
3727         return false;
3728     }
3729 
3730     /**
3731      * Called by a profile or device owner to provision a token which can later be used to reset the
3732      * device lockscreen password (if called by device owner), or managed profile challenge (if
3733      * called by profile owner), via {@link #resetPasswordWithToken}.
3734      * <p>
3735      * If the user currently has a lockscreen password, the provisioned token will not be
3736      * immediately usable; it only becomes active after the user performs a confirm credential
3737      * operation, which can be triggered by {@link KeyguardManager#createConfirmDeviceCredentialIntent}.
3738      * If the user has no lockscreen password, the token is activated immediately. In all cases,
3739      * the active state of the current token can be checked by {@link #isResetPasswordTokenActive}.
3740      * For security reasons, un-activated tokens are only stored in memory and will be lost once
3741      * the device reboots. In this case a new token needs to be provisioned again.
3742      * <p>
3743      * Once provisioned and activated, the token will remain effective even if the user changes
3744      * or clears the lockscreen password.
3745      * <p>
3746      * <em>This token is highly sensitive and should be treated at the same level as user
3747      * credentials. In particular, NEVER store this token on device in plaintext. Do not store
3748      * the plaintext token in device-encrypted storage if it will be needed to reset password on
3749      * file-based encryption devices before user unlocks. Consider carefully how any password token
3750      * will be stored on your server and who will need access to them. Tokens may be the subject of
3751      * legal access requests.
3752      * </em>
3753      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, the
3754      * reset token is not set and this method returns false.
3755      *
3756      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3757      * @param token a secure token a least 32-byte long, which must be generated by a
3758      *        cryptographically strong random number generator.
3759      * @return true if the operation is successful, false otherwise.
3760      * @throws SecurityException if admin is not a device or profile owner.
3761      * @throws IllegalArgumentException if the supplied token is invalid.
3762      */
3763     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setResetPasswordToken(ComponentName admin, byte[] token)3764     public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
3765         throwIfParentInstance("setResetPasswordToken");
3766         if (mService != null) {
3767             try {
3768                 return mService.setResetPasswordToken(admin, token);
3769             } catch (RemoteException e) {
3770                 throw e.rethrowFromSystemServer();
3771             }
3772         }
3773         return false;
3774     }
3775 
3776     /**
3777      * Called by a profile or device owner to revoke the current password reset token.
3778      *
3779      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, this
3780      * method has no effect - the reset token should not have been set in the first place - and
3781      * false is returned.
3782      *
3783      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3784      * @return true if the operation is successful, false otherwise.
3785      * @throws SecurityException if admin is not a device or profile owner.
3786      */
3787     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
clearResetPasswordToken(ComponentName admin)3788     public boolean clearResetPasswordToken(ComponentName admin) {
3789         throwIfParentInstance("clearResetPasswordToken");
3790         if (mService != null) {
3791             try {
3792                 return mService.clearResetPasswordToken(admin);
3793             } catch (RemoteException e) {
3794                 throw e.rethrowFromSystemServer();
3795             }
3796         }
3797         return false;
3798     }
3799 
3800     /**
3801      * Called by a profile or device owner to check if the current reset password token is active.
3802      *
3803      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
3804      * false is always returned.
3805      *
3806      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3807      * @return true if the token is active, false otherwise.
3808      * @throws SecurityException if admin is not a device or profile owner.
3809      * @throws IllegalStateException if no token has been set.
3810      */
3811     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
isResetPasswordTokenActive(ComponentName admin)3812     public boolean isResetPasswordTokenActive(ComponentName admin) {
3813         throwIfParentInstance("isResetPasswordTokenActive");
3814         if (mService != null) {
3815             try {
3816                 return mService.isResetPasswordTokenActive(admin);
3817             } catch (RemoteException e) {
3818                 throw e.rethrowFromSystemServer();
3819             }
3820         }
3821         return false;
3822     }
3823 
3824     /**
3825      * Called by device or profile owner to force set a new device unlock password or a managed
3826      * profile challenge on current user. This takes effect immediately.
3827      * <p>
3828      * Unlike {@link #resetPassword}, this API can change the password even before the user or
3829      * device is unlocked or decrypted. The supplied token must have been previously provisioned via
3830      * {@link #setResetPasswordToken}, and in active state {@link #isResetPasswordTokenActive}.
3831      * <p>
3832      * The given password must be sufficient for the current password quality and length constraints
3833      * as returned by {@link #getPasswordQuality(ComponentName)} and
3834      * {@link #getPasswordMinimumLength(ComponentName)}; if it does not meet these constraints, then
3835      * it will be rejected and false returned. Note that the password may be a stronger quality, for
3836      * example, a password containing alphanumeric characters when the requested quality is only
3837      * numeric.
3838      * <p>
3839      * Calling with a {@code null} or empty password will clear any existing PIN, pattern or
3840      * password if the current password constraints allow it.
3841      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
3842      * calling this methods has no effect - the password is always empty - and false is returned.
3843      *
3844      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3845      * @param password The new password for the user. {@code null} or empty clears the password.
3846      * @param token the password reset token previously provisioned by
3847      *        {@link #setResetPasswordToken}.
3848      * @param flags May be 0 or combination of {@link #RESET_PASSWORD_REQUIRE_ENTRY} and
3849      *        {@link #RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT}.
3850      * @return Returns true if the password was applied, or false if it is not acceptable for the
3851      *         current constraints.
3852      * @throws SecurityException if admin is not a device or profile owner.
3853      * @throws IllegalStateException if the provided token is not valid.
3854      */
3855     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
resetPasswordWithToken(@onNull ComponentName admin, String password, byte[] token, int flags)3856     public boolean resetPasswordWithToken(@NonNull ComponentName admin, String password,
3857             byte[] token, int flags) {
3858         throwIfParentInstance("resetPassword");
3859         if (mService != null) {
3860             try {
3861                 return mService.resetPasswordWithToken(admin, password, token, flags);
3862             } catch (RemoteException e) {
3863                 throw e.rethrowFromSystemServer();
3864             }
3865         }
3866         return false;
3867     }
3868 
3869     /**
3870      * Called by an application that is administering the device to set the maximum time for user
3871      * activity until the device will lock. This limits the length that the user can set. It takes
3872      * effect immediately.
3873      * <p>
3874      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3875      * to be able to call this method; if it has not, a security exception will be thrown.
3876      * <p>
3877      * This method can be called on the {@link DevicePolicyManager} instance returned by
3878      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3879      * profile.
3880      *
3881      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3882      * @param timeMs The new desired maximum time to lock in milliseconds. A value of 0 means there
3883      *            is no restriction.
3884      * @throws SecurityException if {@code admin} is not an active administrator or it does not use
3885      *             {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
3886      */
setMaximumTimeToLock(@onNull ComponentName admin, long timeMs)3887     public void setMaximumTimeToLock(@NonNull ComponentName admin, long timeMs) {
3888         if (mService != null) {
3889             try {
3890                 mService.setMaximumTimeToLock(admin, timeMs, mParentInstance);
3891             } catch (RemoteException e) {
3892                 throw e.rethrowFromSystemServer();
3893             }
3894         }
3895     }
3896 
3897     /**
3898      * Retrieve the current maximum time to unlock for a particular admin or all admins that set
3899      * restrictions on this user and its participating profiles. Restrictions on profiles that have
3900      * a separate challenge are not taken into account.
3901      *
3902      * <p>This method can be called on the {@link DevicePolicyManager} instance
3903      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3904      * restrictions on the parent profile.
3905      *
3906      * @param admin The name of the admin component to check, or {@code null} to aggregate
3907      * all admins.
3908      * @return time in milliseconds for the given admin or the minimum value (strictest) of
3909      * all admins if admin is null. Returns 0 if there are no restrictions.
3910      */
getMaximumTimeToLock(@ullable ComponentName admin)3911     public long getMaximumTimeToLock(@Nullable ComponentName admin) {
3912         return getMaximumTimeToLock(admin, myUserId());
3913     }
3914 
3915     /** @hide per-user version */
3916     @UnsupportedAppUsage
getMaximumTimeToLock(@ullable ComponentName admin, int userHandle)3917     public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) {
3918         if (mService != null) {
3919             try {
3920                 return mService.getMaximumTimeToLock(admin, userHandle, mParentInstance);
3921             } catch (RemoteException e) {
3922                 throw e.rethrowFromSystemServer();
3923             }
3924         }
3925         return 0;
3926     }
3927 
3928     /**
3929      * Called by a device/profile owner to set the timeout after which unlocking with secondary, non
3930      * strong auth (e.g. fingerprint, face, trust agents) times out, i.e. the user has to use a
3931      * strong authentication method like password, pin or pattern.
3932      *
3933      * <p>This timeout is used internally to reset the timer to require strong auth again after
3934      * specified timeout each time it has been successfully used.
3935      *
3936      * <p>Fingerprint can also be disabled altogether using {@link #KEYGUARD_DISABLE_FINGERPRINT}.
3937      *
3938      * <p>Trust agents can also be disabled altogether using {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
3939      *
3940      * <p>The calling device admin must be a device or profile owner. If it is not,
3941      * a {@link SecurityException} will be thrown.
3942      *
3943      * <p>The calling device admin can verify the value it has set by calling
3944      * {@link #getRequiredStrongAuthTimeout(ComponentName)} and passing in its instance.
3945      *
3946      * <p>This method can be called on the {@link DevicePolicyManager} instance returned by
3947      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
3948      * profile.
3949      *
3950      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
3951      * calling this methods has no effect - i.e. the timeout is not set.
3952      *
3953      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
3954      * @param timeoutMs The new timeout in milliseconds, after which the user will have to unlock
3955      *         with strong authentication method. A value of 0 means the admin is not participating
3956      *         in controlling the timeout.
3957      *         The minimum and maximum timeouts are platform-defined and are typically 1 hour and
3958      *         72 hours, respectively. Though discouraged, the admin may choose to require strong
3959      *         auth at all times using {@link #KEYGUARD_DISABLE_FINGERPRINT} and/or
3960      *         {@link #KEYGUARD_DISABLE_TRUST_AGENTS}.
3961      *
3962      * @throws SecurityException if {@code admin} is not a device or profile owner.
3963      */
3964     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setRequiredStrongAuthTimeout(@onNull ComponentName admin, long timeoutMs)3965     public void setRequiredStrongAuthTimeout(@NonNull ComponentName admin,
3966             long timeoutMs) {
3967         if (mService != null) {
3968             try {
3969                 mService.setRequiredStrongAuthTimeout(admin, timeoutMs, mParentInstance);
3970             } catch (RemoteException e) {
3971                 throw e.rethrowFromSystemServer();
3972             }
3973         }
3974     }
3975 
3976     /**
3977      * Determine for how long the user will be able to use secondary, non strong auth for
3978      * authentication, since last strong method authentication (password, pin or pattern) was used.
3979      * After the returned timeout the user is required to use strong authentication method.
3980      *
3981      * <p>This method can be called on the {@link DevicePolicyManager} instance
3982      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
3983      * restrictions on the parent profile.
3984      *
3985      * <p>On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature,
3986      * 0 is returned to indicate that no timeout is configured.
3987      *
3988      * @param admin The name of the admin component to check, or {@code null} to aggregate
3989      *         across all participating admins.
3990      * @return The timeout in milliseconds or 0 if not configured for the provided admin.
3991      */
3992     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getRequiredStrongAuthTimeout(@ullable ComponentName admin)3993     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin) {
3994         return getRequiredStrongAuthTimeout(admin, myUserId());
3995     }
3996 
3997     /** @hide per-user version */
3998     @UnsupportedAppUsage
3999     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getRequiredStrongAuthTimeout(@ullable ComponentName admin, @UserIdInt int userId)4000     public long getRequiredStrongAuthTimeout(@Nullable ComponentName admin, @UserIdInt int userId) {
4001         if (mService != null) {
4002             try {
4003                 return mService.getRequiredStrongAuthTimeout(admin, userId, mParentInstance);
4004             } catch (RemoteException e) {
4005                 throw e.rethrowFromSystemServer();
4006             }
4007         }
4008         return DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4009     }
4010 
4011     /**
4012      * Flag for {@link #lockNow(int)}: also evict the user's credential encryption key from the
4013      * keyring. The user's credential will need to be entered again in order to derive the
4014      * credential encryption key that will be stored back in the keyring for future use.
4015      * <p>
4016      * This flag can only be used by a profile owner when locking a managed profile when
4017      * {@link #getStorageEncryptionStatus} returns {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
4018      * <p>
4019      * In order to secure user data, the user will be stopped and restarted so apps should wait
4020      * until they are next run to perform further actions.
4021      */
4022     public static final int FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY = 1;
4023 
4024     /** @hide */
4025     @Retention(RetentionPolicy.SOURCE)
4026     @IntDef(flag = true, prefix = { "FLAG_EVICT_" }, value = {
4027             FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY
4028     })
4029     public @interface LockNowFlag {}
4030 
4031     /**
4032      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
4033      * this call.
4034      * <p>
4035      * This method secures the device in response to an urgent situation, such as a lost or stolen
4036      * device. After this method is called, the device must be unlocked using strong authentication
4037      * (PIN, pattern, or password). This API is intended for use only by device admins.
4038      * <p>
4039      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
4040      * to be able to call this method; if it has not, a security exception will be thrown.
4041      * <p>
4042      * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
4043      * the device. Device admins who find the device in this state can lock an otherwise-insecure
4044      * device by first calling {@link #resetPassword} to set the password and then lock the device.
4045      * <p>
4046      * This method can be called on the {@link DevicePolicyManager} instance returned by
4047      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
4048      * <p>
4049      * Equivalent to calling {@link #lockNow(int)} with no flags.
4050      *
4051      * @throws SecurityException if the calling application does not own an active administrator
4052      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
4053      */
lockNow()4054     public void lockNow() {
4055         lockNow(0);
4056     }
4057 
4058     /**
4059      * Make the device lock immediately, as if the lock screen timeout has expired at the point of
4060      * this call.
4061      * <p>
4062      * This method secures the device in response to an urgent situation, such as a lost or stolen
4063      * device. After this method is called, the device must be unlocked using strong authentication
4064      * (PIN, pattern, or password). This API is intended for use only by device admins.
4065      * <p>
4066      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK}
4067      * to be able to call this method; if it has not, a security exception will be thrown.
4068      * <p>
4069      * If there's no lock type set, this method forces the device to go to sleep but doesn't lock
4070      * the device. Device admins who find the device in this state can lock an otherwise-insecure
4071      * device by first calling {@link #resetPassword} to set the password and then lock the device.
4072      * <p>
4073      * This method can be called on the {@link DevicePolicyManager} instance returned by
4074      * {@link #getParentProfileInstance(ComponentName)} in order to lock the parent profile.
4075      *
4076      * @param flags May be 0 or {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}.
4077      * @throws SecurityException if the calling application does not own an active administrator
4078      *             that uses {@link DeviceAdminInfo#USES_POLICY_FORCE_LOCK} or the
4079      *             {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is passed by an application
4080      *             that is not a profile
4081      *             owner of a managed profile.
4082      * @throws IllegalArgumentException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY} flag is
4083      *             passed when locking the parent profile.
4084      * @throws UnsupportedOperationException if the {@link #FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY}
4085      *             flag is passed when {@link #getStorageEncryptionStatus} does not return
4086      *             {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
4087      */
lockNow(@ockNowFlag int flags)4088     public void lockNow(@LockNowFlag int flags) {
4089         if (mService != null) {
4090             try {
4091                 mService.lockNow(flags, mParentInstance);
4092             } catch (RemoteException e) {
4093                 throw e.rethrowFromSystemServer();
4094             }
4095         }
4096     }
4097 
4098     /**
4099      * Flag for {@link #wipeData(int)}: also erase the device's external
4100      * storage (such as SD cards).
4101      */
4102     public static final int WIPE_EXTERNAL_STORAGE = 0x0001;
4103 
4104     /**
4105      * Flag for {@link #wipeData(int)}: also erase the factory reset protection
4106      * data.
4107      *
4108      * <p>This flag may only be set by device owner admins; if it is set by
4109      * other admins a {@link SecurityException} will be thrown.
4110      */
4111     public static final int WIPE_RESET_PROTECTION_DATA = 0x0002;
4112 
4113     /**
4114      * Flag for {@link #wipeData(int)}: also erase the device's eUICC data.
4115      */
4116     public static final int WIPE_EUICC = 0x0004;
4117 
4118     /**
4119      * Flag for {@link #wipeData(int)}: won't show reason for wiping to the user.
4120      */
4121     public static final int WIPE_SILENTLY = 0x0008;
4122 
4123     /**
4124      * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
4125      * other users will remain unaffected. Calling from the primary user will cause the device to
4126      * reboot, erasing all device data - including all the secondary users and their data - while
4127      * booting up.
4128      * <p>
4129      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
4130      * be able to call this method; if it has not, a security exception will be thrown.
4131      *
4132      * @param flags Bit mask of additional options: currently supported flags are
4133      *            {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA},
4134      *            {@link #WIPE_EUICC} and {@link #WIPE_SILENTLY}.
4135      * @throws SecurityException if the calling application does not own an active administrator
4136      *            that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
4137      */
wipeData(int flags)4138     public void wipeData(int flags) {
4139         throwIfParentInstance("wipeData");
4140         final String wipeReasonForUser = mContext.getString(
4141                 R.string.work_profile_deleted_description_dpm_wipe);
4142         wipeDataInternal(flags, wipeReasonForUser);
4143     }
4144 
4145     /**
4146      * Ask that all user data be wiped. If called as a secondary user, the user will be removed and
4147      * other users will remain unaffected, the provided reason for wiping data can be shown to
4148      * user. Calling from the primary user will cause the device to reboot, erasing all device data
4149      * - including all the secondary users and their data - while booting up. In this case, we don't
4150      * show the reason to the user since the device would be factory reset.
4151      * <p>
4152      * The calling device admin must have requested {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA} to
4153      * be able to call this method; if it has not, a security exception will be thrown.
4154      *
4155      * @param flags Bit mask of additional options: currently supported flags are
4156      *            {@link #WIPE_EXTERNAL_STORAGE}, {@link #WIPE_RESET_PROTECTION_DATA} and
4157      *            {@link #WIPE_EUICC}.
4158      * @param reason a string that contains the reason for wiping data, which can be
4159      *            presented to the user.
4160      * @throws SecurityException if the calling application does not own an active administrator
4161      *            that uses {@link DeviceAdminInfo#USES_POLICY_WIPE_DATA}
4162      * @throws IllegalArgumentException if the input reason string is null or empty, or if
4163      *            {@link #WIPE_SILENTLY} is set.
4164      */
wipeData(int flags, @NonNull CharSequence reason)4165     public void wipeData(int flags, @NonNull CharSequence reason) {
4166         throwIfParentInstance("wipeData");
4167         Preconditions.checkNotNull(reason, "reason string is null");
4168         Preconditions.checkStringNotEmpty(reason, "reason string is empty");
4169         Preconditions.checkArgument((flags & WIPE_SILENTLY) == 0, "WIPE_SILENTLY cannot be set");
4170         wipeDataInternal(flags, reason.toString());
4171     }
4172 
4173     /**
4174      * Internal function for both {@link #wipeData(int)} and
4175      * {@link #wipeData(int, CharSequence)} to call.
4176      *
4177      * @see #wipeData(int)
4178      * @see #wipeData(int, CharSequence)
4179      * @hide
4180      */
wipeDataInternal(int flags, @NonNull String wipeReasonForUser)4181     private void wipeDataInternal(int flags, @NonNull String wipeReasonForUser) {
4182         if (mService != null) {
4183             try {
4184                 mService.wipeDataWithReason(flags, wipeReasonForUser);
4185             } catch (RemoteException e) {
4186                 throw e.rethrowFromSystemServer();
4187             }
4188         }
4189     }
4190 
4191     /**
4192      * Called by an application that is administering the device to set the
4193      * global proxy and exclusion list.
4194      * <p>
4195      * The calling device admin must have requested
4196      * {@link DeviceAdminInfo#USES_POLICY_SETS_GLOBAL_PROXY} to be able to call
4197      * this method; if it has not, a security exception will be thrown.
4198      * Only the first device admin can set the proxy. If a second admin attempts
4199      * to set the proxy, the {@link ComponentName} of the admin originally setting the
4200      * proxy will be returned. If successful in setting the proxy, {@code null} will
4201      * be returned.
4202      * The method can be called repeatedly by the device admin alrady setting the
4203      * proxy to update the proxy and exclusion list.
4204      *
4205      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4206      * @param proxySpec the global proxy desired. Must be an HTTP Proxy.
4207      *            Pass Proxy.NO_PROXY to reset the proxy.
4208      * @param exclusionList a list of domains to be excluded from the global proxy.
4209      * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName}
4210      *            of the device admin that sets the proxy.
4211      * @hide
4212      */
4213     @UnsupportedAppUsage
setGlobalProxy(@onNull ComponentName admin, Proxy proxySpec, List<String> exclusionList )4214     public @Nullable ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec,
4215             List<String> exclusionList ) {
4216         throwIfParentInstance("setGlobalProxy");
4217         if (proxySpec == null) {
4218             throw new NullPointerException();
4219         }
4220         if (mService != null) {
4221             try {
4222                 String hostSpec;
4223                 String exclSpec;
4224                 if (proxySpec.equals(Proxy.NO_PROXY)) {
4225                     hostSpec = null;
4226                     exclSpec = null;
4227                 } else {
4228                     if (!proxySpec.type().equals(Proxy.Type.HTTP)) {
4229                         throw new IllegalArgumentException();
4230                     }
4231                     InetSocketAddress sa = (InetSocketAddress)proxySpec.address();
4232                     String hostName = sa.getHostName();
4233                     int port = sa.getPort();
4234                     StringBuilder hostBuilder = new StringBuilder();
4235                     hostSpec = hostBuilder.append(hostName)
4236                         .append(":").append(Integer.toString(port)).toString();
4237                     if (exclusionList == null) {
4238                         exclSpec = "";
4239                     } else {
4240                         StringBuilder listBuilder = new StringBuilder();
4241                         boolean firstDomain = true;
4242                         for (String exclDomain : exclusionList) {
4243                             if (!firstDomain) {
4244                                 listBuilder = listBuilder.append(",");
4245                             } else {
4246                                 firstDomain = false;
4247                             }
4248                             listBuilder = listBuilder.append(exclDomain.trim());
4249                         }
4250                         exclSpec = listBuilder.toString();
4251                     }
4252                     if (android.net.Proxy.validate(hostName, Integer.toString(port), exclSpec)
4253                             != android.net.Proxy.PROXY_VALID)
4254                         throw new IllegalArgumentException();
4255                 }
4256                 return mService.setGlobalProxy(admin, hostSpec, exclSpec);
4257             } catch (RemoteException e) {
4258                 throw e.rethrowFromSystemServer();
4259             }
4260         }
4261         return null;
4262     }
4263 
4264     /**
4265      * Set a network-independent global HTTP proxy. This is not normally what you want for typical
4266      * HTTP proxies - they are generally network dependent. However if you're doing something
4267      * unusual like general internal filtering this may be useful. On a private network where the
4268      * proxy is not accessible, you may break HTTP using this.
4269      * <p>
4270      * This method requires the caller to be the device owner.
4271      * <p>
4272      * This proxy is only a recommendation and it is possible that some apps will ignore it.
4273      *
4274      * @see ProxyInfo
4275      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4276      * @param proxyInfo The a {@link ProxyInfo} object defining the new global HTTP proxy. A
4277      *            {@code null} value will clear the global HTTP proxy.
4278      * @throws SecurityException if {@code admin} is not the device owner.
4279      */
setRecommendedGlobalProxy(@onNull ComponentName admin, @Nullable ProxyInfo proxyInfo)4280     public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo
4281             proxyInfo) {
4282         throwIfParentInstance("setRecommendedGlobalProxy");
4283         if (mService != null) {
4284             try {
4285                 mService.setRecommendedGlobalProxy(admin, proxyInfo);
4286             } catch (RemoteException e) {
4287                 throw e.rethrowFromSystemServer();
4288             }
4289         }
4290     }
4291 
4292     /**
4293      * Returns the component name setting the global proxy.
4294      * @return ComponentName object of the device admin that set the global proxy, or {@code null}
4295      *         if no admin has set the proxy.
4296      * @hide
4297      */
getGlobalProxyAdmin()4298     public @Nullable ComponentName getGlobalProxyAdmin() {
4299         if (mService != null) {
4300             try {
4301                 return mService.getGlobalProxyAdmin(myUserId());
4302             } catch (RemoteException e) {
4303                 throw e.rethrowFromSystemServer();
4304             }
4305         }
4306         return null;
4307     }
4308 
4309     /**
4310      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
4311      * indicating that encryption is not supported.
4312      */
4313     public static final int ENCRYPTION_STATUS_UNSUPPORTED = 0;
4314 
4315     /**
4316      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
4317      * indicating that encryption is supported, but is not currently active.
4318      */
4319     public static final int ENCRYPTION_STATUS_INACTIVE = 1;
4320 
4321     /**
4322      * Result code for {@link #getStorageEncryptionStatus}:
4323      * indicating that encryption is not currently active, but is currently
4324      * being activated.  This is only reported by devices that support
4325      * encryption of data and only when the storage is currently
4326      * undergoing a process of becoming encrypted.  A device that must reboot and/or wipe data
4327      * to become encrypted will never return this value.
4328      */
4329     public static final int ENCRYPTION_STATUS_ACTIVATING = 2;
4330 
4331     /**
4332      * Result code for {@link #setStorageEncryption} and {@link #getStorageEncryptionStatus}:
4333      * indicating that encryption is active.
4334      * <p>
4335      * Also see {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
4336      */
4337     public static final int ENCRYPTION_STATUS_ACTIVE = 3;
4338 
4339     /**
4340      * Result code for {@link #getStorageEncryptionStatus}:
4341      * indicating that encryption is active, but an encryption key has not
4342      * been set by the user.
4343      */
4344     public static final int ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY = 4;
4345 
4346     /**
4347      * Result code for {@link #getStorageEncryptionStatus}:
4348      * indicating that encryption is active and the encryption key is tied to the user or profile.
4349      * <p>
4350      * This value is only returned to apps targeting API level 24 and above. For apps targeting
4351      * earlier API levels, {@link #ENCRYPTION_STATUS_ACTIVE} is returned, even if the
4352      * encryption key is specific to the user or profile.
4353      */
4354     public static final int ENCRYPTION_STATUS_ACTIVE_PER_USER = 5;
4355 
4356     /**
4357      * Activity action: begin the process of encrypting data on the device.  This activity should
4358      * be launched after using {@link #setStorageEncryption} to request encryption be activated.
4359      * After resuming from this activity, use {@link #getStorageEncryption}
4360      * to check encryption status.  However, on some devices this activity may never return, as
4361      * it may trigger a reboot and in some cases a complete data wipe of the device.
4362      */
4363     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
4364     public static final String ACTION_START_ENCRYPTION
4365             = "android.app.action.START_ENCRYPTION";
4366 
4367     /**
4368      * Broadcast action: notify managed provisioning that new managed user is created.
4369      *
4370      * @hide
4371      */
4372     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
4373     public static final String ACTION_MANAGED_USER_CREATED =
4374             "android.app.action.MANAGED_USER_CREATED";
4375 
4376     /**
4377      * Widgets are enabled in keyguard
4378      */
4379     public static final int KEYGUARD_DISABLE_FEATURES_NONE = 0;
4380 
4381     /**
4382      * Disable all keyguard widgets. Has no effect starting from
4383      * {@link android.os.Build.VERSION_CODES#LOLLIPOP} since keyguard widget is only supported
4384      * on Android versions lower than 5.0.
4385      */
4386     public static final int KEYGUARD_DISABLE_WIDGETS_ALL = 1 << 0;
4387 
4388     /**
4389      * Disable the camera on secure keyguard screens (e.g. PIN/Pattern/Password)
4390      */
4391     public static final int KEYGUARD_DISABLE_SECURE_CAMERA = 1 << 1;
4392 
4393     /**
4394      * Disable showing all notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
4395      */
4396     public static final int KEYGUARD_DISABLE_SECURE_NOTIFICATIONS = 1 << 2;
4397 
4398     /**
4399      * Only allow redacted notifications on secure keyguard screens (e.g. PIN/Pattern/Password)
4400      */
4401     public static final int KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS = 1 << 3;
4402 
4403     /**
4404      * Disable trust agents on secure keyguard screens (e.g. PIN/Pattern/Password).
4405      * By setting this flag alone, all trust agents are disabled. If the admin then wants to
4406      * whitelist specific features of some trust agent, {@link #setTrustAgentConfiguration} can be
4407      * used in conjuction to set trust-agent-specific configurations.
4408      */
4409     public static final int KEYGUARD_DISABLE_TRUST_AGENTS = 1 << 4;
4410 
4411     /**
4412      * Disable fingerprint authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
4413      */
4414     public static final int KEYGUARD_DISABLE_FINGERPRINT = 1 << 5;
4415 
4416     /**
4417      * Disable text entry into notifications on secure keyguard screens (e.g. PIN/Pattern/Password).
4418      * This flag has no effect starting from version {@link android.os.Build.VERSION_CODES#N}
4419      */
4420     public static final int KEYGUARD_DISABLE_REMOTE_INPUT = 1 << 6;
4421 
4422     /**
4423      * Disable face authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
4424      */
4425     public static final int KEYGUARD_DISABLE_FACE = 1 << 7;
4426 
4427     /**
4428      * Disable iris authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
4429      */
4430     public static final int KEYGUARD_DISABLE_IRIS = 1 << 8;
4431 
4432     /**
4433      * NOTE: Please remember to update the DevicePolicyManagerTest's testKeyguardDisabledFeatures
4434      * CTS test when adding to the list above.
4435      */
4436 
4437     /**
4438      * Disable all biometric authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
4439      */
4440     public static final int KEYGUARD_DISABLE_BIOMETRICS =
4441             DevicePolicyManager.KEYGUARD_DISABLE_FACE
4442             | DevicePolicyManager.KEYGUARD_DISABLE_IRIS
4443             | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
4444 
4445     /**
4446      * Disable all current and future keyguard customizations.
4447      */
4448     public static final int KEYGUARD_DISABLE_FEATURES_ALL = 0x7fffffff;
4449 
4450     /**
4451      * Keyguard features that when set on a managed profile that doesn't have its own challenge will
4452      * affect the profile's parent user. These can also be set on the managed profile's parent
4453      * {@link DevicePolicyManager} instance.
4454      *
4455      * @hide
4456      */
4457     public static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
4458             DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
4459             | DevicePolicyManager.KEYGUARD_DISABLE_BIOMETRICS;
4460 
4461     /**
4462      * Called by an application that is administering the device to request that the storage system
4463      * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
4464      * <p>
4465      * When multiple device administrators attempt to control device encryption, the most secure,
4466      * supported setting will always be used. If any device administrator requests device
4467      * encryption, it will be enabled; Conversely, if a device administrator attempts to disable
4468      * device encryption while another device administrator has enabled it, the call to disable will
4469      * fail (most commonly returning {@link #ENCRYPTION_STATUS_ACTIVE}).
4470      * <p>
4471      * This policy controls encryption of the secure (application data) storage area. Data written
4472      * to other storage areas may or may not be encrypted, and this policy does not require or
4473      * control the encryption of any other storage areas. There is one exception: If
4474      * {@link android.os.Environment#isExternalStorageEmulated()} is {@code true}, then the
4475      * directory returned by {@link android.os.Environment#getExternalStorageDirectory()} must be
4476      * written to disk within the encrypted storage area.
4477      * <p>
4478      * Important Note: On some devices, it is possible to encrypt storage without requiring the user
4479      * to create a device PIN or Password. In this case, the storage is encrypted, but the
4480      * encryption key may not be fully secured. For maximum security, the administrator should also
4481      * require (and check for) a pattern, PIN, or password.
4482      *
4483      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
4484      * @param encrypt true to request encryption, false to release any previous request
4485      * @return the new total request status (for all active admins), or {@link
4486      *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user.
4487      *         Will be one of {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link
4488      *         #ENCRYPTION_STATUS_INACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value
4489      *         of the requests; use {@link #getStorageEncryptionStatus()} to query the actual device
4490      *         state.
4491      *
4492      * @throws SecurityException if {@code admin} is not an active administrator or does not use
4493      *             {@link DeviceAdminInfo#USES_ENCRYPTED_STORAGE}
4494      */
setStorageEncryption(@onNull ComponentName admin, boolean encrypt)4495     public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) {
4496         throwIfParentInstance("setStorageEncryption");
4497         if (mService != null) {
4498             try {
4499                 return mService.setStorageEncryption(admin, encrypt);
4500             } catch (RemoteException e) {
4501                 throw e.rethrowFromSystemServer();
4502             }
4503         }
4504         return ENCRYPTION_STATUS_UNSUPPORTED;
4505     }
4506 
4507     /**
4508      * Called by an application that is administering the device to
4509      * determine the requested setting for secure storage.
4510      *
4511      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.  If null,
4512      * this will return the requested encryption setting as an aggregate of all active
4513      * administrators.
4514      * @return true if the admin(s) are requesting encryption, false if not.
4515      */
getStorageEncryption(@ullable ComponentName admin)4516     public boolean getStorageEncryption(@Nullable ComponentName admin) {
4517         throwIfParentInstance("getStorageEncryption");
4518         if (mService != null) {
4519             try {
4520                 return mService.getStorageEncryption(admin, myUserId());
4521             } catch (RemoteException e) {
4522                 throw e.rethrowFromSystemServer();
4523             }
4524         }
4525         return false;
4526     }
4527 
4528     /**
4529      * Called by an application that is administering the device to
4530      * determine the current encryption status of the device.
4531      * <p>
4532      * Depending on the returned status code, the caller may proceed in different
4533      * ways.  If the result is {@link #ENCRYPTION_STATUS_UNSUPPORTED}, the
4534      * storage system does not support encryption.  If the
4535      * result is {@link #ENCRYPTION_STATUS_INACTIVE}, use {@link
4536      * #ACTION_START_ENCRYPTION} to begin the process of encrypting or decrypting the
4537      * storage.  If the result is {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, the
4538      * storage system has enabled encryption but no password is set so further action
4539      * may be required.  If the result is {@link #ENCRYPTION_STATUS_ACTIVATING},
4540      * {@link #ENCRYPTION_STATUS_ACTIVE} or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER},
4541      * no further action is required.
4542      *
4543      * @return current status of encryption. The value will be one of
4544      * {@link #ENCRYPTION_STATUS_UNSUPPORTED}, {@link #ENCRYPTION_STATUS_INACTIVE},
4545      * {@link #ENCRYPTION_STATUS_ACTIVATING}, {@link #ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
4546      * {@link #ENCRYPTION_STATUS_ACTIVE}, or {@link #ENCRYPTION_STATUS_ACTIVE_PER_USER}.
4547      */
getStorageEncryptionStatus()4548     public int getStorageEncryptionStatus() {
4549         throwIfParentInstance("getStorageEncryptionStatus");
4550         return getStorageEncryptionStatus(myUserId());
4551     }
4552 
4553     /** @hide per-user version */
4554     @UnsupportedAppUsage
getStorageEncryptionStatus(int userHandle)4555     public int getStorageEncryptionStatus(int userHandle) {
4556         if (mService != null) {
4557             try {
4558                 return mService.getStorageEncryptionStatus(mContext.getPackageName(), userHandle);
4559             } catch (RemoteException e) {
4560                 throw e.rethrowFromSystemServer();
4561             }
4562         }
4563         return ENCRYPTION_STATUS_UNSUPPORTED;
4564     }
4565 
4566     /**
4567      * Mark a CA certificate as approved by the device user. This means that they have been notified
4568      * of the installation, were made aware of the risks, viewed the certificate and still wanted to
4569      * keep the certificate on the device.
4570      *
4571      * Calling with {@param approval} as {@code true} will cancel any ongoing warnings related to
4572      * this certificate.
4573      *
4574      * @hide
4575      */
approveCaCert(String alias, int userHandle, boolean approval)4576     public boolean approveCaCert(String alias, int userHandle, boolean approval) {
4577         if (mService != null) {
4578             try {
4579                 return mService.approveCaCert(alias, userHandle, approval);
4580             } catch (RemoteException e) {
4581                 throw e.rethrowFromSystemServer();
4582             }
4583         }
4584         return false;
4585     }
4586 
4587     /**
4588      * Check whether a CA certificate has been approved by the device user.
4589      *
4590      * @hide
4591      */
isCaCertApproved(String alias, int userHandle)4592     public boolean isCaCertApproved(String alias, int userHandle) {
4593         if (mService != null) {
4594             try {
4595                 return mService.isCaCertApproved(alias, userHandle);
4596             } catch (RemoteException e) {
4597                 throw e.rethrowFromSystemServer();
4598             }
4599         }
4600         return false;
4601     }
4602 
4603     /**
4604      * Installs the given certificate as a user CA.
4605      * <p>
4606      * Inserted user CAs aren't automatically trusted by apps in Android 7.0 (API level 24) and
4607      * higher. App developers can change the default behavior for an app by adding a
4608      * <a href="{@docRoot}training/articles/security-config.html">Security Configuration
4609      * File</a> to the app manifest file.
4610      *
4611      * The caller must be a profile or device owner on that user, or a delegate package given the
4612      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
4613      * security exception will be thrown.
4614      *
4615      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4616      *              {@code null} if calling from a delegated certificate installer.
4617      * @param certBuffer encoded form of the certificate to install.
4618      *
4619      * @return false if the certBuffer cannot be parsed or installation is
4620      *         interrupted, true otherwise.
4621      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4622      *         owner.
4623      * @see #setDelegatedScopes
4624      * @see #DELEGATION_CERT_INSTALL
4625      */
installCaCert(@ullable ComponentName admin, byte[] certBuffer)4626     public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
4627         throwIfParentInstance("installCaCert");
4628         if (mService != null) {
4629             try {
4630                 return mService.installCaCert(admin, mContext.getPackageName(), certBuffer);
4631             } catch (RemoteException e) {
4632                 throw e.rethrowFromSystemServer();
4633             }
4634         }
4635         return false;
4636     }
4637 
4638     /**
4639      * Uninstalls the given certificate from trusted user CAs, if present.
4640      *
4641      * The caller must be a profile or device owner on that user, or a delegate package given the
4642      * {@link #DELEGATION_CERT_INSTALL} scope via {@link #setDelegatedScopes}; otherwise a
4643      * security exception will be thrown.
4644      *
4645      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4646      *              {@code null} if calling from a delegated certificate installer.
4647      * @param certBuffer encoded form of the certificate to remove.
4648      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4649      *         owner.
4650      * @see #setDelegatedScopes
4651      * @see #DELEGATION_CERT_INSTALL
4652      */
uninstallCaCert(@ullable ComponentName admin, byte[] certBuffer)4653     public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) {
4654         throwIfParentInstance("uninstallCaCert");
4655         if (mService != null) {
4656             try {
4657                 final String alias = getCaCertAlias(certBuffer);
4658                 mService.uninstallCaCerts(admin, mContext.getPackageName(), new String[] {alias});
4659             } catch (CertificateException e) {
4660                 Log.w(TAG, "Unable to parse certificate", e);
4661             } catch (RemoteException e) {
4662                 throw e.rethrowFromSystemServer();
4663             }
4664         }
4665     }
4666 
4667     /**
4668      * Returns all CA certificates that are currently trusted, excluding system CA certificates.
4669      * If a user has installed any certificates by other means than device policy these will be
4670      * included too.
4671      *
4672      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4673      *              {@code null} if calling from a delegated certificate installer.
4674      * @return a List of byte[] arrays, each encoding one user CA certificate.
4675      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4676      *         owner.
4677      */
getInstalledCaCerts(@ullable ComponentName admin)4678     public @NonNull List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) {
4679         final List<byte[]> certs = new ArrayList<byte[]>();
4680         throwIfParentInstance("getInstalledCaCerts");
4681         if (mService != null) {
4682             try {
4683                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
4684                 final TrustedCertificateStore certStore = new TrustedCertificateStore();
4685                 for (String alias : certStore.userAliases()) {
4686                     try {
4687                         certs.add(certStore.getCertificate(alias).getEncoded());
4688                     } catch (CertificateException ce) {
4689                         Log.w(TAG, "Could not encode certificate: " + alias, ce);
4690                     }
4691                 }
4692             } catch (RemoteException re) {
4693                 throw re.rethrowFromSystemServer();
4694             }
4695         }
4696         return certs;
4697     }
4698 
4699     /**
4700      * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by
4701      * means other than device policy will also be removed, except for system CA certificates.
4702      *
4703      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4704      *              {@code null} if calling from a delegated certificate installer.
4705      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4706      *         owner.
4707      */
uninstallAllUserCaCerts(@ullable ComponentName admin)4708     public void uninstallAllUserCaCerts(@Nullable ComponentName admin) {
4709         throwIfParentInstance("uninstallAllUserCaCerts");
4710         if (mService != null) {
4711             try {
4712                 mService.uninstallCaCerts(admin, mContext.getPackageName(),
4713                         new TrustedCertificateStore().userAliases() .toArray(new String[0]));
4714             } catch (RemoteException re) {
4715                 throw re.rethrowFromSystemServer();
4716             }
4717         }
4718     }
4719 
4720     /**
4721      * Returns whether this certificate is installed as a trusted CA.
4722      *
4723      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4724      *              {@code null} if calling from a delegated certificate installer.
4725      * @param certBuffer encoded form of the certificate to look up.
4726      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4727      *         owner.
4728      */
hasCaCertInstalled(@ullable ComponentName admin, byte[] certBuffer)4729     public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) {
4730         throwIfParentInstance("hasCaCertInstalled");
4731         if (mService != null) {
4732             try {
4733                 mService.enforceCanManageCaCerts(admin, mContext.getPackageName());
4734                 return getCaCertAlias(certBuffer) != null;
4735             } catch (RemoteException re) {
4736                 throw re.rethrowFromSystemServer();
4737             } catch (CertificateException ce) {
4738                 Log.w(TAG, "Could not parse certificate", ce);
4739             }
4740         }
4741         return false;
4742     }
4743 
4744     /**
4745      * Called by a device or profile owner, or delegated certificate installer, to install a
4746      * certificate and corresponding private key. All apps within the profile will be able to access
4747      * the certificate and use the private key, given direct user approval.
4748      *
4749      * <p>Access to the installed credentials will not be granted to the caller of this API without
4750      * direct user approval. This is for security - should a certificate installer become
4751      * compromised, certificates it had already installed will be protected.
4752      *
4753      * <p>If the installer must have access to the credentials, call
4754      * {@link #installKeyPair(ComponentName, PrivateKey, Certificate[], String, boolean)} instead.
4755      *
4756      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
4757      * have been given to access the key and certificates associated with this alias will be
4758      * revoked.
4759      *
4760      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4761      *            {@code null} if calling from a delegated certificate installer.
4762      * @param privKey The private key to install.
4763      * @param cert The certificate to install.
4764      * @param alias The private key alias under which to install the certificate. If a certificate
4765      * with that alias already exists, it will be overwritten.
4766      * @return {@code true} if the keys were installed, {@code false} otherwise.
4767      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4768      *         owner.
4769      * @see #setDelegatedScopes
4770      * @see #DELEGATION_CERT_INSTALL
4771      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate cert, @NonNull String alias)4772     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
4773             @NonNull Certificate cert, @NonNull String alias) {
4774         return installKeyPair(admin, privKey, new Certificate[] {cert}, alias, false);
4775     }
4776 
4777     /**
4778      * Called by a device or profile owner, or delegated certificate installer, to install a
4779      * certificate chain and corresponding private key for the leaf certificate. All apps within the
4780      * profile will be able to access the certificate chain and use the private key, given direct
4781      * user approval.
4782      *
4783      * <p>The caller of this API may grant itself access to the certificate and private key
4784      * immediately, without user approval. It is a best practice not to request this unless strictly
4785      * necessary since it opens up additional security vulnerabilities.
4786      *
4787      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
4788      * have been given to access the key and certificates associated with this alias will be
4789      * revoked.
4790      *
4791      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4792      *        {@code null} if calling from a delegated certificate installer.
4793      * @param privKey The private key to install.
4794      * @param certs The certificate chain to install. The chain should start with the leaf
4795      *        certificate and include the chain of trust in order. This will be returned by
4796      *        {@link android.security.KeyChain#getCertificateChain}.
4797      * @param alias The private key alias under which to install the certificate. If a certificate
4798      *        with that alias already exists, it will be overwritten.
4799      * @param requestAccess {@code true} to request that the calling app be granted access to the
4800      *        credentials immediately. Otherwise, access to the credentials will be gated by user
4801      *        approval.
4802      * @return {@code true} if the keys were installed, {@code false} otherwise.
4803      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4804      *         owner.
4805      * @see android.security.KeyChain#getCertificateChain
4806      * @see #setDelegatedScopes
4807      * @see #DELEGATION_CERT_INSTALL
4808      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess)4809     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
4810             @NonNull Certificate[] certs, @NonNull String alias, boolean requestAccess) {
4811         int flags = INSTALLKEY_SET_USER_SELECTABLE;
4812         if (requestAccess) {
4813             flags |= INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
4814         }
4815         return installKeyPair(admin, privKey, certs, alias, flags);
4816     }
4817 
4818     /**
4819      * Called by a device or profile owner, or delegated certificate installer, to install a
4820      * certificate chain and corresponding private key for the leaf certificate. All apps within the
4821      * profile will be able to access the certificate chain and use the private key, given direct
4822      * user approval (if the user is allowed to select the private key).
4823      *
4824      * <p>The caller of this API may grant itself access to the certificate and private key
4825      * immediately, without user approval. It is a best practice not to request this unless strictly
4826      * necessary since it opens up additional security vulnerabilities.
4827      *
4828      * <p>Include {@link #INSTALLKEY_SET_USER_SELECTABLE} in the {@code flags} argument to allow
4829      * the user to select the key from a dialog.
4830      *
4831      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
4832      * have been given to access the key and certificates associated with this alias will be
4833      * revoked.
4834      *
4835      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4836      *        {@code null} if calling from a delegated certificate installer.
4837      * @param privKey The private key to install.
4838      * @param certs The certificate chain to install. The chain should start with the leaf
4839      *        certificate and include the chain of trust in order. This will be returned by
4840      *        {@link android.security.KeyChain#getCertificateChain}.
4841      * @param alias The private key alias under which to install the certificate. If a certificate
4842      *        with that alias already exists, it will be overwritten.
4843      * @param flags Flags to request that the calling app be granted access to the credentials
4844      *        and set the key to be user-selectable. See {@link #INSTALLKEY_SET_USER_SELECTABLE} and
4845      *        {@link #INSTALLKEY_REQUEST_CREDENTIALS_ACCESS}.
4846      * @return {@code true} if the keys were installed, {@code false} otherwise.
4847      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4848      *         owner.
4849      * @see android.security.KeyChain#getCertificateChain
4850      * @see #setDelegatedScopes
4851      * @see #DELEGATION_CERT_INSTALL
4852      */
installKeyPair(@ullable ComponentName admin, @NonNull PrivateKey privKey, @NonNull Certificate[] certs, @NonNull String alias, int flags)4853     public boolean installKeyPair(@Nullable ComponentName admin, @NonNull PrivateKey privKey,
4854             @NonNull Certificate[] certs, @NonNull String alias, int flags) {
4855         throwIfParentInstance("installKeyPair");
4856         boolean requestAccess = (flags & INSTALLKEY_REQUEST_CREDENTIALS_ACCESS)
4857                 == INSTALLKEY_REQUEST_CREDENTIALS_ACCESS;
4858         boolean isUserSelectable = (flags & INSTALLKEY_SET_USER_SELECTABLE)
4859                 == INSTALLKEY_SET_USER_SELECTABLE;
4860         try {
4861             final byte[] pemCert = Credentials.convertToPem(certs[0]);
4862             byte[] pemChain = null;
4863             if (certs.length > 1) {
4864                 pemChain = Credentials.convertToPem(Arrays.copyOfRange(certs, 1, certs.length));
4865             }
4866             final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm())
4867                     .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded();
4868             return mService.installKeyPair(admin, mContext.getPackageName(), pkcs8Key, pemCert,
4869                     pemChain, alias, requestAccess, isUserSelectable);
4870         } catch (RemoteException e) {
4871             throw e.rethrowFromSystemServer();
4872         } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
4873             Log.w(TAG, "Failed to obtain private key material", e);
4874         } catch (CertificateException | IOException e) {
4875             Log.w(TAG, "Could not pem-encode certificate", e);
4876         }
4877         return false;
4878     }
4879 
4880     /**
4881      * Called by a device or profile owner, or delegated certificate installer, to remove a
4882      * certificate and private key pair installed under a given alias.
4883      *
4884      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4885      *        {@code null} if calling from a delegated certificate installer.
4886      * @param alias The private key alias under which the certificate is installed.
4887      * @return {@code true} if the private key alias no longer exists, {@code false} otherwise.
4888      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4889      *         owner.
4890      * @see #setDelegatedScopes
4891      * @see #DELEGATION_CERT_INSTALL
4892      */
removeKeyPair(@ullable ComponentName admin, @NonNull String alias)4893     public boolean removeKeyPair(@Nullable ComponentName admin, @NonNull String alias) {
4894         throwIfParentInstance("removeKeyPair");
4895         try {
4896             return mService.removeKeyPair(admin, mContext.getPackageName(), alias);
4897         } catch (RemoteException e) {
4898             throw e.rethrowFromSystemServer();
4899         }
4900     }
4901 
4902     /**
4903      * Called by a device or profile owner, or delegated certificate installer, to generate a
4904      * new private/public key pair. If the device supports key generation via secure hardware,
4905      * this method is useful for creating a key in KeyChain that never left the secure hardware.
4906      * Access to the key is controlled the same way as in {@link #installKeyPair}.
4907      *
4908      * <p>Because this method might take several seconds to complete, it should only be called from
4909      * a worker thread. This method returns {@code null} when called from the main thread.
4910      *
4911      * <p>Note: If the provided {@code alias} is of an existing alias, all former grants that apps
4912      * have been given to access the key and certificates associated with this alias will be
4913      * revoked.
4914      *
4915      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
4916      *            {@code null} if calling from a delegated certificate installer.
4917      * @param algorithm The key generation algorithm, see {@link java.security.KeyPairGenerator}.
4918      * @param keySpec Specification of the key to generate, see
4919      * {@link java.security.KeyPairGenerator}.
4920      * @param idAttestationFlags A bitmask of all the identifiers that should be included in the
4921      *        attestation record ({@code ID_TYPE_BASE_INFO}, {@code ID_TYPE_SERIAL},
4922      *        {@code ID_TYPE_IMEI} and {@code ID_TYPE_MEID}), or {@code 0} if no device
4923      *        identification is required in the attestation record.
4924      *        Device owner, profile owner and their delegated certificate installer can use
4925      *        {@link #ID_TYPE_BASE_INFO} to request inclusion of the general device information
4926      *        including manufacturer, model, brand, device and product in the attestation record.
4927      *        Only device owner and their delegated certificate installer can use
4928      *        {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID} to request
4929      *        unique device identifiers to be attested.
4930      *        <p>
4931      *        If any of {@link #ID_TYPE_SERIAL}, {@link #ID_TYPE_IMEI} and {@link #ID_TYPE_MEID}
4932      *        is set, it is implicitly assumed that {@link #ID_TYPE_BASE_INFO} is also set.
4933      *        <p>
4934      *        If any flag is specified, then an attestation challenge must be included in the
4935      *        {@code keySpec}.
4936      * @return A non-null {@code AttestedKeyPair} if the key generation succeeded, null otherwise.
4937      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
4938      *         owner. If Device ID attestation is requested (using {@link #ID_TYPE_SERIAL},
4939      *         {@link #ID_TYPE_IMEI} or {@link #ID_TYPE_MEID}), the caller must be the Device Owner
4940      *         or the Certificate Installer delegate.
4941      * @throws IllegalArgumentException if the alias in {@code keySpec} is empty, if the
4942      *         algorithm specification in {@code keySpec} is not {@code RSAKeyGenParameterSpec}
4943      *         or {@code ECGenParameterSpec}, or if Device ID attestation was requested but the
4944      *         {@code keySpec} does not contain an attestation challenge.
4945      * @throws UnsupportedOperationException if Device ID attestation was requested but the
4946      *         underlying hardware does not support it.
4947      * @throws StrongBoxUnavailableException if the use of StrongBox for key generation was
4948      *         specified in {@code keySpec} but the device does not have one.
4949      * @see KeyGenParameterSpec.Builder#setAttestationChallenge(byte[])
4950      */
generateKeyPair(@ullable ComponentName admin, @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec, @AttestationIdType int idAttestationFlags)4951     public AttestedKeyPair generateKeyPair(@Nullable ComponentName admin,
4952             @NonNull String algorithm, @NonNull KeyGenParameterSpec keySpec,
4953             @AttestationIdType int idAttestationFlags) {
4954         throwIfParentInstance("generateKeyPair");
4955         try {
4956             final ParcelableKeyGenParameterSpec parcelableSpec =
4957                     new ParcelableKeyGenParameterSpec(keySpec);
4958             KeymasterCertificateChain attestationChain = new KeymasterCertificateChain();
4959 
4960             // Translate ID attestation flags to values used by AttestationUtils
4961             final boolean success = mService.generateKeyPair(
4962                     admin, mContext.getPackageName(), algorithm, parcelableSpec,
4963                     idAttestationFlags, attestationChain);
4964             if (!success) {
4965                 Log.e(TAG, "Error generating key via DevicePolicyManagerService.");
4966                 return null;
4967             }
4968 
4969             final String alias = keySpec.getKeystoreAlias();
4970             final KeyPair keyPair = KeyChain.getKeyPair(mContext, alias);
4971             Certificate[] outputChain = null;
4972             try {
4973                 if (AttestationUtils.isChainValid(attestationChain)) {
4974                     outputChain = AttestationUtils.parseCertificateChain(attestationChain);
4975                 }
4976             } catch (KeyAttestationException e) {
4977                 Log.e(TAG, "Error parsing attestation chain for alias " + alias, e);
4978                 mService.removeKeyPair(admin, mContext.getPackageName(), alias);
4979                 return null;
4980             }
4981             return new AttestedKeyPair(keyPair, outputChain);
4982         } catch (RemoteException e) {
4983             throw e.rethrowFromSystemServer();
4984         } catch (KeyChainException e) {
4985             Log.w(TAG, "Failed to generate key", e);
4986         } catch (InterruptedException e) {
4987             Log.w(TAG, "Interrupted while generating key", e);
4988             Thread.currentThread().interrupt();
4989         } catch (ServiceSpecificException e) {
4990             Log.w(TAG, String.format("Key Generation failure: %d", e.errorCode));
4991             switch (e.errorCode) {
4992                 case KEY_GEN_STRONGBOX_UNAVAILABLE:
4993                     throw new StrongBoxUnavailableException("No StrongBox for key generation.");
4994                 default:
4995                     throw new RuntimeException(
4996                             String.format("Unknown error while generating key: %d", e.errorCode));
4997             }
4998         }
4999         return null;
5000     }
5001 
5002     /**
5003      * Returns {@code true} if the device supports attestation of device identifiers in addition
5004      * to key attestation.
5005      * @return {@code true} if Device ID attestation is supported.
5006      */
isDeviceIdAttestationSupported()5007     public boolean isDeviceIdAttestationSupported() {
5008         PackageManager pm = mContext.getPackageManager();
5009         return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ID_ATTESTATION);
5010     }
5011 
5012     /**
5013      * Called by a device or profile owner, or delegated certificate installer, to associate
5014      * certificates with a key pair that was generated using {@link #generateKeyPair}, and
5015      * set whether the key is available for the user to choose in the certificate selection
5016      * prompt.
5017      *
5018      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5019      *            {@code null} if calling from a delegated certificate installer.
5020      * @param alias The private key alias under which to install the certificate. The {@code alias}
5021      *        should denote an existing private key. If a certificate with that alias already
5022      *        exists, it will be overwritten.
5023      * @param certs The certificate chain to install. The chain should start with the leaf
5024      *        certificate and include the chain of trust in order. This will be returned by
5025      *        {@link android.security.KeyChain#getCertificateChain}.
5026      * @param isUserSelectable {@code true} to indicate that a user can select this key via the
5027      *        certificate selection prompt, {@code false} to indicate that this key can only be
5028      *        granted access by implementing
5029      *        {@link android.app.admin.DeviceAdminReceiver#onChoosePrivateKeyAlias}.
5030      * @return {@code true} if the provided {@code alias} exists and the certificates has been
5031      *        successfully associated with it, {@code false} otherwise.
5032      * @throws SecurityException if {@code admin} is not {@code null} and not a device or profile
5033      *         owner, or {@code admin} is null but the calling application is not a delegated
5034      *         certificate installer.
5035      */
setKeyPairCertificate(@ullable ComponentName admin, @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable)5036     public boolean setKeyPairCertificate(@Nullable ComponentName admin,
5037             @NonNull String alias, @NonNull List<Certificate> certs, boolean isUserSelectable) {
5038         throwIfParentInstance("setKeyPairCertificate");
5039         try {
5040             final byte[] pemCert = Credentials.convertToPem(certs.get(0));
5041             byte[] pemChain = null;
5042             if (certs.size() > 1) {
5043                 pemChain = Credentials.convertToPem(
5044                         certs.subList(1, certs.size()).toArray(new Certificate[0]));
5045             }
5046             return mService.setKeyPairCertificate(admin, mContext.getPackageName(), alias, pemCert,
5047                     pemChain, isUserSelectable);
5048         } catch (RemoteException e) {
5049             throw e.rethrowFromSystemServer();
5050         } catch (CertificateException | IOException e) {
5051             Log.w(TAG, "Could not pem-encode certificate", e);
5052         }
5053         return false;
5054     }
5055 
5056 
5057     /**
5058      * @return the alias of a given CA certificate in the certificate store, or {@code null} if it
5059      * doesn't exist.
5060      */
getCaCertAlias(byte[] certBuffer)5061     private static String getCaCertAlias(byte[] certBuffer) throws CertificateException {
5062         final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
5063         final X509Certificate cert = (X509Certificate) certFactory.generateCertificate(
5064                               new ByteArrayInputStream(certBuffer));
5065         return new TrustedCertificateStore().getCertificateAlias(cert);
5066     }
5067 
5068     /**
5069      * Called by a profile owner or device owner to grant access to privileged certificate
5070      * manipulation APIs to a third-party certificate installer app. Granted APIs include
5071      * {@link #getInstalledCaCerts}, {@link #hasCaCertInstalled}, {@link #installCaCert},
5072      * {@link #uninstallCaCert}, {@link #uninstallAllUserCaCerts} and {@link #installKeyPair}.
5073      * <p>
5074      * Delegated certificate installer is a per-user state. The delegated access is persistent until
5075      * it is later cleared by calling this method with a null value or uninstallling the certificate
5076      * installer.
5077      * <p>
5078      * <b>Note:</b>Starting from {@link android.os.Build.VERSION_CODES#N}, if the caller
5079      * application's target SDK version is {@link android.os.Build.VERSION_CODES#N} or newer, the
5080      * supplied certificate installer package must be installed when calling this API, otherwise an
5081      * {@link IllegalArgumentException} will be thrown.
5082      *
5083      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5084      * @param installerPackage The package name of the certificate installer which will be given
5085      *            access. If {@code null} is given the current package will be cleared.
5086      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5087      *
5088      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
5089      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
5090      */
5091     @Deprecated
setCertInstallerPackage(@onNull ComponentName admin, @Nullable String installerPackage)5092     public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String
5093             installerPackage) throws SecurityException {
5094         throwIfParentInstance("setCertInstallerPackage");
5095         if (mService != null) {
5096             try {
5097                 mService.setCertInstallerPackage(admin, installerPackage);
5098             } catch (RemoteException e) {
5099                 throw e.rethrowFromSystemServer();
5100             }
5101         }
5102     }
5103 
5104     /**
5105      * Called by a profile owner or device owner to retrieve the certificate installer for the user,
5106      * or {@code null} if none is set. If there are multiple delegates this function will return one
5107      * of them.
5108      *
5109      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5110      * @return The package name of the current delegated certificate installer, or {@code null} if
5111      *         none is set.
5112      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5113      *
5114      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
5115      * with the {@link #DELEGATION_CERT_INSTALL} scope instead.
5116      */
5117     @Deprecated
getCertInstallerPackage(@onNull ComponentName admin)5118     public @Nullable String getCertInstallerPackage(@NonNull ComponentName admin)
5119             throws SecurityException {
5120         throwIfParentInstance("getCertInstallerPackage");
5121         if (mService != null) {
5122             try {
5123                 return mService.getCertInstallerPackage(admin);
5124             } catch (RemoteException e) {
5125                 throw e.rethrowFromSystemServer();
5126             }
5127         }
5128         return null;
5129     }
5130 
5131     /**
5132      * Called by a profile owner or device owner to grant access to privileged APIs to another app.
5133      * Granted APIs are determined by {@code scopes}, which is a list of the {@code DELEGATION_*}
5134      * constants.
5135      * <p>
5136      * A broadcast with the {@link #ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED} action will be
5137      * sent to the {@code delegatePackage} with its new scopes in an {@code ArrayList<String>} extra
5138      * under the {@link #EXTRA_DELEGATION_SCOPES} key. The broadcast is sent with the
5139      * {@link Intent#FLAG_RECEIVER_REGISTERED_ONLY} flag.
5140      * <p>
5141      * Delegated scopes are a per-user state. The delegated access is persistent until it is later
5142      * cleared by calling this method with an empty {@code scopes} list or uninstalling the
5143      * {@code delegatePackage}.
5144      *
5145      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5146      * @param delegatePackage The package name of the app which will be given access.
5147      * @param scopes The groups of privileged APIs whose access should be granted to
5148      *            {@code delegatedPackage}.
5149      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5150      */
setDelegatedScopes(@onNull ComponentName admin, @NonNull String delegatePackage, @NonNull List<String> scopes)5151      public void setDelegatedScopes(@NonNull ComponentName admin, @NonNull String delegatePackage,
5152             @NonNull List<String> scopes) {
5153         throwIfParentInstance("setDelegatedScopes");
5154         if (mService != null) {
5155             try {
5156                 mService.setDelegatedScopes(admin, delegatePackage, scopes);
5157             } catch (RemoteException e) {
5158                 throw e.rethrowFromSystemServer();
5159             }
5160         }
5161     }
5162 
5163     /**
5164      * Called by a profile owner or device owner to retrieve a list of the scopes given to a
5165      * delegate package. Other apps can use this method to retrieve their own delegated scopes by
5166      * passing {@code null} for {@code admin} and their own package name as
5167      * {@code delegatedPackage}.
5168      *
5169      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
5170      *            {@code null} if the caller is {@code delegatedPackage}.
5171      * @param delegatedPackage The package name of the app whose scopes should be retrieved.
5172      * @return A list containing the scopes given to {@code delegatedPackage}.
5173      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5174      */
5175      @NonNull
getDelegatedScopes(@ullable ComponentName admin, @NonNull String delegatedPackage)5176      public List<String> getDelegatedScopes(@Nullable ComponentName admin,
5177              @NonNull String delegatedPackage) {
5178          throwIfParentInstance("getDelegatedScopes");
5179          if (mService != null) {
5180              try {
5181                  return mService.getDelegatedScopes(admin, delegatedPackage);
5182              } catch (RemoteException e) {
5183                  throw e.rethrowFromSystemServer();
5184              }
5185          }
5186          return null;
5187     }
5188 
5189     /**
5190      * Called by a profile owner or device owner to retrieve a list of delegate packages that were
5191      * granted a delegation scope.
5192      *
5193      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5194      * @param delegationScope The scope whose delegates should be retrieved.
5195      * @return A list of package names of the current delegated packages for
5196                {@code delegationScope}.
5197      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5198      */
5199      @Nullable
getDelegatePackages(@onNull ComponentName admin, @NonNull String delegationScope)5200      public List<String> getDelegatePackages(@NonNull ComponentName admin,
5201              @NonNull String delegationScope) {
5202         throwIfParentInstance("getDelegatePackages");
5203         if (mService != null) {
5204             try {
5205                 return mService.getDelegatePackages(admin, delegationScope);
5206             } catch (RemoteException e) {
5207                 throw e.rethrowFromSystemServer();
5208             }
5209         }
5210         return null;
5211     }
5212 
5213     /**
5214      * Service-specific error code used in implementation of {@code setAlwaysOnVpnPackage} methods.
5215      * @hide
5216      */
5217     public static final int ERROR_VPN_PACKAGE_NOT_FOUND = 1;
5218 
5219     /**
5220      * Called by a device or profile owner to configure an always-on VPN connection through a
5221      * specific application for the current user. This connection is automatically granted and
5222      * persisted after a reboot.
5223      * <p> To support the always-on feature, an app must
5224      * <ul>
5225      *     <li>declare a {@link android.net.VpnService} in its manifest, guarded by
5226      *         {@link android.Manifest.permission#BIND_VPN_SERVICE};</li>
5227      *     <li>target {@link android.os.Build.VERSION_CODES#N API 24} or above; and</li>
5228      *     <li><i>not</i> explicitly opt out of the feature through
5229      *         {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}.</li>
5230      * </ul>
5231      * The call will fail if called with the package name of an unsupported VPN app.
5232      * <p> Enabling lockdown via {@code lockdownEnabled} argument carries the risk that any failure
5233      * of the VPN provider could break networking for all apps. This method clears any lockdown
5234      * whitelist set by {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)}.
5235      *
5236      * @param vpnPackage The package name for an installed VPN app on the device, or {@code null} to
5237      *        remove an existing always-on VPN configuration.
5238      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
5239      *        {@code false} otherwise. This has no effect when clearing.
5240      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5241      * @throws NameNotFoundException if {@code vpnPackage} is not installed.
5242      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does not support being
5243      *         set as always-on, or if always-on VPN is not available.
5244      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
5245      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled)5246     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
5247             boolean lockdownEnabled) throws NameNotFoundException {
5248         setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled, Collections.emptySet());
5249     }
5250 
5251     /**
5252      * A version of {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} that allows the
5253      * admin to specify a set of apps that should be able to access the network directly when VPN
5254      * is not connected. When VPN connects these apps switch over to VPN if allowed to use that VPN.
5255      * System apps can always bypass VPN.
5256      * <p> Note that the system doesn't update the whitelist when packages are installed or
5257      * uninstalled, the admin app must call this method to keep the list up to date.
5258      * <p> When {@code lockdownEnabled} is false {@code lockdownWhitelist} is ignored . When
5259      * {@code lockdownEnabled} is {@code true} and {@code lockdownWhitelist} is {@code null} or
5260      * empty, only system apps can bypass VPN.
5261      * <p> Setting always-on VPN package to {@code null} or using
5262      * {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)} clears lockdown whitelist.
5263      *
5264      * @param vpnPackage package name for an installed VPN app on the device, or {@code null}
5265      *         to remove an existing always-on VPN configuration
5266      * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
5267      *         {@code false} otherwise. This has no effect when clearing.
5268      * @param lockdownWhitelist Packages that will be able to access the network directly when VPN
5269      *         is in lockdown mode but not connected. Has no effect when clearing.
5270      * @throws SecurityException if {@code admin} is not a device or a profile
5271      *         owner.
5272      * @throws NameNotFoundException if {@code vpnPackage} or one of
5273      *         {@code lockdownWhitelist} is not installed.
5274      * @throws UnsupportedOperationException if {@code vpnPackage} exists but does
5275      *         not support being set as always-on, or if always-on VPN is not
5276      *         available.
5277      */
setAlwaysOnVpnPackage(@onNull ComponentName admin, @Nullable String vpnPackage, boolean lockdownEnabled, @Nullable Set<String> lockdownWhitelist)5278     public void setAlwaysOnVpnPackage(@NonNull ComponentName admin, @Nullable String vpnPackage,
5279             boolean lockdownEnabled, @Nullable Set<String> lockdownWhitelist)
5280             throws NameNotFoundException {
5281         throwIfParentInstance("setAlwaysOnVpnPackage");
5282         if (mService != null) {
5283             try {
5284                 mService.setAlwaysOnVpnPackage(admin, vpnPackage, lockdownEnabled,
5285                         lockdownWhitelist == null ? null : new ArrayList<>(lockdownWhitelist));
5286             } catch (ServiceSpecificException e) {
5287                 switch (e.errorCode) {
5288                     case ERROR_VPN_PACKAGE_NOT_FOUND:
5289                         throw new NameNotFoundException(e.getMessage());
5290                     default:
5291                         throw new RuntimeException(
5292                                 "Unknown error setting always-on VPN: " + e.errorCode, e);
5293                 }
5294             } catch (RemoteException e) {
5295                 throw e.rethrowFromSystemServer();
5296             }
5297         }
5298     }
5299 
5300     /**
5301      * Called by device or profile owner to query whether current always-on VPN is configured in
5302      * lockdown mode. Returns {@code false} when no always-on configuration is set.
5303      *
5304      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5305      *
5306      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5307      *
5308      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean)
5309      */
isAlwaysOnVpnLockdownEnabled(@onNull ComponentName admin)5310     public boolean isAlwaysOnVpnLockdownEnabled(@NonNull ComponentName admin) {
5311         throwIfParentInstance("isAlwaysOnVpnLockdownEnabled");
5312         if (mService != null) {
5313             try {
5314                 // Starting from Android R, the caller can pass the permission check in
5315                 // DevicePolicyManagerService if it holds android.permission.MAINLINE_NETWORK_STACK.
5316                 // Note that the android.permission.MAINLINE_NETWORK_STACK is a signature permission
5317                 // which is used by the NetworkStack mainline module.
5318                 return mService.isAlwaysOnVpnLockdownEnabled(admin);
5319             } catch (RemoteException e) {
5320                 throw e.rethrowFromSystemServer();
5321             }
5322         }
5323         return false;
5324     }
5325 
5326     /**
5327      * Called by device or profile owner to query the set of packages that are allowed to access
5328      * the network directly when always-on VPN is in lockdown mode but not connected. Returns
5329      * {@code null} when always-on VPN is not active or not in lockdown mode.
5330      *
5331      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5332      *
5333      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5334      *
5335      * @see #setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
5336      */
getAlwaysOnVpnLockdownWhitelist(@onNull ComponentName admin)5337     public @Nullable Set<String> getAlwaysOnVpnLockdownWhitelist(@NonNull ComponentName admin) {
5338         throwIfParentInstance("getAlwaysOnVpnLockdownWhitelist");
5339         if (mService != null) {
5340             try {
5341                 final List<String> whitelist =
5342                         mService.getAlwaysOnVpnLockdownWhitelist(admin);
5343                 return whitelist == null ? null : new HashSet<>(whitelist);
5344             } catch (RemoteException e) {
5345                 throw e.rethrowFromSystemServer();
5346             }
5347         }
5348         return null;
5349     }
5350 
5351     /**
5352      * Called by a device or profile owner to read the name of the package administering an
5353      * always-on VPN connection for the current user. If there is no such package, or the always-on
5354      * VPN is provided by the system instead of by an application, {@code null} will be returned.
5355      *
5356      * @return Package name of VPN controller responsible for always-on VPN, or {@code null} if none
5357      *         is set.
5358      * @throws SecurityException if {@code admin} is not a device or a profile owner.
5359      */
getAlwaysOnVpnPackage(@onNull ComponentName admin)5360     public @Nullable String getAlwaysOnVpnPackage(@NonNull ComponentName admin) {
5361         throwIfParentInstance("getAlwaysOnVpnPackage");
5362         if (mService != null) {
5363             try {
5364                 return mService.getAlwaysOnVpnPackage(admin);
5365             } catch (RemoteException e) {
5366                 throw e.rethrowFromSystemServer();
5367             }
5368         }
5369         return null;
5370     }
5371 
5372     /**
5373      * Called by an application that is administering the device to disable all cameras on the
5374      * device, for this user. After setting this, no applications running as this user will be able
5375      * to access any cameras on the device.
5376      * <p>
5377      * If the caller is device owner, then the restriction will be applied to all users.
5378      * <p>
5379      * The calling device admin must have requested
5380      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA} to be able to call this method; if it has
5381      * not, a security exception will be thrown.
5382      *
5383      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5384      * @param disabled Whether or not the camera should be disabled.
5385      * @throws SecurityException if {@code admin} is not an active administrator or does not use
5386      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_CAMERA}.
5387      */
setCameraDisabled(@onNull ComponentName admin, boolean disabled)5388     public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) {
5389         throwIfParentInstance("setCameraDisabled");
5390         if (mService != null) {
5391             try {
5392                 mService.setCameraDisabled(admin, disabled);
5393             } catch (RemoteException e) {
5394                 throw e.rethrowFromSystemServer();
5395             }
5396         }
5397     }
5398 
5399     /**
5400      * Determine whether or not the device's cameras have been disabled for this user,
5401      * either by the calling admin, if specified, or all admins.
5402      * @param admin The name of the admin component to check, or {@code null} to check whether any admins
5403      * have disabled the camera
5404      */
getCameraDisabled(@ullable ComponentName admin)5405     public boolean getCameraDisabled(@Nullable ComponentName admin) {
5406         throwIfParentInstance("getCameraDisabled");
5407         return getCameraDisabled(admin, myUserId());
5408     }
5409 
5410     /** @hide per-user version */
5411     @UnsupportedAppUsage
getCameraDisabled(@ullable ComponentName admin, int userHandle)5412     public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) {
5413         if (mService != null) {
5414             try {
5415                 return mService.getCameraDisabled(admin, userHandle);
5416             } catch (RemoteException e) {
5417                 throw e.rethrowFromSystemServer();
5418             }
5419         }
5420         return false;
5421     }
5422 
5423     /**
5424      * Called by a device owner to request a bugreport.
5425      * <p>
5426      * If the device contains secondary users or profiles, they must be affiliated with the device.
5427      * Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
5428      *
5429      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5430      * @return {@code true} if the bugreport collection started successfully, or {@code false} if it
5431      *         wasn't triggered because a previous bugreport operation is still active (either the
5432      *         bugreport is still running or waiting for the user to share or decline)
5433      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
5434      *         profile or secondary user that is not affiliated with the device.
5435      * @see #isAffiliatedUser
5436      */
requestBugreport(@onNull ComponentName admin)5437     public boolean requestBugreport(@NonNull ComponentName admin) {
5438         throwIfParentInstance("requestBugreport");
5439         if (mService != null) {
5440             try {
5441                 return mService.requestBugreport(admin);
5442             } catch (RemoteException e) {
5443                 throw e.rethrowFromSystemServer();
5444             }
5445         }
5446         return false;
5447     }
5448 
5449     /**
5450      * Determine whether or not creating a guest user has been disabled for the device
5451      *
5452      * @hide
5453      */
getGuestUserDisabled(@ullable ComponentName admin)5454     public boolean getGuestUserDisabled(@Nullable ComponentName admin) {
5455         // Currently guest users can always be created if multi-user is enabled
5456         // TODO introduce a policy for guest user creation
5457         return false;
5458     }
5459 
5460     /**
5461      * Called by a device/profile owner to set whether the screen capture is disabled. Disabling
5462      * screen capture also prevents the content from being shown on display devices that do not have
5463      * a secure video output. See {@link android.view.Display#FLAG_SECURE} for more details about
5464      * secure surfaces and secure displays.
5465      * <p>
5466      * The calling device admin must be a device or profile owner. If it is not, a security
5467      * exception will be thrown.
5468      * <p>
5469      * From version {@link android.os.Build.VERSION_CODES#M} disabling screen capture also blocks
5470      * assist requests for all activities of the relevant user.
5471      *
5472      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5473      * @param disabled Whether screen capture is disabled or not.
5474      * @throws SecurityException if {@code admin} is not a device or profile owner.
5475      */
setScreenCaptureDisabled(@onNull ComponentName admin, boolean disabled)5476     public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) {
5477         throwIfParentInstance("setScreenCaptureDisabled");
5478         if (mService != null) {
5479             try {
5480                 mService.setScreenCaptureDisabled(admin, disabled);
5481             } catch (RemoteException e) {
5482                 throw e.rethrowFromSystemServer();
5483             }
5484         }
5485     }
5486 
5487     /**
5488      * Determine whether or not screen capture has been disabled by the calling
5489      * admin, if specified, or all admins.
5490      * @param admin The name of the admin component to check, or {@code null} to check whether any admins
5491      * have disabled screen capture.
5492      */
getScreenCaptureDisabled(@ullable ComponentName admin)5493     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) {
5494         throwIfParentInstance("getScreenCaptureDisabled");
5495         return getScreenCaptureDisabled(admin, myUserId());
5496     }
5497 
5498     /** @hide per-user version */
getScreenCaptureDisabled(@ullable ComponentName admin, int userHandle)5499     public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) {
5500         if (mService != null) {
5501             try {
5502                 return mService.getScreenCaptureDisabled(admin, userHandle);
5503             } catch (RemoteException e) {
5504                 throw e.rethrowFromSystemServer();
5505             }
5506         }
5507         return false;
5508     }
5509 
5510     /**
5511      * Called by a device owner, or alternatively a profile owner from Android 8.0 (API level 26) or
5512      * higher, to set whether auto time is required. If auto time is required, no user will be able
5513      * set the date and time and network date and time will be used.
5514      * <p>
5515      * Note: if auto time is required the user can still manually set the time zone.
5516      * <p>
5517      * The calling device admin must be a device owner, or alternatively a profile owner from
5518      * Android 8.0 (API level 26) or higher. If it is not, a security exception will be thrown.
5519      *
5520      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5521      * @param required Whether auto time is set required or not.
5522      * @throws SecurityException if {@code admin} is not a device owner.
5523      */
setAutoTimeRequired(@onNull ComponentName admin, boolean required)5524     public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) {
5525         throwIfParentInstance("setAutoTimeRequired");
5526         if (mService != null) {
5527             try {
5528                 mService.setAutoTimeRequired(admin, required);
5529             } catch (RemoteException e) {
5530                 throw e.rethrowFromSystemServer();
5531             }
5532         }
5533     }
5534 
5535     /**
5536      * @return true if auto time is required.
5537      */
getAutoTimeRequired()5538     public boolean getAutoTimeRequired() {
5539         throwIfParentInstance("getAutoTimeRequired");
5540         if (mService != null) {
5541             try {
5542                 return mService.getAutoTimeRequired();
5543             } catch (RemoteException e) {
5544                 throw e.rethrowFromSystemServer();
5545             }
5546         }
5547         return false;
5548     }
5549 
5550     /**
5551      * Called by a device owner to set whether all users created on the device should be ephemeral.
5552      * <p>
5553      * The system user is exempt from this policy - it is never ephemeral.
5554      * <p>
5555      * The calling device admin must be the device owner. If it is not, a security exception will be
5556      * thrown.
5557      *
5558      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5559      * @param forceEphemeralUsers If true, all the existing users will be deleted and all
5560      *            subsequently created users will be ephemeral.
5561      * @throws SecurityException if {@code admin} is not a device owner.
5562      * @hide
5563      */
setForceEphemeralUsers( @onNull ComponentName admin, boolean forceEphemeralUsers)5564     public void setForceEphemeralUsers(
5565             @NonNull ComponentName admin, boolean forceEphemeralUsers) {
5566         throwIfParentInstance("setForceEphemeralUsers");
5567         if (mService != null) {
5568             try {
5569                 mService.setForceEphemeralUsers(admin, forceEphemeralUsers);
5570             } catch (RemoteException e) {
5571                 throw e.rethrowFromSystemServer();
5572             }
5573         }
5574     }
5575 
5576     /**
5577      * @return true if all users are created ephemeral.
5578      * @throws SecurityException if {@code admin} is not a device owner.
5579      * @hide
5580      */
getForceEphemeralUsers(@onNull ComponentName admin)5581     public boolean getForceEphemeralUsers(@NonNull ComponentName admin) {
5582         throwIfParentInstance("getForceEphemeralUsers");
5583         if (mService != null) {
5584             try {
5585                 return mService.getForceEphemeralUsers(admin);
5586             } catch (RemoteException e) {
5587                 throw e.rethrowFromSystemServer();
5588             }
5589         }
5590         return false;
5591     }
5592 
5593     /**
5594      * Called by an application that is administering the device to disable keyguard customizations,
5595      * such as widgets. After setting this, keyguard features will be disabled according to the
5596      * provided feature list.
5597      * <p>
5598      * The calling device admin must have requested
5599      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
5600      * if it has not, a security exception will be thrown.
5601      * <p>
5602      * Calling this from a managed profile before version {@link android.os.Build.VERSION_CODES#M}
5603      * will throw a security exception. From version {@link android.os.Build.VERSION_CODES#M} the
5604      * profile owner of a managed profile can set:
5605      * <ul>
5606      * <li>{@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which affects the parent user, but only if there
5607      * is no separate challenge set on the managed profile.
5608      * <li>{@link #KEYGUARD_DISABLE_FINGERPRINT}, {@link #KEYGUARD_DISABLE_FACE} or
5609      * {@link #KEYGUARD_DISABLE_IRIS} which affects the managed profile challenge if
5610      * there is one, or the parent user otherwise.
5611      * <li>{@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS} which affects notifications generated
5612      * by applications in the managed profile.
5613      * </ul>
5614      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, {@link #KEYGUARD_DISABLE_FINGERPRINT},
5615      * {@link #KEYGUARD_DISABLE_FACE} and {@link #KEYGUARD_DISABLE_IRIS} can also be
5616      * set on the {@link DevicePolicyManager} instance returned by
5617      * {@link #getParentProfileInstance(ComponentName)} in order to set restrictions on the parent
5618      * profile.
5619      * <p>
5620      * Requests to disable other features on a managed profile will be ignored.
5621      * <p>
5622      * The admin can check which features have been disabled by calling
5623      * {@link #getKeyguardDisabledFeatures(ComponentName)}
5624      *
5625      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
5626      * @param which The disabled features flag which can be either
5627      *            {@link #KEYGUARD_DISABLE_FEATURES_NONE} (default),
5628      *            {@link #KEYGUARD_DISABLE_FEATURES_ALL}, or a combination of
5629      *            {@link #KEYGUARD_DISABLE_WIDGETS_ALL}, {@link #KEYGUARD_DISABLE_SECURE_CAMERA},
5630      *            {@link #KEYGUARD_DISABLE_SECURE_NOTIFICATIONS},
5631      *            {@link #KEYGUARD_DISABLE_TRUST_AGENTS},
5632      *            {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS},
5633      *            {@link #KEYGUARD_DISABLE_FINGERPRINT},
5634      *            {@link #KEYGUARD_DISABLE_FACE},
5635      *            {@link #KEYGUARD_DISABLE_IRIS}.
5636      * @throws SecurityException if {@code admin} is not an active administrator or does not user
5637      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
5638      */
setKeyguardDisabledFeatures(@onNull ComponentName admin, int which)5639     public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) {
5640         if (mService != null) {
5641             try {
5642                 mService.setKeyguardDisabledFeatures(admin, which, mParentInstance);
5643             } catch (RemoteException e) {
5644                 throw e.rethrowFromSystemServer();
5645             }
5646         }
5647     }
5648 
5649     /**
5650      * Determine whether or not features have been disabled in keyguard either by the calling
5651      * admin, if specified, or all admins that set restrictions on this user and its participating
5652      * profiles. Restrictions on profiles that have a separate challenge are not taken into account.
5653      *
5654      * <p>This method can be called on the {@link DevicePolicyManager} instance
5655      * returned by {@link #getParentProfileInstance(ComponentName)} in order to retrieve
5656      * restrictions on the parent profile.
5657      *
5658      * @param admin The name of the admin component to check, or {@code null} to check whether any
5659      * admins have disabled features in keyguard.
5660      * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)}
5661      * for a list.
5662      */
getKeyguardDisabledFeatures(@ullable ComponentName admin)5663     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) {
5664         return getKeyguardDisabledFeatures(admin, myUserId());
5665     }
5666 
5667     /** @hide per-user version */
5668     @UnsupportedAppUsage
getKeyguardDisabledFeatures(@ullable ComponentName admin, int userHandle)5669     public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) {
5670         if (mService != null) {
5671             try {
5672                 return mService.getKeyguardDisabledFeatures(admin, userHandle, mParentInstance);
5673             } catch (RemoteException e) {
5674                 throw e.rethrowFromSystemServer();
5675             }
5676         }
5677         return KEYGUARD_DISABLE_FEATURES_NONE;
5678     }
5679 
5680     /**
5681      * @hide
5682      */
5683     @UnsupportedAppUsage
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing, int userHandle)5684     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing,
5685             int userHandle) {
5686         if (mService != null) {
5687             try {
5688                 mService.setActiveAdmin(policyReceiver, refreshing, userHandle);
5689             } catch (RemoteException e) {
5690                 throw e.rethrowFromSystemServer();
5691             }
5692         }
5693     }
5694 
5695     /**
5696      * @hide
5697      */
5698     @UnsupportedAppUsage
setActiveAdmin(@onNull ComponentName policyReceiver, boolean refreshing)5699     public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) {
5700         setActiveAdmin(policyReceiver, refreshing, myUserId());
5701     }
5702 
5703     /**
5704      * @hide
5705      */
getRemoveWarning(@ullable ComponentName admin, RemoteCallback result)5706     public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) {
5707         if (mService != null) {
5708             try {
5709                 mService.getRemoveWarning(admin, result, myUserId());
5710             } catch (RemoteException e) {
5711                 throw e.rethrowFromSystemServer();
5712             }
5713         }
5714     }
5715 
5716     /**
5717      * @hide
5718      */
5719     @UnsupportedAppUsage
5720     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setActivePasswordState(PasswordMetrics metrics, int userHandle)5721     public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
5722         if (mService != null) {
5723             try {
5724                 mService.setActivePasswordState(metrics, userHandle);
5725             } catch (RemoteException e) {
5726                 throw e.rethrowFromSystemServer();
5727             }
5728         }
5729     }
5730 
5731     /**
5732      * @hide
5733      */
5734     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportPasswordChanged(@serIdInt int userId)5735     public void reportPasswordChanged(@UserIdInt int userId) {
5736         if (mService != null) {
5737             try {
5738                 mService.reportPasswordChanged(userId);
5739             } catch (RemoteException e) {
5740                 throw e.rethrowFromSystemServer();
5741             }
5742         }
5743     }
5744 
5745     /**
5746      * @hide
5747      */
5748     @UnsupportedAppUsage
5749     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedPasswordAttempt(int userHandle)5750     public void reportFailedPasswordAttempt(int userHandle) {
5751         if (mService != null) {
5752             try {
5753                 mService.reportFailedPasswordAttempt(userHandle);
5754             } catch (RemoteException e) {
5755                 throw e.rethrowFromSystemServer();
5756             }
5757         }
5758     }
5759 
5760     /**
5761      * @hide
5762      */
5763     @UnsupportedAppUsage
5764     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulPasswordAttempt(int userHandle)5765     public void reportSuccessfulPasswordAttempt(int userHandle) {
5766         if (mService != null) {
5767             try {
5768                 mService.reportSuccessfulPasswordAttempt(userHandle);
5769             } catch (RemoteException e) {
5770                 throw e.rethrowFromSystemServer();
5771             }
5772         }
5773     }
5774 
5775     /**
5776      * @hide
5777      */
5778     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportFailedBiometricAttempt(int userHandle)5779     public void reportFailedBiometricAttempt(int userHandle) {
5780         if (mService != null) {
5781             try {
5782                 mService.reportFailedBiometricAttempt(userHandle);
5783             } catch (RemoteException e) {
5784                 throw e.rethrowFromSystemServer();
5785             }
5786         }
5787     }
5788 
5789     /**
5790      * @hide
5791      */
5792     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
reportSuccessfulBiometricAttempt(int userHandle)5793     public void reportSuccessfulBiometricAttempt(int userHandle) {
5794         if (mService != null) {
5795             try {
5796                 mService.reportSuccessfulBiometricAttempt(userHandle);
5797             } catch (RemoteException e) {
5798                 throw e.rethrowFromSystemServer();
5799             }
5800         }
5801     }
5802 
5803     /**
5804      * Should be called when keyguard has been dismissed.
5805      * @hide
5806      */
reportKeyguardDismissed(int userHandle)5807     public void reportKeyguardDismissed(int userHandle) {
5808         if (mService != null) {
5809             try {
5810                 mService.reportKeyguardDismissed(userHandle);
5811             } catch (RemoteException e) {
5812                 throw e.rethrowFromSystemServer();
5813             }
5814         }
5815     }
5816 
5817     /**
5818      * Should be called when keyguard view has been shown to the user.
5819      * @hide
5820      */
reportKeyguardSecured(int userHandle)5821     public void reportKeyguardSecured(int userHandle) {
5822         if (mService != null) {
5823             try {
5824                 mService.reportKeyguardSecured(userHandle);
5825             } catch (RemoteException e) {
5826                 throw e.rethrowFromSystemServer();
5827             }
5828         }
5829     }
5830 
5831     /**
5832      * @hide
5833      * Sets the given package as the device owner.
5834      * Same as {@link #setDeviceOwner(ComponentName, String)} but without setting a device owner name.
5835      * @param who the component name to be registered as device owner.
5836      * @return whether the package was successfully registered as the device owner.
5837      * @throws IllegalArgumentException if the package name is null or invalid
5838      * @throws IllegalStateException If the preconditions mentioned are not met.
5839      */
setDeviceOwner(ComponentName who)5840     public boolean setDeviceOwner(ComponentName who) {
5841         return setDeviceOwner(who, null);
5842     }
5843 
5844     /**
5845      * @hide
5846      */
setDeviceOwner(ComponentName who, int userId)5847     public boolean setDeviceOwner(ComponentName who, int userId)  {
5848         return setDeviceOwner(who, null, userId);
5849     }
5850 
5851     /**
5852      * @hide
5853      */
setDeviceOwner(ComponentName who, String ownerName)5854     public boolean setDeviceOwner(ComponentName who, String ownerName) {
5855         return setDeviceOwner(who, ownerName, UserHandle.USER_SYSTEM);
5856     }
5857 
5858     /**
5859      * @hide
5860      * Sets the given package as the device owner. The package must already be installed. There
5861      * must not already be a device owner.
5862      * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
5863      * this method.
5864      * Calling this after the setup phase of the primary user has completed is allowed only if
5865      * the caller is the shell uid, and there are no additional users and no accounts.
5866      * @param who the component name to be registered as device owner.
5867      * @param ownerName the human readable name of the institution that owns this device.
5868      * @param userId ID of the user on which the device owner runs.
5869      * @return whether the package was successfully registered as the device owner.
5870      * @throws IllegalArgumentException if the package name is null or invalid
5871      * @throws IllegalStateException If the preconditions mentioned are not met.
5872      */
setDeviceOwner(ComponentName who, String ownerName, int userId)5873     public boolean setDeviceOwner(ComponentName who, String ownerName, int userId)
5874             throws IllegalArgumentException, IllegalStateException {
5875         if (mService != null) {
5876             try {
5877                 return mService.setDeviceOwner(who, ownerName, userId);
5878             } catch (RemoteException re) {
5879                 throw re.rethrowFromSystemServer();
5880             }
5881         }
5882         return false;
5883     }
5884 
5885     /**
5886      * Used to determine if a particular package has been registered as a Device Owner app.
5887      * A device owner app is a special device admin that cannot be deactivated by the user, once
5888      * activated as a device admin. It also cannot be uninstalled. To check whether a particular
5889      * package is currently registered as the device owner app, pass in the package name from
5890      * {@link Context#getPackageName()} to this method.<p/>This is useful for device
5891      * admin apps that want to check whether they are also registered as the device owner app. The
5892      * exact mechanism by which a device admin app is registered as a device owner app is defined by
5893      * the setup process.
5894      * @param packageName the package name of the app, to compare with the registered device owner
5895      * app, if any.
5896      * @return whether or not the package is registered as the device owner app.
5897      */
isDeviceOwnerApp(String packageName)5898     public boolean isDeviceOwnerApp(String packageName) {
5899         throwIfParentInstance("isDeviceOwnerApp");
5900         return isDeviceOwnerAppOnCallingUser(packageName);
5901     }
5902 
5903     /**
5904      * @return true if a package is registered as device owner, only when it's running on the
5905      * calling user.
5906      *
5907      * <p>Same as {@link #isDeviceOwnerApp}, but bundled code should use it for clarity.
5908      * @hide
5909      */
isDeviceOwnerAppOnCallingUser(String packageName)5910     public boolean isDeviceOwnerAppOnCallingUser(String packageName) {
5911         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ true);
5912     }
5913 
5914     /**
5915      * @return true if a package is registered as device owner, even if it's running on a different
5916      * user.
5917      *
5918      * <p>Requires the MANAGE_USERS permission.
5919      *
5920      * @hide
5921      */
isDeviceOwnerAppOnAnyUser(String packageName)5922     public boolean isDeviceOwnerAppOnAnyUser(String packageName) {
5923         return isDeviceOwnerAppOnAnyUserInner(packageName, /* callingUserOnly =*/ false);
5924     }
5925 
5926     /**
5927      * @return device owner component name, only when it's running on the calling user.
5928      *
5929      * @hide
5930      */
getDeviceOwnerComponentOnCallingUser()5931     public ComponentName getDeviceOwnerComponentOnCallingUser() {
5932         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ true);
5933     }
5934 
5935     /**
5936      * @return device owner component name, even if it's running on a different user.
5937      *
5938      * @hide
5939      */
5940     @SystemApi
5941     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwnerComponentOnAnyUser()5942     public ComponentName getDeviceOwnerComponentOnAnyUser() {
5943         return getDeviceOwnerComponentInner(/* callingUserOnly =*/ false);
5944     }
5945 
isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly)5946     private boolean isDeviceOwnerAppOnAnyUserInner(String packageName, boolean callingUserOnly) {
5947         if (packageName == null) {
5948             return false;
5949         }
5950         final ComponentName deviceOwner = getDeviceOwnerComponentInner(callingUserOnly);
5951         if (deviceOwner == null) {
5952             return false;
5953         }
5954         return packageName.equals(deviceOwner.getPackageName());
5955     }
5956 
getDeviceOwnerComponentInner(boolean callingUserOnly)5957     private ComponentName getDeviceOwnerComponentInner(boolean callingUserOnly) {
5958         if (mService != null) {
5959             try {
5960                 return mService.getDeviceOwnerComponent(callingUserOnly);
5961             } catch (RemoteException re) {
5962                 throw re.rethrowFromSystemServer();
5963             }
5964         }
5965         return null;
5966     }
5967 
5968     /**
5969      * @return Handle of the user who runs device owner, or {@code null} if there's no device owner.
5970      *
5971      * @hide
5972      */
5973     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
5974     @SystemApi
getDeviceOwnerUser()5975     public @Nullable UserHandle getDeviceOwnerUser() {
5976         if (mService != null) {
5977             try {
5978                 int userId = mService.getDeviceOwnerUserId();
5979 
5980                 if (userId != UserHandle.USER_NULL) {
5981                     return UserHandle.of(userId);
5982                 }
5983             } catch (RemoteException re) {
5984                 throw re.rethrowFromSystemServer();
5985             }
5986         }
5987         return null;
5988     }
5989 
5990     /**
5991      * @hide
5992      */
getDeviceOwnerUserId()5993     public int getDeviceOwnerUserId() {
5994         if (mService != null) {
5995             try {
5996                 return mService.getDeviceOwnerUserId();
5997             } catch (RemoteException re) {
5998                 throw re.rethrowFromSystemServer();
5999             }
6000         }
6001         return UserHandle.USER_NULL;
6002     }
6003 
6004     /**
6005      * Clears the current device owner. The caller must be the device owner. This function should be
6006      * used cautiously as once it is called it cannot be undone. The device owner can only be set as
6007      * a part of device setup, before it completes.
6008      * <p>
6009      * While some policies previously set by the device owner will be cleared by this method, it is
6010      * a best-effort process and some other policies will still remain in place after the device
6011      * owner is cleared.
6012      *
6013      * @param packageName The package name of the device owner.
6014      * @throws SecurityException if the caller is not in {@code packageName} or {@code packageName}
6015      *             does not own the current device owner component.
6016      *
6017      * @deprecated This method is expected to be used for testing purposes only. The device owner
6018      * will lose control of the device and its data after calling it. In order to protect any
6019      * sensitive data that remains on the device, it is advised that the device owner factory resets
6020      * the device instead of calling this method. See {@link #wipeData(int)}.
6021      */
6022     @Deprecated
clearDeviceOwnerApp(String packageName)6023     public void clearDeviceOwnerApp(String packageName) {
6024         throwIfParentInstance("clearDeviceOwnerApp");
6025         if (mService != null) {
6026             try {
6027                 mService.clearDeviceOwner(packageName);
6028             } catch (RemoteException re) {
6029                 throw re.rethrowFromSystemServer();
6030             }
6031         }
6032     }
6033 
6034     /**
6035      * Returns the device owner package name, only if it's running on the calling user.
6036      *
6037      * <p>Bundled components should use {@code getDeviceOwnerComponentOnCallingUser()} for clarity.
6038      *
6039      * @hide
6040      */
6041     @SystemApi
6042     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwner()6043     public @Nullable String getDeviceOwner() {
6044         throwIfParentInstance("getDeviceOwner");
6045         final ComponentName name = getDeviceOwnerComponentOnCallingUser();
6046         return name != null ? name.getPackageName() : null;
6047     }
6048 
6049     /**
6050      * Called by the system to find out whether the device is managed by a Device Owner.
6051      *
6052      * @return whether the device is managed by a Device Owner.
6053      * @throws SecurityException if the caller is not the device owner, does not hold the
6054      *         MANAGE_USERS permission and is not the system.
6055      *
6056      * @hide
6057      */
6058     @SystemApi
6059     @TestApi
6060     @SuppressLint("Doclava125")
isDeviceManaged()6061     public boolean isDeviceManaged() {
6062         try {
6063             return mService.hasDeviceOwner();
6064         } catch (RemoteException re) {
6065             throw re.rethrowFromSystemServer();
6066         }
6067     }
6068 
6069     /**
6070      * Returns the device owner name.  Note this method *will* return the device owner
6071      * name when it's running on a different user.
6072      *
6073      * @hide
6074      */
6075     @SystemApi
6076     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getDeviceOwnerNameOnAnyUser()6077     public String getDeviceOwnerNameOnAnyUser() {
6078         throwIfParentInstance("getDeviceOwnerNameOnAnyUser");
6079         if (mService != null) {
6080             try {
6081                 return mService.getDeviceOwnerName();
6082             } catch (RemoteException re) {
6083                 throw re.rethrowFromSystemServer();
6084             }
6085         }
6086         return null;
6087     }
6088 
6089     /**
6090      * @hide
6091      * @deprecated Do not use
6092      * @removed
6093      */
6094     @Deprecated
6095     @SystemApi
6096     @SuppressLint("Doclava125")
getDeviceInitializerApp()6097     public @Nullable String getDeviceInitializerApp() {
6098         return null;
6099     }
6100 
6101     /**
6102      * @hide
6103      * @deprecated Do not use
6104      * @removed
6105      */
6106     @Deprecated
6107     @SystemApi
6108     @SuppressLint("Doclava125")
getDeviceInitializerComponent()6109     public @Nullable ComponentName getDeviceInitializerComponent() {
6110         return null;
6111     }
6112 
6113     /**
6114      * @hide
6115      * @deprecated Use #ACTION_SET_PROFILE_OWNER
6116      * Sets the given component as an active admin and registers the package as the profile
6117      * owner for this user. The package must already be installed and there shouldn't be
6118      * an existing profile owner registered for this user. Also, this method must be called
6119      * before the user setup has been completed.
6120      * <p>
6121      * This method can only be called by system apps that hold MANAGE_USERS permission and
6122      * MANAGE_DEVICE_ADMINS permission.
6123      * @param admin The component to register as an active admin and profile owner.
6124      * @param ownerName The user-visible name of the entity that is managing this user.
6125      * @return whether the admin was successfully registered as the profile owner.
6126      * @throws IllegalArgumentException if packageName is null, the package isn't installed, or
6127      *         the user has already been set up.
6128      */
6129     @Deprecated
6130     @SystemApi
6131     @RequiresPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS)
setActiveProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName)6132     public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName)
6133             throws IllegalArgumentException {
6134         throwIfParentInstance("setActiveProfileOwner");
6135         if (mService != null) {
6136             try {
6137                 final int myUserId = myUserId();
6138                 mService.setActiveAdmin(admin, false, myUserId);
6139                 return mService.setProfileOwner(admin, ownerName, myUserId);
6140             } catch (RemoteException re) {
6141                 throw re.rethrowFromSystemServer();
6142             }
6143         }
6144         return false;
6145     }
6146 
6147     /**
6148      * Clears the active profile owner. The caller must be the profile owner of this user, otherwise
6149      * a SecurityException will be thrown. This method is not available to managed profile owners.
6150      * <p>
6151      * While some policies previously set by the profile owner will be cleared by this method, it is
6152      * a best-effort process and some other policies will still remain in place after the profile
6153      * owner is cleared.
6154      *
6155      * @param admin The component to remove as the profile owner.
6156      * @throws SecurityException if {@code admin} is not an active profile owner, or the method is
6157      * being called from a managed profile.
6158      *
6159      * @deprecated This method is expected to be used for testing purposes only. The profile owner
6160      * will lose control of the user and its data after calling it. In order to protect any
6161      * sensitive data that remains on this user, it is advised that the profile owner deletes it
6162      * instead of calling this method. See {@link #wipeData(int)}.
6163      */
6164     @Deprecated
clearProfileOwner(@onNull ComponentName admin)6165     public void clearProfileOwner(@NonNull ComponentName admin) {
6166         throwIfParentInstance("clearProfileOwner");
6167         if (mService != null) {
6168             try {
6169                 mService.clearProfileOwner(admin);
6170             } catch (RemoteException re) {
6171                 throw re.rethrowFromSystemServer();
6172             }
6173         }
6174     }
6175 
6176     /**
6177      * @hide
6178      * Checks whether the user was already setup.
6179      */
hasUserSetupCompleted()6180     public boolean hasUserSetupCompleted() {
6181         if (mService != null) {
6182             try {
6183                 return mService.hasUserSetupCompleted();
6184             } catch (RemoteException re) {
6185                 throw re.rethrowFromSystemServer();
6186             }
6187         }
6188         return true;
6189     }
6190 
6191     /**
6192      * @hide
6193      * Sets the given component as the profile owner of the given user profile. The package must
6194      * already be installed. There must not already be a profile owner for this user.
6195      * Only apps with the MANAGE_PROFILE_AND_DEVICE_OWNERS permission and the shell uid can call
6196      * this method.
6197      * Calling this after the setup phase of the specified user has completed is allowed only if:
6198      * - the caller is SYSTEM_UID.
6199      * - or the caller is the shell uid, and there are no accounts on the specified user.
6200      * @param admin the component name to be registered as profile owner.
6201      * @param ownerName the human readable name of the organisation associated with this DPM.
6202      * @param userHandle the userId to set the profile owner for.
6203      * @return whether the component was successfully registered as the profile owner.
6204      * @throws IllegalArgumentException if admin is null, the package isn't installed, or the
6205      * preconditions mentioned are not met.
6206      */
setProfileOwner(@onNull ComponentName admin, @Deprecated String ownerName, int userHandle)6207     public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName,
6208             int userHandle) throws IllegalArgumentException {
6209         if (mService != null) {
6210             try {
6211                 if (ownerName == null) {
6212                     ownerName = "";
6213                 }
6214                 return mService.setProfileOwner(admin, ownerName, userHandle);
6215             } catch (RemoteException re) {
6216                 throw re.rethrowFromSystemServer();
6217             }
6218         }
6219         return false;
6220     }
6221 
6222     /**
6223      * Sets the device owner information to be shown on the lock screen.
6224      * <p>
6225      * If the device owner information is {@code null} or empty then the device owner info is
6226      * cleared and the user owner info is shown on the lock screen if it is set.
6227      * <p>
6228      * If the device owner information contains only whitespaces then the message on the lock screen
6229      * will be blank and the user will not be allowed to change it.
6230      * <p>
6231      * If the device owner information needs to be localized, it is the responsibility of the
6232      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
6233      * and set a new version of this string accordingly.
6234      *
6235      * @param admin The name of the admin component to check.
6236      * @param info Device owner information which will be displayed instead of the user owner info.
6237      * @throws SecurityException if {@code admin} is not a device owner.
6238      */
setDeviceOwnerLockScreenInfo(@onNull ComponentName admin, CharSequence info)6239     public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
6240         throwIfParentInstance("setDeviceOwnerLockScreenInfo");
6241         if (mService != null) {
6242             try {
6243                 mService.setDeviceOwnerLockScreenInfo(admin, info);
6244             } catch (RemoteException re) {
6245                 throw re.rethrowFromSystemServer();
6246             }
6247         }
6248     }
6249 
6250     /**
6251      * @return The device owner information. If it is not set returns {@code null}.
6252      */
getDeviceOwnerLockScreenInfo()6253     public CharSequence getDeviceOwnerLockScreenInfo() {
6254         throwIfParentInstance("getDeviceOwnerLockScreenInfo");
6255         if (mService != null) {
6256             try {
6257                 return mService.getDeviceOwnerLockScreenInfo();
6258             } catch (RemoteException re) {
6259                 throw re.rethrowFromSystemServer();
6260             }
6261         }
6262         return null;
6263     }
6264 
6265     /**
6266      * Called by device or profile owners to suspend packages for this user. This function can be
6267      * called by a device owner, profile owner, or by a delegate given the
6268      * {@link #DELEGATION_PACKAGE_ACCESS} scope via {@link #setDelegatedScopes}.
6269      * <p>
6270      * A suspended package will not be able to start activities. Its notifications will be hidden,
6271      * it will not show up in recents, will not be able to show toasts or dialogs or ring the
6272      * device.
6273      * <p>
6274      * The package must already be installed. If the package is uninstalled while suspended the
6275      * package will no longer be suspended. The admin can block this by using
6276      * {@link #setUninstallBlocked}.
6277      *
6278      * @param admin The name of the admin component to check, or {@code null} if the caller is a
6279      *            package access delegate.
6280      * @param packageNames The package names to suspend or unsuspend.
6281      * @param suspended If set to {@code true} than the packages will be suspended, if set to
6282      *            {@code false} the packages will be unsuspended.
6283      * @return an array of package names for which the suspended status is not set as requested in
6284      *         this method.
6285      * @throws SecurityException if {@code admin} is not a device or profile owner.
6286      * @see #setDelegatedScopes
6287      * @see #DELEGATION_PACKAGE_ACCESS
6288      */
setPackagesSuspended(@onNull ComponentName admin, @NonNull String[] packageNames, boolean suspended)6289     public @NonNull String[] setPackagesSuspended(@NonNull ComponentName admin,
6290             @NonNull String[] packageNames, boolean suspended) {
6291         throwIfParentInstance("setPackagesSuspended");
6292         if (mService != null) {
6293             try {
6294                 return mService.setPackagesSuspended(admin, mContext.getPackageName(), packageNames,
6295                         suspended);
6296             } catch (RemoteException re) {
6297                 throw re.rethrowFromSystemServer();
6298             }
6299         }
6300         return packageNames;
6301     }
6302 
6303     /**
6304      * Determine if a package is suspended. This function can be called by a device owner, profile
6305      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
6306      * {@link #setDelegatedScopes}.
6307      *
6308      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6309      *            {@code null} if the caller is a package access delegate.
6310      * @param packageName The name of the package to retrieve the suspended status of.
6311      * @return {@code true} if the package is suspended or {@code false} if the package is not
6312      *         suspended, could not be found or an error occurred.
6313      * @throws SecurityException if {@code admin} is not a device or profile owner.
6314      * @throws NameNotFoundException if the package could not be found.
6315      * @see #setDelegatedScopes
6316      * @see #DELEGATION_PACKAGE_ACCESS
6317      */
isPackageSuspended(@onNull ComponentName admin, String packageName)6318     public boolean isPackageSuspended(@NonNull ComponentName admin, String packageName)
6319             throws NameNotFoundException {
6320         throwIfParentInstance("isPackageSuspended");
6321         if (mService != null) {
6322             try {
6323                 return mService.isPackageSuspended(admin, mContext.getPackageName(), packageName);
6324             } catch (RemoteException e) {
6325                 throw e.rethrowFromSystemServer();
6326             } catch (IllegalArgumentException ex) {
6327                 throw new NameNotFoundException(packageName);
6328             }
6329         }
6330         return false;
6331     }
6332 
6333     /**
6334      * Sets the enabled state of the profile. A profile should be enabled only once it is ready to
6335      * be used. Only the profile owner can call this.
6336      *
6337      * @see #isProfileOwnerApp
6338      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6339      * @throws SecurityException if {@code admin} is not a profile owner.
6340      */
setProfileEnabled(@onNull ComponentName admin)6341     public void setProfileEnabled(@NonNull ComponentName admin) {
6342         throwIfParentInstance("setProfileEnabled");
6343         if (mService != null) {
6344             try {
6345                 mService.setProfileEnabled(admin);
6346             } catch (RemoteException e) {
6347                 throw e.rethrowFromSystemServer();
6348             }
6349         }
6350     }
6351 
6352     /**
6353      * Sets the name of the profile. In the device owner case it sets the name of the user which it
6354      * is called from. Only a profile owner or device owner can call this. If this is never called
6355      * by the profile or device owner, the name will be set to default values.
6356      *
6357      * @see #isProfileOwnerApp
6358      * @see #isDeviceOwnerApp
6359      * @param admin Which {@link DeviceAdminReceiver} this request is associate with.
6360      * @param profileName The name of the profile.
6361      * @throws SecurityException if {@code admin} is not a device or profile owner.
6362      */
setProfileName(@onNull ComponentName admin, String profileName)6363     public void setProfileName(@NonNull ComponentName admin, String profileName) {
6364         throwIfParentInstance("setProfileName");
6365         if (mService != null) {
6366             try {
6367                 mService.setProfileName(admin, profileName);
6368             } catch (RemoteException e) {
6369                 throw e.rethrowFromSystemServer();
6370             }
6371         }
6372     }
6373 
6374     /**
6375      * Used to determine if a particular package is registered as the profile owner for the
6376      * user. A profile owner is a special device admin that has additional privileges
6377      * within the profile.
6378      *
6379      * @param packageName The package name of the app to compare with the registered profile owner.
6380      * @return Whether or not the package is registered as the profile owner.
6381      */
isProfileOwnerApp(String packageName)6382     public boolean isProfileOwnerApp(String packageName) {
6383         throwIfParentInstance("isProfileOwnerApp");
6384         if (mService != null) {
6385             try {
6386                 ComponentName profileOwner = mService.getProfileOwner(myUserId());
6387                 return profileOwner != null
6388                         && profileOwner.getPackageName().equals(packageName);
6389             } catch (RemoteException re) {
6390                 throw re.rethrowFromSystemServer();
6391             }
6392         }
6393         return false;
6394     }
6395 
6396     /**
6397      * @hide
6398      * @return the packageName of the owner of the given user profile or {@code null} if no profile
6399      * owner has been set for that user.
6400      * @throws IllegalArgumentException if the userId is invalid.
6401      */
6402     @SystemApi
getProfileOwner()6403     public @Nullable ComponentName getProfileOwner() throws IllegalArgumentException {
6404         throwIfParentInstance("getProfileOwner");
6405         return getProfileOwnerAsUser(mContext.getUserId());
6406     }
6407 
6408     /**
6409      * @see #getProfileOwner()
6410      * @hide
6411      */
6412     @RequiresPermission(value = android.Manifest.permission.INTERACT_ACROSS_USERS,
6413             conditional = true)
getProfileOwnerAsUser(@onNull UserHandle user)6414     public @Nullable ComponentName getProfileOwnerAsUser(@NonNull UserHandle user) {
6415         if (mService != null) {
6416             try {
6417                 return mService.getProfileOwnerAsUser(user.getIdentifier());
6418             } catch (RemoteException re) {
6419                 throw re.rethrowFromSystemServer();
6420             }
6421         }
6422         return null;
6423     }
6424 
6425     /**
6426      * @hide
6427      */
6428     @UnsupportedAppUsage
getProfileOwnerAsUser(final int userId)6429     public @Nullable ComponentName getProfileOwnerAsUser(final int userId) {
6430         if (mService != null) {
6431             try {
6432                 return mService.getProfileOwnerAsUser(userId);
6433             } catch (RemoteException re) {
6434                 throw re.rethrowFromSystemServer();
6435             }
6436         }
6437         return null;
6438     }
6439 
6440     /**
6441      * @hide
6442      * @return the human readable name of the organisation associated with this DPM or {@code null}
6443      *         if one is not set.
6444      * @throws IllegalArgumentException if the userId is invalid.
6445      */
getProfileOwnerName()6446     public @Nullable String getProfileOwnerName() throws IllegalArgumentException {
6447         if (mService != null) {
6448             try {
6449                 return mService.getProfileOwnerName(mContext.getUserId());
6450             } catch (RemoteException re) {
6451                 throw re.rethrowFromSystemServer();
6452             }
6453         }
6454         return null;
6455     }
6456 
6457     /**
6458      * @hide
6459      * @param userId The user for whom to fetch the profile owner name, if any.
6460      * @return the human readable name of the organisation associated with this profile owner or
6461      *         null if one is not set.
6462      * @throws IllegalArgumentException if the userId is invalid.
6463      */
6464     @SystemApi
6465     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getProfileOwnerNameAsUser(int userId)6466     public @Nullable String getProfileOwnerNameAsUser(int userId) throws IllegalArgumentException {
6467         throwIfParentInstance("getProfileOwnerNameAsUser");
6468         if (mService != null) {
6469             try {
6470                 return mService.getProfileOwnerName(userId);
6471             } catch (RemoteException re) {
6472                 throw re.rethrowFromSystemServer();
6473             }
6474         }
6475         return null;
6476     }
6477 
6478     /**
6479      * Returns whether the specified package can read the device identifiers.
6480      *
6481      * @param packageName The package name of the app to check for device identifier access.
6482      * @param pid The process id of the package to be checked.
6483      * @param uid The uid of the package to be checked.
6484      * @return whether the package can read the device identifiers.
6485      *
6486      * @hide
6487      */
checkDeviceIdentifierAccess(String packageName, int pid, int uid)6488     public boolean checkDeviceIdentifierAccess(String packageName, int pid, int uid) {
6489         throwIfParentInstance("checkDeviceIdentifierAccess");
6490         if (packageName == null) {
6491             return false;
6492         }
6493         if (mService != null) {
6494             try {
6495                 return mService.checkDeviceIdentifierAccess(packageName, pid, uid);
6496             } catch (RemoteException re) {
6497                 throw re.rethrowFromSystemServer();
6498             }
6499         }
6500         return false;
6501     }
6502 
6503     /**
6504      * Called by a profile owner or device owner to set a default activity that the system selects
6505      * to handle intents that match the given {@link IntentFilter}. This activity will remain the
6506      * default intent handler even if the set of potential event handlers for the intent filter
6507      * changes and if the intent preferences are reset.
6508      * <p>
6509      * Note that the caller should still declare the activity in the manifest, the API just sets
6510      * the activity to be the default one to handle the given intent filter.
6511      * <p>
6512      * The default disambiguation mechanism takes over if the activity is not installed (anymore).
6513      * When the activity is (re)installed, it is automatically reset as default intent handler for
6514      * the filter.
6515      * <p>
6516      * The calling device admin must be a profile owner or device owner. If it is not, a security
6517      * exception will be thrown.
6518      *
6519      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6520      * @param filter The IntentFilter for which a default handler is added.
6521      * @param activity The Activity that is added as default intent handler.
6522      * @throws SecurityException if {@code admin} is not a device or profile owner.
6523      */
addPersistentPreferredActivity(@onNull ComponentName admin, IntentFilter filter, @NonNull ComponentName activity)6524     public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter,
6525             @NonNull ComponentName activity) {
6526         throwIfParentInstance("addPersistentPreferredActivity");
6527         if (mService != null) {
6528             try {
6529                 mService.addPersistentPreferredActivity(admin, filter, activity);
6530             } catch (RemoteException e) {
6531                 throw e.rethrowFromSystemServer();
6532             }
6533         }
6534     }
6535 
6536     /**
6537      * Called by a profile owner or device owner to remove all persistent intent handler preferences
6538      * associated with the given package that were set by {@link #addPersistentPreferredActivity}.
6539      * <p>
6540      * The calling device admin must be a profile owner. If it is not, a security exception will be
6541      * thrown.
6542      *
6543      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6544      * @param packageName The name of the package for which preferences are removed.
6545      * @throws SecurityException if {@code admin} is not a device or profile owner.
6546      */
clearPackagePersistentPreferredActivities(@onNull ComponentName admin, String packageName)6547     public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin,
6548             String packageName) {
6549         throwIfParentInstance("clearPackagePersistentPreferredActivities");
6550         if (mService != null) {
6551             try {
6552                 mService.clearPackagePersistentPreferredActivities(admin, packageName);
6553             } catch (RemoteException e) {
6554                 throw e.rethrowFromSystemServer();
6555             }
6556         }
6557     }
6558 
6559     /**
6560      * Called by a device owner to set the default SMS application.
6561      * <p>
6562      * The calling device admin must be a device owner. If it is not, a security exception will be
6563      * thrown.
6564      *
6565      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6566      * @param packageName The name of the package to set as the default SMS application.
6567      * @throws SecurityException if {@code admin} is not a device owner.
6568      */
setDefaultSmsApplication(@onNull ComponentName admin, @NonNull String packageName)6569     public void setDefaultSmsApplication(@NonNull ComponentName admin,
6570             @NonNull String packageName) {
6571         throwIfParentInstance("setDefaultSmsApplication");
6572         if (mService != null) {
6573             try {
6574                 mService.setDefaultSmsApplication(admin, packageName);
6575             } catch (RemoteException e) {
6576                 throw e.rethrowFromSystemServer();
6577             }
6578         }
6579     }
6580 
6581     /**
6582      * Called by a profile owner or device owner to grant permission to a package to manage
6583      * application restrictions for the calling user via {@link #setApplicationRestrictions} and
6584      * {@link #getApplicationRestrictions}.
6585      * <p>
6586      * This permission is persistent until it is later cleared by calling this method with a
6587      * {@code null} value or uninstalling the managing package.
6588      * <p>
6589      * The supplied application restriction managing package must be installed when calling this
6590      * API, otherwise an {@link NameNotFoundException} will be thrown.
6591      *
6592      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6593      * @param packageName The package name which will be given access to application restrictions
6594      *            APIs. If {@code null} is given the current package will be cleared.
6595      * @throws SecurityException if {@code admin} is not a device or profile owner.
6596      * @throws NameNotFoundException if {@code packageName} is not found
6597      *
6598      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #setDelegatedScopes}
6599      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
6600      */
6601     @Deprecated
setApplicationRestrictionsManagingPackage(@onNull ComponentName admin, @Nullable String packageName)6602     public void setApplicationRestrictionsManagingPackage(@NonNull ComponentName admin,
6603             @Nullable String packageName) throws NameNotFoundException {
6604         throwIfParentInstance("setApplicationRestrictionsManagingPackage");
6605         if (mService != null) {
6606             try {
6607                 if (!mService.setApplicationRestrictionsManagingPackage(admin, packageName)) {
6608                     throw new NameNotFoundException(packageName);
6609                 }
6610             } catch (RemoteException e) {
6611                 throw e.rethrowFromSystemServer();
6612             }
6613         }
6614     }
6615 
6616     /**
6617      * Called by a profile owner or device owner to retrieve the application restrictions managing
6618      * package for the current user, or {@code null} if none is set. If there are multiple
6619      * delegates this function will return one of them.
6620      *
6621      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6622      * @return The package name allowed to manage application restrictions on the current user, or
6623      *         {@code null} if none is set.
6624      * @throws SecurityException if {@code admin} is not a device or profile owner.
6625      *
6626      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatePackages}
6627      * with the {@link #DELEGATION_APP_RESTRICTIONS} scope instead.
6628      */
6629     @Deprecated
6630     @Nullable
getApplicationRestrictionsManagingPackage( @onNull ComponentName admin)6631     public String getApplicationRestrictionsManagingPackage(
6632             @NonNull ComponentName admin) {
6633         throwIfParentInstance("getApplicationRestrictionsManagingPackage");
6634         if (mService != null) {
6635             try {
6636                 return mService.getApplicationRestrictionsManagingPackage(admin);
6637             } catch (RemoteException e) {
6638                 throw e.rethrowFromSystemServer();
6639             }
6640         }
6641         return null;
6642     }
6643 
6644     /**
6645      * Called by any application to find out whether it has been granted permission via
6646      * {@link #setApplicationRestrictionsManagingPackage} to manage application restrictions
6647      * for the calling user.
6648      *
6649      * <p>This is done by comparing the calling Linux uid with the uid of the package specified by
6650      * that method.
6651      *
6652      * @deprecated From {@link android.os.Build.VERSION_CODES#O}. Use {@link #getDelegatedScopes}
6653      * instead.
6654      */
6655     @Deprecated
isCallerApplicationRestrictionsManagingPackage()6656     public boolean isCallerApplicationRestrictionsManagingPackage() {
6657         throwIfParentInstance("isCallerApplicationRestrictionsManagingPackage");
6658         if (mService != null) {
6659             try {
6660                 return mService.isCallerApplicationRestrictionsManagingPackage(
6661                         mContext.getPackageName());
6662             } catch (RemoteException e) {
6663                 throw e.rethrowFromSystemServer();
6664             }
6665         }
6666         return false;
6667     }
6668 
6669     /**
6670      * Sets the application restrictions for a given target application running in the calling user.
6671      * <p>
6672      * The caller must be a profile or device owner on that user, or the package allowed to manage
6673      * application restrictions via {@link #setDelegatedScopes} with the
6674      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
6675      * <p>
6676      * The provided {@link Bundle} consists of key-value pairs, where the types of values may be:
6677      * <ul>
6678      * <li>{@code boolean}
6679      * <li>{@code int}
6680      * <li>{@code String} or {@code String[]}
6681      * <li>From {@link android.os.Build.VERSION_CODES#M}, {@code Bundle} or {@code Bundle[]}
6682      * </ul>
6683      * <p>
6684      * If the restrictions are not available yet, but may be applied in the near future, the caller
6685      * can notify the target application of that by adding
6686      * {@link UserManager#KEY_RESTRICTIONS_PENDING} to the settings parameter.
6687      * <p>
6688      * The application restrictions are only made visible to the target application via
6689      * {@link UserManager#getApplicationRestrictions(String)}, in addition to the profile or device
6690      * owner, and the application restrictions managing package via
6691      * {@link #getApplicationRestrictions}.
6692      *
6693      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
6694      *
6695      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
6696      *            {@code null} if called by the application restrictions managing package.
6697      * @param packageName The name of the package to update restricted settings for.
6698      * @param settings A {@link Bundle} to be parsed by the receiving application, conveying a new
6699      *            set of active restrictions.
6700      * @throws SecurityException if {@code admin} is not a device or profile owner.
6701      * @see #setDelegatedScopes
6702      * @see #DELEGATION_APP_RESTRICTIONS
6703      * @see UserManager#KEY_RESTRICTIONS_PENDING
6704      */
6705     @WorkerThread
setApplicationRestrictions(@ullable ComponentName admin, String packageName, Bundle settings)6706     public void setApplicationRestrictions(@Nullable ComponentName admin, String packageName,
6707             Bundle settings) {
6708         throwIfParentInstance("setApplicationRestrictions");
6709         if (mService != null) {
6710             try {
6711                 mService.setApplicationRestrictions(admin, mContext.getPackageName(), packageName,
6712                         settings);
6713             } catch (RemoteException e) {
6714                 throw e.rethrowFromSystemServer();
6715             }
6716         }
6717     }
6718 
6719     /**
6720      * Sets a list of configuration features to enable for a trust agent component. This is meant to
6721      * be used in conjunction with {@link #KEYGUARD_DISABLE_TRUST_AGENTS}, which disables all trust
6722      * agents but those enabled by this function call. If flag
6723      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} is not set, then this call has no effect.
6724      * <p>
6725      * For any specific trust agent, whether it is disabled or not depends on the aggregated state
6726      * of each admin's {@link #KEYGUARD_DISABLE_TRUST_AGENTS} setting and its trust agent
6727      * configuration as set by this function call. In particular: if any admin sets
6728      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and does not additionally set any
6729      * trust agent configuration, the trust agent is disabled completely. Otherwise, the trust agent
6730      * will receive the list of configurations from all admins who set
6731      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} and aggregate the configurations to determine its
6732      * behavior. The exact meaning of aggregation is trust-agent-specific.
6733      * <p>
6734      * The calling device admin must have requested
6735      * {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES} to be able to call this method;
6736      * if not, a security exception will be thrown.
6737      * <p>
6738      * This method can be called on the {@link DevicePolicyManager} instance returned by
6739      * {@link #getParentProfileInstance(ComponentName)} in order to set the configuration for
6740      * the parent profile.
6741      * <p>
6742      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, calling
6743      * this method has no effect - no trust agent configuration will be set.
6744      *
6745      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6746      * @param target Component name of the agent to be configured.
6747      * @param configuration Trust-agent-specific feature configuration bundle. Please consult
6748      *        documentation of the specific trust agent to determine the interpretation of this
6749      *        bundle.
6750      * @throws SecurityException if {@code admin} is not an active administrator or does not use
6751      *             {@link DeviceAdminInfo#USES_POLICY_DISABLE_KEYGUARD_FEATURES}
6752      */
6753     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
setTrustAgentConfiguration(@onNull ComponentName admin, @NonNull ComponentName target, PersistableBundle configuration)6754     public void setTrustAgentConfiguration(@NonNull ComponentName admin,
6755             @NonNull ComponentName target, PersistableBundle configuration) {
6756         if (mService != null) {
6757             try {
6758                 mService.setTrustAgentConfiguration(admin, target, configuration, mParentInstance);
6759             } catch (RemoteException e) {
6760                 throw e.rethrowFromSystemServer();
6761             }
6762         }
6763     }
6764 
6765     /**
6766      * Gets configuration for the given trust agent based on aggregating all calls to
6767      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)} for
6768      * all device admins.
6769      * <p>
6770      * This method can be called on the {@link DevicePolicyManager} instance returned by
6771      * {@link #getParentProfileInstance(ComponentName)} in order to retrieve the configuration set
6772      * on the parent profile.
6773      * <p>
6774      * On devices not supporting {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature, null is
6775      * always returned.
6776      *
6777      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. If null,
6778      * this function returns a list of configurations for all admins that declare
6779      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS}. If any admin declares
6780      * {@link #KEYGUARD_DISABLE_TRUST_AGENTS} but doesn't call
6781      * {@link #setTrustAgentConfiguration(ComponentName, ComponentName, PersistableBundle)}
6782      * for this {@param agent} or calls it with a null configuration, null is returned.
6783      * @param agent Which component to get enabled features for.
6784      * @return configuration for the given trust agent.
6785      */
6786     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent)6787     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
6788             @Nullable ComponentName admin, @NonNull ComponentName agent) {
6789         return getTrustAgentConfiguration(admin, agent, myUserId());
6790     }
6791 
6792     /** @hide per-user version */
6793     @UnsupportedAppUsage
6794     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
getTrustAgentConfiguration( @ullable ComponentName admin, @NonNull ComponentName agent, int userHandle)6795     public @Nullable List<PersistableBundle> getTrustAgentConfiguration(
6796             @Nullable ComponentName admin, @NonNull ComponentName agent, int userHandle) {
6797         if (mService != null) {
6798             try {
6799                 return mService.getTrustAgentConfiguration(admin, agent, userHandle,
6800                         mParentInstance);
6801             } catch (RemoteException e) {
6802                 throw e.rethrowFromSystemServer();
6803             }
6804         }
6805         return new ArrayList<PersistableBundle>(); // empty list
6806     }
6807 
6808     /**
6809      * Called by a profile owner of a managed profile to set whether caller-Id information from the
6810      * managed profile will be shown in the parent profile, for incoming calls.
6811      * <p>
6812      * The calling device admin must be a profile owner. If it is not, a security exception will be
6813      * thrown.
6814      *
6815      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6816      * @param disabled If true caller-Id information in the managed profile is not displayed.
6817      * @throws SecurityException if {@code admin} is not a profile owner.
6818      */
setCrossProfileCallerIdDisabled(@onNull ComponentName admin, boolean disabled)6819     public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) {
6820         throwIfParentInstance("setCrossProfileCallerIdDisabled");
6821         if (mService != null) {
6822             try {
6823                 mService.setCrossProfileCallerIdDisabled(admin, disabled);
6824             } catch (RemoteException e) {
6825                 throw e.rethrowFromSystemServer();
6826             }
6827         }
6828     }
6829 
6830     /**
6831      * Called by a profile owner of a managed profile to determine whether or not caller-Id
6832      * information has been disabled.
6833      * <p>
6834      * The calling device admin must be a profile owner. If it is not, a security exception will be
6835      * thrown.
6836      *
6837      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6838      * @throws SecurityException if {@code admin} is not a profile owner.
6839      */
getCrossProfileCallerIdDisabled(@onNull ComponentName admin)6840     public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) {
6841         throwIfParentInstance("getCrossProfileCallerIdDisabled");
6842         if (mService != null) {
6843             try {
6844                 return mService.getCrossProfileCallerIdDisabled(admin);
6845             } catch (RemoteException e) {
6846                 throw e.rethrowFromSystemServer();
6847             }
6848         }
6849         return false;
6850     }
6851 
6852     /**
6853      * Determine whether or not caller-Id information has been disabled.
6854      *
6855      * @param userHandle The user for whom to check the caller-id permission
6856      * @hide
6857      */
getCrossProfileCallerIdDisabled(UserHandle userHandle)6858     public boolean getCrossProfileCallerIdDisabled(UserHandle userHandle) {
6859         if (mService != null) {
6860             try {
6861                 return mService.getCrossProfileCallerIdDisabledForUser(userHandle.getIdentifier());
6862             } catch (RemoteException e) {
6863                 throw e.rethrowFromSystemServer();
6864             }
6865         }
6866         return false;
6867     }
6868 
6869     /**
6870      * Called by a profile owner of a managed profile to set whether contacts search from the
6871      * managed profile will be shown in the parent profile, for incoming calls.
6872      * <p>
6873      * The calling device admin must be a profile owner. If it is not, a security exception will be
6874      * thrown.
6875      *
6876      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6877      * @param disabled If true contacts search in the managed profile is not displayed.
6878      * @throws SecurityException if {@code admin} is not a profile owner.
6879      */
setCrossProfileContactsSearchDisabled(@onNull ComponentName admin, boolean disabled)6880     public void setCrossProfileContactsSearchDisabled(@NonNull ComponentName admin,
6881             boolean disabled) {
6882         throwIfParentInstance("setCrossProfileContactsSearchDisabled");
6883         if (mService != null) {
6884             try {
6885                 mService.setCrossProfileContactsSearchDisabled(admin, disabled);
6886             } catch (RemoteException e) {
6887                 throw e.rethrowFromSystemServer();
6888             }
6889         }
6890     }
6891 
6892     /**
6893      * Called by a profile owner of a managed profile to determine whether or not contacts search
6894      * has been disabled.
6895      * <p>
6896      * The calling device admin must be a profile owner. If it is not, a security exception will be
6897      * thrown.
6898      *
6899      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6900      * @throws SecurityException if {@code admin} is not a profile owner.
6901      */
getCrossProfileContactsSearchDisabled(@onNull ComponentName admin)6902     public boolean getCrossProfileContactsSearchDisabled(@NonNull ComponentName admin) {
6903         throwIfParentInstance("getCrossProfileContactsSearchDisabled");
6904         if (mService != null) {
6905             try {
6906                 return mService.getCrossProfileContactsSearchDisabled(admin);
6907             } catch (RemoteException e) {
6908                 throw e.rethrowFromSystemServer();
6909             }
6910         }
6911         return false;
6912     }
6913 
6914 
6915     /**
6916      * Determine whether or not contacts search has been disabled.
6917      *
6918      * @param userHandle The user for whom to check the contacts search permission
6919      * @hide
6920      */
getCrossProfileContactsSearchDisabled(@onNull UserHandle userHandle)6921     public boolean getCrossProfileContactsSearchDisabled(@NonNull UserHandle userHandle) {
6922         if (mService != null) {
6923             try {
6924                 return mService
6925                         .getCrossProfileContactsSearchDisabledForUser(userHandle.getIdentifier());
6926             } catch (RemoteException e) {
6927                 throw e.rethrowFromSystemServer();
6928             }
6929         }
6930         return false;
6931     }
6932 
6933     /**
6934      * Start Quick Contact on the managed profile for the user, if the policy allows.
6935      *
6936      * @hide
6937      */
startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long directoryId, Intent originalIntent)6938     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
6939             boolean isContactIdIgnored, long directoryId, Intent originalIntent) {
6940         if (mService != null) {
6941             try {
6942                 mService.startManagedQuickContact(actualLookupKey, actualContactId,
6943                         isContactIdIgnored, directoryId, originalIntent);
6944             } catch (RemoteException e) {
6945                 throw e.rethrowFromSystemServer();
6946             }
6947         }
6948     }
6949 
6950     /**
6951      * Start Quick Contact on the managed profile for the user, if the policy allows.
6952      * @hide
6953      */
startManagedQuickContact(String actualLookupKey, long actualContactId, Intent originalIntent)6954     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
6955             Intent originalIntent) {
6956         startManagedQuickContact(actualLookupKey, actualContactId, false, Directory.DEFAULT,
6957                 originalIntent);
6958     }
6959 
6960     /**
6961      * Called by a profile owner of a managed profile to set whether bluetooth devices can access
6962      * enterprise contacts.
6963      * <p>
6964      * The calling device admin must be a profile owner. If it is not, a security exception will be
6965      * thrown.
6966      * <p>
6967      * This API works on managed profile only.
6968      *
6969      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6970      * @param disabled If true, bluetooth devices cannot access enterprise contacts.
6971      * @throws SecurityException if {@code admin} is not a profile owner.
6972      */
setBluetoothContactSharingDisabled(@onNull ComponentName admin, boolean disabled)6973     public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) {
6974         throwIfParentInstance("setBluetoothContactSharingDisabled");
6975         if (mService != null) {
6976             try {
6977                 mService.setBluetoothContactSharingDisabled(admin, disabled);
6978             } catch (RemoteException e) {
6979                 throw e.rethrowFromSystemServer();
6980             }
6981         }
6982     }
6983 
6984     /**
6985      * Called by a profile owner of a managed profile to determine whether or not Bluetooth devices
6986      * cannot access enterprise contacts.
6987      * <p>
6988      * The calling device admin must be a profile owner. If it is not, a security exception will be
6989      * thrown.
6990      * <p>
6991      * This API works on managed profile only.
6992      *
6993      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
6994      * @throws SecurityException if {@code admin} is not a profile owner.
6995      */
getBluetoothContactSharingDisabled(@onNull ComponentName admin)6996     public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) {
6997         throwIfParentInstance("getBluetoothContactSharingDisabled");
6998         if (mService != null) {
6999             try {
7000                 return mService.getBluetoothContactSharingDisabled(admin);
7001             } catch (RemoteException e) {
7002                 throw e.rethrowFromSystemServer();
7003             }
7004         }
7005         return true;
7006     }
7007 
7008     /**
7009      * Determine whether or not Bluetooth devices cannot access contacts.
7010      * <p>
7011      * This API works on managed profile UserHandle only.
7012      *
7013      * @param userHandle The user for whom to check the caller-id permission
7014      * @hide
7015      */
7016     @SystemApi
7017     @RequiresPermission(permission.INTERACT_ACROSS_USERS)
getBluetoothContactSharingDisabled(@onNull UserHandle userHandle)7018     public boolean getBluetoothContactSharingDisabled(@NonNull UserHandle userHandle) {
7019         if (mService != null) {
7020             try {
7021                 return mService.getBluetoothContactSharingDisabledForUser(userHandle
7022                         .getIdentifier());
7023             } catch (RemoteException e) {
7024                 throw e.rethrowFromSystemServer();
7025             }
7026         }
7027         return true;
7028     }
7029 
7030     /**
7031      * Called by the profile owner of a managed profile so that some intents sent in the managed
7032      * profile can also be resolved in the parent, or vice versa. Only activity intents are
7033      * supported.
7034      *
7035      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7036      * @param filter The {@link IntentFilter} the intent has to match to be also resolved in the
7037      *            other profile
7038      * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and
7039      *            {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported.
7040      * @throws SecurityException if {@code admin} is not a device or profile owner.
7041      */
addCrossProfileIntentFilter(@onNull ComponentName admin, IntentFilter filter, int flags)7042     public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) {
7043         throwIfParentInstance("addCrossProfileIntentFilter");
7044         if (mService != null) {
7045             try {
7046                 mService.addCrossProfileIntentFilter(admin, filter, flags);
7047             } catch (RemoteException e) {
7048                 throw e.rethrowFromSystemServer();
7049             }
7050         }
7051     }
7052 
7053     /**
7054      * Called by a profile owner of a managed profile to remove the cross-profile intent filters
7055      * that go from the managed profile to the parent, or from the parent to the managed profile.
7056      * Only removes those that have been set by the profile owner.
7057      * <p>
7058      * <em>Note</em>: A list of default cross profile intent filters are set up by the system when
7059      * the profile is created, some of them ensure the proper functioning of the profile, while
7060      * others enable sharing of data from the parent to the managed profile for user convenience.
7061      * These default intent filters are not cleared when this API is called. If the default cross
7062      * profile data sharing is not desired, they can be disabled with
7063      * {@link UserManager#DISALLOW_SHARE_INTO_MANAGED_PROFILE}.
7064      *
7065      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7066      * @throws SecurityException if {@code admin} is not a profile owner.
7067      */
clearCrossProfileIntentFilters(@onNull ComponentName admin)7068     public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) {
7069         throwIfParentInstance("clearCrossProfileIntentFilters");
7070         if (mService != null) {
7071             try {
7072                 mService.clearCrossProfileIntentFilters(admin);
7073             } catch (RemoteException e) {
7074                 throw e.rethrowFromSystemServer();
7075             }
7076         }
7077     }
7078 
7079     /**
7080      * Called by a profile or device owner to set the permitted
7081      * {@link android.accessibilityservice.AccessibilityService}. When set by
7082      * a device owner or profile owner the restriction applies to all profiles of the user the
7083      * device owner or profile owner is an admin for. By default, the user can use any accessibility
7084      * service. When zero or more packages have been added, accessibility services that are not in
7085      * the list and not part of the system can not be enabled by the user.
7086      * <p>
7087      * Calling with a null value for the list disables the restriction so that all services can be
7088      * used, calling with an empty list only allows the built-in system services. Any non-system
7089      * accessibility service that's currently enabled must be included in the list.
7090      * <p>
7091      * System accessibility services are always available to the user the list can't modify this.
7092      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7093      * @param packageNames List of accessibility service package names.
7094      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
7095      *         contain every enabled non-system accessibility service.
7096      * @throws SecurityException if {@code admin} is not a device or profile owner.
7097      */
setPermittedAccessibilityServices(@onNull ComponentName admin, List<String> packageNames)7098     public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin,
7099             List<String> packageNames) {
7100         throwIfParentInstance("setPermittedAccessibilityServices");
7101         if (mService != null) {
7102             try {
7103                 return mService.setPermittedAccessibilityServices(admin, packageNames);
7104             } catch (RemoteException e) {
7105                 throw e.rethrowFromSystemServer();
7106             }
7107         }
7108         return false;
7109     }
7110 
7111     /**
7112      * Returns the list of permitted accessibility services set by this device or profile owner.
7113      * <p>
7114      * An empty list means no accessibility services except system services are allowed. Null means
7115      * all accessibility services are allowed.
7116      *
7117      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7118      * @return List of accessiblity service package names.
7119      * @throws SecurityException if {@code admin} is not a device or profile owner.
7120      */
getPermittedAccessibilityServices(@onNull ComponentName admin)7121     public @Nullable List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) {
7122         throwIfParentInstance("getPermittedAccessibilityServices");
7123         if (mService != null) {
7124             try {
7125                 return mService.getPermittedAccessibilityServices(admin);
7126             } catch (RemoteException e) {
7127                 throw e.rethrowFromSystemServer();
7128             }
7129         }
7130         return null;
7131     }
7132 
7133     /**
7134      * Called by the system to check if a specific accessibility service is disabled by admin.
7135      *
7136      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7137      * @param packageName Accessibility service package name that needs to be checked.
7138      * @param userHandle user id the admin is running as.
7139      * @return true if the accessibility service is permitted, otherwise false.
7140      *
7141      * @hide
7142      */
isAccessibilityServicePermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)7143     public boolean isAccessibilityServicePermittedByAdmin(@NonNull ComponentName admin,
7144             @NonNull String packageName, int userHandle) {
7145         if (mService != null) {
7146             try {
7147                 return mService.isAccessibilityServicePermittedByAdmin(admin, packageName,
7148                         userHandle);
7149             } catch (RemoteException e) {
7150                 throw e.rethrowFromSystemServer();
7151             }
7152         }
7153         return false;
7154     }
7155 
7156     /**
7157      * Returns the list of accessibility services permitted by the device or profiles
7158      * owners of this user.
7159      *
7160      * <p>Null means all accessibility services are allowed, if a non-null list is returned
7161      * it will contain the intersection of the permitted lists for any device or profile
7162      * owners that apply to this user. It will also include any system accessibility services.
7163      *
7164      * @param userId which user to check for.
7165      * @return List of accessiblity service package names.
7166      * @hide
7167      */
7168      @SystemApi
7169      @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getPermittedAccessibilityServices(int userId)7170      public @Nullable List<String> getPermittedAccessibilityServices(int userId) {
7171         throwIfParentInstance("getPermittedAccessibilityServices");
7172         if (mService != null) {
7173             try {
7174                 return mService.getPermittedAccessibilityServicesForUser(userId);
7175             } catch (RemoteException e) {
7176                 throw e.rethrowFromSystemServer();
7177             }
7178         }
7179         return null;
7180      }
7181 
7182     /**
7183      * Called by a profile or device owner to set the permitted input methods services for this
7184      * user. By default, the user can use any input method.
7185      * <p>
7186      * When zero or more packages have been added, input method that are not in the list and not
7187      * part of the system can not be enabled by the user. This method will fail if it is called for
7188      * a admin that is not for the foreground user or a profile of the foreground user. Any
7189      * non-system input method service that's currently enabled must be included in the list.
7190      * <p>
7191      * Calling with a null value for the list disables the restriction so that all input methods can
7192      * be used, calling with an empty list disables all but the system's own input methods.
7193      * <p>
7194      * System input methods are always available to the user - this method can't modify this.
7195      *
7196      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7197      * @param packageNames List of input method package names.
7198      * @return {@code true} if the operation succeeded, or {@code false} if the list didn't
7199      *        contain every enabled non-system input method service.
7200      * @throws SecurityException if {@code admin} is not a device or profile owner.
7201      */
setPermittedInputMethods( @onNull ComponentName admin, List<String> packageNames)7202     public boolean setPermittedInputMethods(
7203             @NonNull ComponentName admin, List<String> packageNames) {
7204         throwIfParentInstance("setPermittedInputMethods");
7205         if (mService != null) {
7206             try {
7207                 return mService.setPermittedInputMethods(admin, packageNames);
7208             } catch (RemoteException e) {
7209                 throw e.rethrowFromSystemServer();
7210             }
7211         }
7212         return false;
7213     }
7214 
7215 
7216     /**
7217      * Returns the list of permitted input methods set by this device or profile owner.
7218      * <p>
7219      * An empty list means no input methods except system input methods are allowed. Null means all
7220      * input methods are allowed.
7221      *
7222      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7223      * @return List of input method package names.
7224      * @throws SecurityException if {@code admin} is not a device or profile owner.
7225      */
getPermittedInputMethods(@onNull ComponentName admin)7226     public @Nullable List<String> getPermittedInputMethods(@NonNull ComponentName admin) {
7227         throwIfParentInstance("getPermittedInputMethods");
7228         if (mService != null) {
7229             try {
7230                 return mService.getPermittedInputMethods(admin);
7231             } catch (RemoteException e) {
7232                 throw e.rethrowFromSystemServer();
7233             }
7234         }
7235         return null;
7236     }
7237 
7238     /**
7239      * Called by the system to check if a specific input method is disabled by admin.
7240      *
7241      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7242      * @param packageName Input method package name that needs to be checked.
7243      * @param userHandle user id the admin is running as.
7244      * @return true if the input method is permitted, otherwise false.
7245      *
7246      * @hide
7247      */
isInputMethodPermittedByAdmin(@onNull ComponentName admin, @NonNull String packageName, int userHandle)7248     public boolean isInputMethodPermittedByAdmin(@NonNull ComponentName admin,
7249             @NonNull String packageName, int userHandle) {
7250         if (mService != null) {
7251             try {
7252                 return mService.isInputMethodPermittedByAdmin(admin, packageName, userHandle);
7253             } catch (RemoteException e) {
7254                 throw e.rethrowFromSystemServer();
7255             }
7256         }
7257         return false;
7258     }
7259 
7260     /**
7261      * Returns the list of input methods permitted by the device or profiles owners.
7262      *
7263      * <p>On {@link android.os.Build.VERSION_CODES#Q} and later devices, this method returns the
7264      * result for the calling user.</p>
7265      *
7266      * <p>On Android P and prior devices, this method returns the result for the current user.</p>
7267      *
7268      * <p>Null means all input methods are allowed, if a non-null list is returned
7269      * it will contain the intersection of the permitted lists for any device or profile
7270      * owners that apply to this user. It will also include any system input methods.
7271      *
7272      * @return List of input method package names.
7273      * @hide
7274      */
7275     @SystemApi
7276     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
getPermittedInputMethodsForCurrentUser()7277     public @Nullable List<String> getPermittedInputMethodsForCurrentUser() {
7278         throwIfParentInstance("getPermittedInputMethodsForCurrentUser");
7279         if (mService != null) {
7280             try {
7281                 return mService.getPermittedInputMethodsForCurrentUser();
7282             } catch (RemoteException e) {
7283                 throw e.rethrowFromSystemServer();
7284             }
7285         }
7286         return null;
7287     }
7288 
7289     /**
7290      * Called by a profile owner of a managed profile to set the packages that are allowed to use
7291      * a {@link android.service.notification.NotificationListenerService} in the primary user to
7292      * see notifications from the managed profile. By default all packages are permitted by this
7293      * policy. When zero or more packages have been added, notification listeners installed on the
7294      * primary user that are not in the list and are not part of the system won't receive events
7295      * for managed profile notifications.
7296      * <p>
7297      * Calling with a {@code null} value for the list disables the restriction so that all
7298      * notification listener services be used. Calling with an empty list disables all but the
7299      * system's own notification listeners. System notification listener services are always
7300      * available to the user.
7301      * <p>
7302      * If a device or profile owner want to stop notification listeners in their user from seeing
7303      * that user's notifications they should prevent that service from running instead (e.g. via
7304      * {@link #setApplicationHidden(ComponentName, String, boolean)})
7305      *
7306      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7307      * @param packageList List of package names to whitelist
7308      * @return true if setting the restriction succeeded. It will fail if called outside a managed
7309      * profile
7310      * @throws SecurityException if {@code admin} is not a profile owner.
7311      *
7312      * @see android.service.notification.NotificationListenerService
7313      */
setPermittedCrossProfileNotificationListeners( @onNull ComponentName admin, @Nullable List<String> packageList)7314     public boolean setPermittedCrossProfileNotificationListeners(
7315             @NonNull ComponentName admin, @Nullable List<String> packageList) {
7316         throwIfParentInstance("setPermittedCrossProfileNotificationListeners");
7317         if (mService != null) {
7318             try {
7319                 return mService.setPermittedCrossProfileNotificationListeners(admin, packageList);
7320             } catch (RemoteException e) {
7321                 throw e.rethrowFromSystemServer();
7322             }
7323         }
7324         return false;
7325     }
7326 
7327     /**
7328      * Returns the list of packages installed on the primary user that allowed to use a
7329      * {@link android.service.notification.NotificationListenerService} to receive
7330      * notifications from this managed profile, as set by the profile owner.
7331      * <p>
7332      * An empty list means no notification listener services except system ones are allowed.
7333      * A {@code null} return value indicates that all notification listeners are allowed.
7334      */
getPermittedCrossProfileNotificationListeners( @onNull ComponentName admin)7335     public @Nullable List<String> getPermittedCrossProfileNotificationListeners(
7336             @NonNull ComponentName admin) {
7337         throwIfParentInstance("getPermittedCrossProfileNotificationListeners");
7338         if (mService != null) {
7339             try {
7340                 return mService.getPermittedCrossProfileNotificationListeners(admin);
7341             } catch (RemoteException e) {
7342                 throw e.rethrowFromSystemServer();
7343             }
7344         }
7345         return null;
7346     }
7347 
7348     /**
7349      * Returns true if {@code NotificationListenerServices} from the given package are allowed to
7350      * receive events for notifications from the given user id. Can only be called by the system uid
7351      *
7352      * @see #setPermittedCrossProfileNotificationListeners(ComponentName, List)
7353      *
7354      * @hide
7355      */
isNotificationListenerServicePermitted( @onNull String packageName, @UserIdInt int userId)7356     public boolean isNotificationListenerServicePermitted(
7357             @NonNull String packageName, @UserIdInt int userId) {
7358         if (mService != null) {
7359             try {
7360                 return mService.isNotificationListenerServicePermitted(packageName, userId);
7361             } catch (RemoteException e) {
7362                 throw e.rethrowFromSystemServer();
7363             }
7364         }
7365         return true;
7366     }
7367 
7368     /**
7369      * Get the list of apps to keep around as APKs even if no user has currently installed it. This
7370      * function can be called by a device owner or by a delegate given the
7371      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
7372      * <p>
7373      * Please note that packages returned in this method are not automatically pre-cached.
7374      *
7375      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7376      *            {@code null} if the caller is a keep uninstalled packages delegate.
7377      * @return List of package names to keep cached.
7378      * @see #setDelegatedScopes
7379      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
7380      */
getKeepUninstalledPackages(@ullable ComponentName admin)7381     public @Nullable List<String> getKeepUninstalledPackages(@Nullable ComponentName admin) {
7382         throwIfParentInstance("getKeepUninstalledPackages");
7383         if (mService != null) {
7384             try {
7385                 return mService.getKeepUninstalledPackages(admin, mContext.getPackageName());
7386             } catch (RemoteException e) {
7387                 throw e.rethrowFromSystemServer();
7388             }
7389         }
7390         return null;
7391     }
7392 
7393     /**
7394      * Set a list of apps to keep around as APKs even if no user has currently installed it. This
7395      * function can be called by a device owner or by a delegate given the
7396      * {@link #DELEGATION_KEEP_UNINSTALLED_PACKAGES} scope via {@link #setDelegatedScopes}.
7397      *
7398      * <p>Please note that setting this policy does not imply that specified apps will be
7399      * automatically pre-cached.</p>
7400      *
7401      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7402      *            {@code null} if the caller is a keep uninstalled packages delegate.
7403      * @param packageNames List of package names to keep cached.
7404      * @throws SecurityException if {@code admin} is not a device owner.
7405      * @see #setDelegatedScopes
7406      * @see #DELEGATION_KEEP_UNINSTALLED_PACKAGES
7407      */
setKeepUninstalledPackages(@ullable ComponentName admin, @NonNull List<String> packageNames)7408     public void setKeepUninstalledPackages(@Nullable ComponentName admin,
7409             @NonNull List<String> packageNames) {
7410         throwIfParentInstance("setKeepUninstalledPackages");
7411         if (mService != null) {
7412             try {
7413                 mService.setKeepUninstalledPackages(admin, mContext.getPackageName(), packageNames);
7414             } catch (RemoteException e) {
7415                 throw e.rethrowFromSystemServer();
7416             }
7417         }
7418     }
7419 
7420     /**
7421      * Called by a device owner to create a user with the specified name. The UserHandle returned
7422      * by this method should not be persisted as user handles are recycled as users are removed and
7423      * created. If you need to persist an identifier for this user, use
7424      * {@link UserManager#getSerialNumberForUser}.
7425      *
7426      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7427      * @param name the user's name
7428      * @see UserHandle
7429      * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
7430      *         user could not be created.
7431      *
7432      * @deprecated From {@link android.os.Build.VERSION_CODES#M}
7433      * @removed From {@link android.os.Build.VERSION_CODES#N}
7434      */
7435     @Deprecated
createUser(@onNull ComponentName admin, String name)7436     public @Nullable UserHandle createUser(@NonNull ComponentName admin, String name) {
7437         return null;
7438     }
7439 
7440     /**
7441      * Called by a device owner to create a user with the specified name. The UserHandle returned
7442      * by this method should not be persisted as user handles are recycled as users are removed and
7443      * created. If you need to persist an identifier for this user, use
7444      * {@link UserManager#getSerialNumberForUser}.  The new user will be started in the background
7445      * immediately.
7446      *
7447      * <p> profileOwnerComponent is the {@link DeviceAdminReceiver} to be the profile owner as well
7448      * as registered as an active admin on the new user.  The profile owner package will be
7449      * installed on the new user if it already is installed on the device.
7450      *
7451      * <p>If the optionalInitializeData is not null, then the extras will be passed to the
7452      * profileOwnerComponent when onEnable is called.
7453      *
7454      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7455      * @param name the user's name
7456      * @param ownerName the human readable name of the organisation associated with this DPM.
7457      * @param profileOwnerComponent The {@link DeviceAdminReceiver} that will be an active admin on
7458      *      the user.
7459      * @param adminExtras Extras that will be passed to onEnable of the admin receiver
7460      *      on the new user.
7461      * @see UserHandle
7462      * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
7463      *         user could not be created.
7464      *
7465      * @deprecated From {@link android.os.Build.VERSION_CODES#M}
7466      * @removed From {@link android.os.Build.VERSION_CODES#N}
7467      */
7468     @Deprecated
createAndInitializeUser(@onNull ComponentName admin, String name, String ownerName, @NonNull ComponentName profileOwnerComponent, Bundle adminExtras)7469     public @Nullable UserHandle createAndInitializeUser(@NonNull ComponentName admin, String name,
7470             String ownerName, @NonNull ComponentName profileOwnerComponent, Bundle adminExtras) {
7471         return null;
7472     }
7473 
7474     /**
7475       * Flag used by {@link #createAndManageUser} to skip setup wizard after creating a new user.
7476       */
7477     public static final int SKIP_SETUP_WIZARD = 0x0001;
7478 
7479     /**
7480      * Flag used by {@link #createAndManageUser} to specify that the user should be created
7481      * ephemeral. Ephemeral users will be removed after switching to another user or rebooting the
7482      * device.
7483      */
7484     public static final int MAKE_USER_EPHEMERAL = 0x0002;
7485 
7486     /**
7487      * Flag used by {@link #createAndManageUser} to specify that the user should be created as a
7488      * demo user.
7489      * @hide
7490      */
7491     public static final int MAKE_USER_DEMO = 0x0004;
7492 
7493     /**
7494      * Flag used by {@link #createAndManageUser} to specify that the newly created user should skip
7495      * the disabling of system apps during provisioning.
7496      */
7497     public static final int LEAVE_ALL_SYSTEM_APPS_ENABLED = 0x0010;
7498 
7499     /**
7500      * @hide
7501      */
7502     @IntDef(flag = true, prefix = { "SKIP_", "MAKE_USER_", "START_", "LEAVE_" }, value = {
7503             SKIP_SETUP_WIZARD,
7504             MAKE_USER_EPHEMERAL,
7505             MAKE_USER_DEMO,
7506             LEAVE_ALL_SYSTEM_APPS_ENABLED
7507     })
7508     @Retention(RetentionPolicy.SOURCE)
7509     public @interface CreateAndManageUserFlags {}
7510 
7511     /**
7512      * Called by a device owner to create a user with the specified name and a given component of
7513      * the calling package as profile owner. The UserHandle returned by this method should not be
7514      * persisted as user handles are recycled as users are removed and created. If you need to
7515      * persist an identifier for this user, use {@link UserManager#getSerialNumberForUser}. The new
7516      * user will not be started in the background.
7517      * <p>
7518      * admin is the {@link DeviceAdminReceiver} which is the device owner. profileOwner is also a
7519      * DeviceAdminReceiver in the same package as admin, and will become the profile owner and will
7520      * be registered as an active admin on the new user. The profile owner package will be installed
7521      * on the new user.
7522      * <p>
7523      * If the adminExtras are not null, they will be stored on the device until the user is started
7524      * for the first time. Then the extras will be passed to the admin when onEnable is called.
7525      * <p>From {@link android.os.Build.VERSION_CODES#P} onwards, if targeting
7526      * {@link android.os.Build.VERSION_CODES#P}, throws {@link UserOperationException} instead of
7527      * returning {@code null} on failure.
7528      *
7529      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7530      * @param name The user's name.
7531      * @param profileOwner Which {@link DeviceAdminReceiver} will be profile owner. Has to be in the
7532      *            same package as admin, otherwise no user is created and an
7533      *            IllegalArgumentException is thrown.
7534      * @param adminExtras Extras that will be passed to onEnable of the admin receiver on the new
7535      *            user.
7536      * @param flags {@link #SKIP_SETUP_WIZARD}, {@link #MAKE_USER_EPHEMERAL} and
7537      *        {@link #LEAVE_ALL_SYSTEM_APPS_ENABLED} are supported.
7538      * @see UserHandle
7539      * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the
7540      *         user could not be created.
7541      * @throws SecurityException if {@code admin} is not a device owner.
7542      * @throws UserOperationException if the user could not be created and the calling app is
7543      * targeting {@link android.os.Build.VERSION_CODES#P} and running on
7544      * {@link android.os.Build.VERSION_CODES#P}.
7545      */
createAndManageUser(@onNull ComponentName admin, @NonNull String name, @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras, @CreateAndManageUserFlags int flags)7546     public @Nullable UserHandle createAndManageUser(@NonNull ComponentName admin,
7547             @NonNull String name,
7548             @NonNull ComponentName profileOwner, @Nullable PersistableBundle adminExtras,
7549             @CreateAndManageUserFlags int flags) {
7550         throwIfParentInstance("createAndManageUser");
7551         try {
7552             return mService.createAndManageUser(admin, name, profileOwner, adminExtras, flags);
7553         } catch (ServiceSpecificException e) {
7554             throw new UserOperationException(e.getMessage(), e.errorCode);
7555         } catch (RemoteException re) {
7556             throw re.rethrowFromSystemServer();
7557         }
7558     }
7559 
7560     /**
7561      * Called by a device owner to remove a user/profile and all associated data. The primary user
7562      * can not be removed.
7563      *
7564      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7565      * @param userHandle the user to remove.
7566      * @return {@code true} if the user was removed, {@code false} otherwise.
7567      * @throws SecurityException if {@code admin} is not a device owner.
7568      */
removeUser(@onNull ComponentName admin, @NonNull UserHandle userHandle)7569     public boolean removeUser(@NonNull ComponentName admin, @NonNull UserHandle userHandle) {
7570         throwIfParentInstance("removeUser");
7571         try {
7572             return mService.removeUser(admin, userHandle);
7573         } catch (RemoteException re) {
7574             throw re.rethrowFromSystemServer();
7575         }
7576     }
7577 
7578     /**
7579      * Called by a device owner to switch the specified secondary user to the foreground.
7580      *
7581      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7582      * @param userHandle the user to switch to; null will switch to primary.
7583      * @return {@code true} if the switch was successful, {@code false} otherwise.
7584      * @throws SecurityException if {@code admin} is not a device owner.
7585      * @see Intent#ACTION_USER_FOREGROUND
7586      * @see #getSecondaryUsers(ComponentName)
7587      */
switchUser(@onNull ComponentName admin, @Nullable UserHandle userHandle)7588     public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) {
7589         throwIfParentInstance("switchUser");
7590         try {
7591             return mService.switchUser(admin, userHandle);
7592         } catch (RemoteException re) {
7593             throw re.rethrowFromSystemServer();
7594         }
7595     }
7596 
7597     /**
7598      * Called by a device owner to start the specified secondary user in background.
7599      *
7600      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7601      * @param userHandle the user to be started in background.
7602      * @return one of the following result codes:
7603      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
7604      * {@link UserManager#USER_OPERATION_SUCCESS},
7605      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
7606      * {@link UserManager#USER_OPERATION_ERROR_MAX_RUNNING_USERS},
7607      * @throws SecurityException if {@code admin} is not a device owner.
7608      * @see #getSecondaryUsers(ComponentName)
7609      */
startUserInBackground( @onNull ComponentName admin, @NonNull UserHandle userHandle)7610     public @UserOperationResult int startUserInBackground(
7611             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
7612         throwIfParentInstance("startUserInBackground");
7613         try {
7614             return mService.startUserInBackground(admin, userHandle);
7615         } catch (RemoteException re) {
7616             throw re.rethrowFromSystemServer();
7617         }
7618     }
7619 
7620     /**
7621      * Called by a device owner to stop the specified secondary user.
7622      *
7623      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7624      * @param userHandle the user to be stopped.
7625      * @return one of the following result codes:
7626      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
7627      * {@link UserManager#USER_OPERATION_SUCCESS},
7628      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
7629      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
7630      * @throws SecurityException if {@code admin} is not a device owner.
7631      * @see #getSecondaryUsers(ComponentName)
7632      */
stopUser( @onNull ComponentName admin, @NonNull UserHandle userHandle)7633     public @UserOperationResult int stopUser(
7634             @NonNull ComponentName admin, @NonNull UserHandle userHandle) {
7635         throwIfParentInstance("stopUser");
7636         try {
7637             return mService.stopUser(admin, userHandle);
7638         } catch (RemoteException re) {
7639             throw re.rethrowFromSystemServer();
7640         }
7641     }
7642 
7643     /**
7644      * Called by a profile owner of secondary user that is affiliated with the device to stop the
7645      * calling user and switch back to primary.
7646      *
7647      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7648      * @return one of the following result codes:
7649      * {@link UserManager#USER_OPERATION_ERROR_UNKNOWN},
7650      * {@link UserManager#USER_OPERATION_SUCCESS},
7651      * {@link UserManager#USER_OPERATION_ERROR_MANAGED_PROFILE},
7652      * {@link UserManager#USER_OPERATION_ERROR_CURRENT_USER}
7653      * @throws SecurityException if {@code admin} is not a profile owner affiliated with the device.
7654      * @see #getSecondaryUsers(ComponentName)
7655      */
logoutUser(@onNull ComponentName admin)7656     public @UserOperationResult int logoutUser(@NonNull ComponentName admin) {
7657         throwIfParentInstance("logoutUser");
7658         try {
7659             return mService.logoutUser(admin);
7660         } catch (RemoteException re) {
7661             throw re.rethrowFromSystemServer();
7662         }
7663     }
7664 
7665     /**
7666      * Called by a device owner to list all secondary users on the device. Managed profiles are not
7667      * considered as secondary users.
7668      * <p> Used for various user management APIs, including {@link #switchUser}, {@link #removeUser}
7669      * and {@link #stopUser}.
7670      *
7671      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7672      * @return list of other {@link UserHandle}s on the device.
7673      * @throws SecurityException if {@code admin} is not a device owner.
7674      * @see #removeUser(ComponentName, UserHandle)
7675      * @see #switchUser(ComponentName, UserHandle)
7676      * @see #startUserInBackground(ComponentName, UserHandle)
7677      * @see #stopUser(ComponentName, UserHandle)
7678      */
getSecondaryUsers(@onNull ComponentName admin)7679     public List<UserHandle> getSecondaryUsers(@NonNull ComponentName admin) {
7680         throwIfParentInstance("getSecondaryUsers");
7681         try {
7682             return mService.getSecondaryUsers(admin);
7683         } catch (RemoteException re) {
7684             throw re.rethrowFromSystemServer();
7685         }
7686     }
7687 
7688     /**
7689      * Checks if the profile owner is running in an ephemeral user.
7690      *
7691      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7692      * @return whether the profile owner is running in an ephemeral user.
7693      */
isEphemeralUser(@onNull ComponentName admin)7694     public boolean isEphemeralUser(@NonNull ComponentName admin) {
7695         throwIfParentInstance("isEphemeralUser");
7696         try {
7697             return mService.isEphemeralUser(admin);
7698         } catch (RemoteException re) {
7699             throw re.rethrowFromSystemServer();
7700         }
7701     }
7702 
7703     /**
7704      * Retrieves the application restrictions for a given target application running in the calling
7705      * user.
7706      * <p>
7707      * The caller must be a profile or device owner on that user, or the package allowed to manage
7708      * application restrictions via {@link #setDelegatedScopes} with the
7709      * {@link #DELEGATION_APP_RESTRICTIONS} scope; otherwise a security exception will be thrown.
7710      *
7711      * <p>NOTE: The method performs disk I/O and shouldn't be called on the main thread
7712      *
7713      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7714      *            {@code null} if called by the application restrictions managing package.
7715      * @param packageName The name of the package to fetch restricted settings of.
7716      * @return {@link Bundle} of settings corresponding to what was set last time
7717      *         {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty
7718      *         {@link Bundle} if no restrictions have been set.
7719      * @throws SecurityException if {@code admin} is not a device or profile owner.
7720      * @see #setDelegatedScopes
7721      * @see #DELEGATION_APP_RESTRICTIONS
7722      */
7723     @WorkerThread
getApplicationRestrictions( @ullable ComponentName admin, String packageName)7724     public @NonNull Bundle getApplicationRestrictions(
7725             @Nullable ComponentName admin, String packageName) {
7726         throwIfParentInstance("getApplicationRestrictions");
7727         if (mService != null) {
7728             try {
7729                 return mService.getApplicationRestrictions(admin, mContext.getPackageName(),
7730                         packageName);
7731             } catch (RemoteException e) {
7732                 throw e.rethrowFromSystemServer();
7733             }
7734         }
7735         return null;
7736     }
7737 
7738     /**
7739      * Called by a profile or device owner to set a user restriction specified by the key.
7740      * <p>
7741      * The calling device admin must be a profile or device owner; if it is not, a security
7742      * exception will be thrown.
7743      *
7744      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7745      * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
7746      *            for the list of keys.
7747      * @throws SecurityException if {@code admin} is not a device or profile owner.
7748      */
addUserRestriction(@onNull ComponentName admin, String key)7749     public void addUserRestriction(@NonNull ComponentName admin, String key) {
7750         throwIfParentInstance("addUserRestriction");
7751         if (mService != null) {
7752             try {
7753                 mService.setUserRestriction(admin, key, true);
7754             } catch (RemoteException e) {
7755                 throw e.rethrowFromSystemServer();
7756             }
7757         }
7758     }
7759 
7760     /**
7761      * Called by a profile or device owner to clear a user restriction specified by the key.
7762      * <p>
7763      * The calling device admin must be a profile or device owner; if it is not, a security
7764      * exception will be thrown.
7765      *
7766      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7767      * @param key The key of the restriction. See the constants in {@link android.os.UserManager}
7768      *            for the list of keys.
7769      * @throws SecurityException if {@code admin} is not a device or profile owner.
7770      */
clearUserRestriction(@onNull ComponentName admin, String key)7771     public void clearUserRestriction(@NonNull ComponentName admin, String key) {
7772         throwIfParentInstance("clearUserRestriction");
7773         if (mService != null) {
7774             try {
7775                 mService.setUserRestriction(admin, key, false);
7776             } catch (RemoteException e) {
7777                 throw e.rethrowFromSystemServer();
7778             }
7779         }
7780     }
7781 
7782     /**
7783      * Called by a profile or device owner to get user restrictions set with
7784      * {@link #addUserRestriction(ComponentName, String)}.
7785      * <p>
7786      * The target user may have more restrictions set by the system or other device owner / profile
7787      * owner. To get all the user restrictions currently set, use
7788      * {@link UserManager#getUserRestrictions()}.
7789      *
7790      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7791      * @throws SecurityException if {@code admin} is not a device or profile owner.
7792      */
getUserRestrictions(@onNull ComponentName admin)7793     public @NonNull Bundle getUserRestrictions(@NonNull ComponentName admin) {
7794         throwIfParentInstance("getUserRestrictions");
7795         Bundle ret = null;
7796         if (mService != null) {
7797             try {
7798                 ret = mService.getUserRestrictions(admin);
7799             } catch (RemoteException e) {
7800                 throw e.rethrowFromSystemServer();
7801             }
7802         }
7803         return ret == null ? new Bundle() : ret;
7804     }
7805 
7806     /**
7807      * Called by any app to display a support dialog when a feature was disabled by an admin.
7808      * This returns an intent that can be used with {@link Context#startActivity(Intent)} to
7809      * display the dialog. It will tell the user that the feature indicated by {@code restriction}
7810      * was disabled by an admin, and include a link for more information. The default content of
7811      * the dialog can be changed by the restricting admin via
7812      * {@link #setShortSupportMessage(ComponentName, CharSequence)}. If the restriction is not
7813      * set (i.e. the feature is available), then the return value will be {@code null}.
7814      * @param restriction Indicates for which feature the dialog should be displayed. Can be a
7815      *            user restriction from {@link UserManager}, e.g.
7816      *            {@link UserManager#DISALLOW_ADJUST_VOLUME}, or one of the constants
7817      *            {@link #POLICY_DISABLE_CAMERA} or {@link #POLICY_DISABLE_SCREEN_CAPTURE}.
7818      * @return Intent An intent to be used to start the dialog-activity if the restriction is
7819      *            set by an admin, or null if the restriction does not exist or no admin set it.
7820      */
createAdminSupportIntent(@onNull String restriction)7821     public Intent createAdminSupportIntent(@NonNull String restriction) {
7822         throwIfParentInstance("createAdminSupportIntent");
7823         if (mService != null) {
7824             try {
7825                 return mService.createAdminSupportIntent(restriction);
7826             } catch (RemoteException e) {
7827                 throw e.rethrowFromSystemServer();
7828             }
7829         }
7830         return null;
7831     }
7832 
7833     /**
7834      * Hide or unhide packages. When a package is hidden it is unavailable for use, but the data and
7835      * actual package file remain. This function can be called by a device owner, profile owner, or
7836      * by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
7837      * {@link #setDelegatedScopes}.
7838      *
7839      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7840      *            {@code null} if the caller is a package access delegate.
7841      * @param packageName The name of the package to hide or unhide.
7842      * @param hidden {@code true} if the package should be hidden, {@code false} if it should be
7843      *            unhidden.
7844      * @return boolean Whether the hidden setting of the package was successfully updated.
7845      * @throws SecurityException if {@code admin} is not a device or profile owner.
7846      * @see #setDelegatedScopes
7847      * @see #DELEGATION_PACKAGE_ACCESS
7848      */
setApplicationHidden(@onNull ComponentName admin, String packageName, boolean hidden)7849     public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName,
7850             boolean hidden) {
7851         throwIfParentInstance("setApplicationHidden");
7852         if (mService != null) {
7853             try {
7854                 return mService.setApplicationHidden(admin, mContext.getPackageName(), packageName,
7855                         hidden);
7856             } catch (RemoteException e) {
7857                 throw e.rethrowFromSystemServer();
7858             }
7859         }
7860         return false;
7861     }
7862 
7863     /**
7864      * Determine if a package is hidden. This function can be called by a device owner, profile
7865      * owner, or by a delegate given the {@link #DELEGATION_PACKAGE_ACCESS} scope via
7866      * {@link #setDelegatedScopes}.
7867      *
7868      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7869      *            {@code null} if the caller is a package access delegate.
7870      * @param packageName The name of the package to retrieve the hidden status of.
7871      * @return boolean {@code true} if the package is hidden, {@code false} otherwise.
7872      * @throws SecurityException if {@code admin} is not a device or profile owner.
7873      * @see #setDelegatedScopes
7874      * @see #DELEGATION_PACKAGE_ACCESS
7875      */
isApplicationHidden(@onNull ComponentName admin, String packageName)7876     public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) {
7877         throwIfParentInstance("isApplicationHidden");
7878         if (mService != null) {
7879             try {
7880                 return mService.isApplicationHidden(admin, mContext.getPackageName(), packageName);
7881             } catch (RemoteException e) {
7882                 throw e.rethrowFromSystemServer();
7883             }
7884         }
7885         return false;
7886     }
7887 
7888     /**
7889      * Re-enable a system app that was disabled by default when the user was initialized. This
7890      * function can be called by a device owner, profile owner, or by a delegate given the
7891      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
7892      *
7893      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7894      *            {@code null} if the caller is an enable system app delegate.
7895      * @param packageName The package to be re-enabled in the calling profile.
7896      * @throws SecurityException if {@code admin} is not a device or profile owner.
7897      * @see #setDelegatedScopes
7898      * @see #DELEGATION_PACKAGE_ACCESS
7899      */
enableSystemApp(@onNull ComponentName admin, String packageName)7900     public void enableSystemApp(@NonNull ComponentName admin, String packageName) {
7901         throwIfParentInstance("enableSystemApp");
7902         if (mService != null) {
7903             try {
7904                 mService.enableSystemApp(admin, mContext.getPackageName(), packageName);
7905             } catch (RemoteException e) {
7906                 throw e.rethrowFromSystemServer();
7907             }
7908         }
7909     }
7910 
7911     /**
7912      * Re-enable system apps by intent that were disabled by default when the user was initialized.
7913      * This function can be called by a device owner, profile owner, or by a delegate given the
7914      * {@link #DELEGATION_ENABLE_SYSTEM_APP} scope via {@link #setDelegatedScopes}.
7915      *
7916      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
7917      *            {@code null} if the caller is an enable system app delegate.
7918      * @param intent An intent matching the app(s) to be installed. All apps that resolve for this
7919      *            intent will be re-enabled in the calling profile.
7920      * @return int The number of activities that matched the intent and were installed.
7921      * @throws SecurityException if {@code admin} is not a device or profile owner.
7922      * @see #setDelegatedScopes
7923      * @see #DELEGATION_PACKAGE_ACCESS
7924      */
enableSystemApp(@onNull ComponentName admin, Intent intent)7925     public int enableSystemApp(@NonNull ComponentName admin, Intent intent) {
7926         throwIfParentInstance("enableSystemApp");
7927         if (mService != null) {
7928             try {
7929                 return mService.enableSystemAppWithIntent(admin, mContext.getPackageName(), intent);
7930             } catch (RemoteException e) {
7931                 throw e.rethrowFromSystemServer();
7932             }
7933         }
7934         return 0;
7935     }
7936 
7937     /**
7938      * Install an existing package that has been installed in another user, or has been kept after
7939      * removal via {@link #setKeepUninstalledPackages}.
7940      * This function can be called by a device owner, profile owner or a delegate given
7941      * the {@link #DELEGATION_INSTALL_EXISTING_PACKAGE} scope via {@link #setDelegatedScopes}.
7942      * When called in a secondary user or managed profile, the user/profile must be affiliated with
7943      * the device. See {@link #isAffiliatedUser}.
7944      *
7945      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7946      * @param packageName The package to be installed in the calling profile.
7947      * @return {@code true} if the app is installed; {@code false} otherwise.
7948      * @throws SecurityException if {@code admin} is not the device owner, or the profile owner of
7949      * an affiliated user or profile.
7950      * @see #setKeepUninstalledPackages
7951      * @see #setDelegatedScopes
7952      * @see #isAffiliatedUser
7953      * @see #DELEGATION_PACKAGE_ACCESS
7954      */
installExistingPackage(@onNull ComponentName admin, String packageName)7955     public boolean installExistingPackage(@NonNull ComponentName admin, String packageName) {
7956         throwIfParentInstance("installExistingPackage");
7957         if (mService != null) {
7958             try {
7959                 return mService.installExistingPackage(admin, mContext.getPackageName(),
7960                         packageName);
7961             } catch (RemoteException e) {
7962                 throw e.rethrowFromSystemServer();
7963             }
7964         }
7965         return false;
7966     }
7967 
7968     /**
7969      * Called by a device owner or profile owner to disable account management for a specific type
7970      * of account.
7971      * <p>
7972      * The calling device admin must be a device owner or profile owner. If it is not, a security
7973      * exception will be thrown.
7974      * <p>
7975      * When account management is disabled for an account type, adding or removing an account of
7976      * that type will not be possible.
7977      * <p>
7978      * From {@link android.os.Build.VERSION_CODES#N} the profile or device owner can still use
7979      * {@link android.accounts.AccountManager} APIs to add or remove accounts when account
7980      * management for a specific type is disabled.
7981      *
7982      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
7983      * @param accountType For which account management is disabled or enabled.
7984      * @param disabled The boolean indicating that account management will be disabled (true) or
7985      *            enabled (false).
7986      * @throws SecurityException if {@code admin} is not a device or profile owner.
7987      */
setAccountManagementDisabled(@onNull ComponentName admin, String accountType, boolean disabled)7988     public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType,
7989             boolean disabled) {
7990         throwIfParentInstance("setAccountManagementDisabled");
7991         if (mService != null) {
7992             try {
7993                 mService.setAccountManagementDisabled(admin, accountType, disabled);
7994             } catch (RemoteException e) {
7995                 throw e.rethrowFromSystemServer();
7996             }
7997         }
7998     }
7999 
8000     /**
8001      * Gets the array of accounts for which account management is disabled by the profile owner.
8002      *
8003      * <p> Account management can be disabled/enabled by calling
8004      * {@link #setAccountManagementDisabled}.
8005      *
8006      * @return a list of account types for which account management has been disabled.
8007      *
8008      * @see #setAccountManagementDisabled
8009      */
getAccountTypesWithManagementDisabled()8010     public @Nullable String[] getAccountTypesWithManagementDisabled() {
8011         throwIfParentInstance("getAccountTypesWithManagementDisabled");
8012         return getAccountTypesWithManagementDisabledAsUser(myUserId());
8013     }
8014 
8015     /**
8016      * @see #getAccountTypesWithManagementDisabled()
8017      * @hide
8018      */
getAccountTypesWithManagementDisabledAsUser(int userId)8019     public @Nullable String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
8020         if (mService != null) {
8021             try {
8022                 return mService.getAccountTypesWithManagementDisabledAsUser(userId);
8023             } catch (RemoteException e) {
8024                 throw e.rethrowFromSystemServer();
8025             }
8026         }
8027 
8028         return null;
8029     }
8030 
8031     /**
8032      * Sets which packages may enter lock task mode.
8033      * <p>
8034      * Any packages that share uid with an allowed package will also be allowed to activate lock
8035      * task. From {@link android.os.Build.VERSION_CODES#M} removing packages from the lock task
8036      * package list results in locked tasks belonging to those packages to be finished.
8037      * <p>
8038      * This function can only be called by the device owner, a profile owner of an affiliated user
8039      * or profile, or the profile owner when no device owner is set. See {@link #isAffiliatedUser}.
8040      * Any package set via this method will be cleared if the user becomes unaffiliated.
8041      *
8042      * @param packages The list of packages allowed to enter lock task mode
8043      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8044      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
8045      * affiliated user or profile, or the profile owner when no device owner is set.
8046      * @see #isAffiliatedUser
8047      * @see Activity#startLockTask()
8048      * @see DeviceAdminReceiver#onLockTaskModeEntering(Context, Intent, String)
8049      * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent)
8050      * @see UserManager#DISALLOW_CREATE_WINDOWS
8051      */
setLockTaskPackages(@onNull ComponentName admin, @NonNull String[] packages)8052     public void setLockTaskPackages(@NonNull ComponentName admin, @NonNull String[] packages)
8053             throws SecurityException {
8054         throwIfParentInstance("setLockTaskPackages");
8055         if (mService != null) {
8056             try {
8057                 mService.setLockTaskPackages(admin, packages);
8058             } catch (RemoteException e) {
8059                 throw e.rethrowFromSystemServer();
8060             }
8061         }
8062     }
8063 
8064     /**
8065      * Returns the list of packages allowed to start the lock task mode.
8066      *
8067      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
8068      * affiliated user or profile, or the profile owner when no device owner is set.
8069      * @see #isAffiliatedUser
8070      * @see #setLockTaskPackages
8071      */
getLockTaskPackages(@onNull ComponentName admin)8072     public @NonNull String[] getLockTaskPackages(@NonNull ComponentName admin) {
8073         throwIfParentInstance("getLockTaskPackages");
8074         if (mService != null) {
8075             try {
8076                 return mService.getLockTaskPackages(admin);
8077             } catch (RemoteException e) {
8078                 throw e.rethrowFromSystemServer();
8079             }
8080         }
8081         return new String[0];
8082     }
8083 
8084     /**
8085      * This function lets the caller know whether the given component is allowed to start the
8086      * lock task mode.
8087      * @param pkg The package to check
8088      */
isLockTaskPermitted(String pkg)8089     public boolean isLockTaskPermitted(String pkg) {
8090         throwIfParentInstance("isLockTaskPermitted");
8091         if (mService != null) {
8092             try {
8093                 return mService.isLockTaskPermitted(pkg);
8094             } catch (RemoteException e) {
8095                 throw e.rethrowFromSystemServer();
8096             }
8097         }
8098         return false;
8099     }
8100 
8101     /**
8102      * Sets which system features are enabled when the device runs in lock task mode. This method
8103      * doesn't affect the features when lock task mode is inactive. Any system features not included
8104      * in {@code flags} are implicitly disabled when calling this method. By default, only
8105      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS} is enabled; all the other features are disabled. To
8106      * disable the global actions dialog, call this method omitting
8107      * {@link #LOCK_TASK_FEATURE_GLOBAL_ACTIONS}.
8108      *
8109      * <p>This method can only be called by the device owner, a profile owner of an affiliated
8110      * user or profile, or the profile owner when no device owner is set. See
8111      * {@link #isAffiliatedUser}.
8112      * Any features set using this method are cleared if the user becomes unaffiliated.
8113      *
8114      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8115      * @param flags The system features enabled during lock task mode.
8116      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
8117      * affiliated user or profile, or the profile owner when no device owner is set.
8118      * @see #isAffiliatedUser
8119      **/
setLockTaskFeatures(@onNull ComponentName admin, @LockTaskFeature int flags)8120     public void setLockTaskFeatures(@NonNull ComponentName admin, @LockTaskFeature int flags) {
8121         throwIfParentInstance("setLockTaskFeatures");
8122         if (mService != null) {
8123             try {
8124                 mService.setLockTaskFeatures(admin, flags);
8125             } catch (RemoteException e) {
8126                 throw e.rethrowFromSystemServer();
8127             }
8128         }
8129     }
8130 
8131     /**
8132      * Gets which system features are enabled for LockTask mode.
8133      *
8134      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8135      * @return bitfield of flags. See {@link #setLockTaskFeatures(ComponentName, int)} for a list.
8136      * @throws SecurityException if {@code admin} is not the device owner, the profile owner of an
8137      * affiliated user or profile, or the profile owner when no device owner is set.
8138      * @see #isAffiliatedUser
8139      * @see #setLockTaskFeatures
8140      */
getLockTaskFeatures(@onNull ComponentName admin)8141     public @LockTaskFeature int getLockTaskFeatures(@NonNull ComponentName admin) {
8142         throwIfParentInstance("getLockTaskFeatures");
8143         if (mService != null) {
8144             try {
8145                 return mService.getLockTaskFeatures(admin);
8146             } catch (RemoteException e) {
8147                 throw e.rethrowFromSystemServer();
8148             }
8149         }
8150         return 0;
8151     }
8152 
8153     /**
8154      * Called by device owner to update {@link android.provider.Settings.Global} settings.
8155      * Validation that the value of the setting is in the correct form for the setting type should
8156      * be performed by the caller.
8157      * <p>
8158      * The settings that can be updated with this method are:
8159      * <ul>
8160      * <li>{@link android.provider.Settings.Global#ADB_ENABLED}</li>
8161      * <li>{@link android.provider.Settings.Global#AUTO_TIME}</li>
8162      * <li>{@link android.provider.Settings.Global#AUTO_TIME_ZONE}</li>
8163      * <li>{@link android.provider.Settings.Global#DATA_ROAMING}</li>
8164      * <li>{@link android.provider.Settings.Global#USB_MASS_STORAGE_ENABLED}</li>
8165      * <li>{@link android.provider.Settings.Global#WIFI_SLEEP_POLICY}</li>
8166      * <li>{@link android.provider.Settings.Global#STAY_ON_WHILE_PLUGGED_IN} This setting is only
8167      * available from {@link android.os.Build.VERSION_CODES#M} onwards and can only be set if
8168      * {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
8169      * <li>{@link android.provider.Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li> This
8170      * setting is only available from {@link android.os.Build.VERSION_CODES#M} onwards.</li>
8171      * </ul>
8172      * <p>
8173      * Changing the following settings has no effect as of {@link android.os.Build.VERSION_CODES#M}:
8174      * <ul>
8175      * <li>{@link android.provider.Settings.Global#BLUETOOTH_ON}. Use
8176      * {@link android.bluetooth.BluetoothAdapter#enable()} and
8177      * {@link android.bluetooth.BluetoothAdapter#disable()} instead.</li>
8178      * <li>{@link android.provider.Settings.Global#DEVELOPMENT_SETTINGS_ENABLED}</li>
8179      * <li>{@link android.provider.Settings.Global#MODE_RINGER}. Use
8180      * {@link android.media.AudioManager#setRingerMode(int)} instead.</li>
8181      * <li>{@link android.provider.Settings.Global#NETWORK_PREFERENCE}</li>
8182      * <li>{@link android.provider.Settings.Global#WIFI_ON}. Use
8183      * {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)} instead.</li>
8184      * </ul>
8185      *
8186      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8187      * @param setting The name of the setting to update.
8188      * @param value The value to update the setting to.
8189      * @throws SecurityException if {@code admin} is not a device owner.
8190      */
setGlobalSetting(@onNull ComponentName admin, String setting, String value)8191     public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) {
8192         throwIfParentInstance("setGlobalSetting");
8193         if (mService != null) {
8194             try {
8195                 mService.setGlobalSetting(admin, setting, value);
8196             } catch (RemoteException e) {
8197                 throw e.rethrowFromSystemServer();
8198             }
8199         }
8200     }
8201 
8202     /** @hide */
8203     @StringDef({
8204             Settings.System.SCREEN_BRIGHTNESS_MODE,
8205             Settings.System.SCREEN_BRIGHTNESS,
8206             Settings.System.SCREEN_OFF_TIMEOUT
8207     })
8208     @Retention(RetentionPolicy.SOURCE)
8209     public @interface SystemSettingsWhitelist {}
8210 
8211     /**
8212      * Called by a device or profile owner to update {@link android.provider.Settings.System}
8213      * settings. Validation that the value of the setting is in the correct form for the setting
8214      * type should be performed by the caller.
8215      * <p>
8216      * The settings that can be updated by a device owner or profile owner of secondary user with
8217      * this method are:
8218      * <ul>
8219      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS}</li>
8220      * <li>{@link android.provider.Settings.System#SCREEN_BRIGHTNESS_MODE}</li>
8221      * <li>{@link android.provider.Settings.System#SCREEN_OFF_TIMEOUT}</li>
8222      * </ul>
8223      * <p>
8224      *
8225      * @see android.provider.Settings.System#SCREEN_OFF_TIMEOUT
8226      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8227      * @param setting The name of the setting to update.
8228      * @param value The value to update the setting to.
8229      * @throws SecurityException if {@code admin} is not a device or profile owner.
8230      */
setSystemSetting(@onNull ComponentName admin, @NonNull @SystemSettingsWhitelist String setting, String value)8231     public void setSystemSetting(@NonNull ComponentName admin,
8232             @NonNull @SystemSettingsWhitelist String setting, String value) {
8233         throwIfParentInstance("setSystemSetting");
8234         if (mService != null) {
8235             try {
8236                 mService.setSystemSetting(admin, setting, value);
8237             } catch (RemoteException e) {
8238                 throw e.rethrowFromSystemServer();
8239             }
8240         }
8241     }
8242 
8243     /**
8244      * Called by device owner to set the system wall clock time. This only takes effect if called
8245      * when {@link android.provider.Settings.Global#AUTO_TIME} is 0, otherwise {@code false} will be
8246      * returned.
8247      *
8248      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
8249      * @param millis time in milliseconds since the Epoch
8250      * @return {@code true} if set time succeeded, {@code false} otherwise.
8251      * @throws SecurityException if {@code admin} is not a device owner.
8252      */
setTime(@onNull ComponentName admin, long millis)8253     public boolean setTime(@NonNull ComponentName admin, long millis) {
8254         throwIfParentInstance("setTime");
8255         if (mService != null) {
8256             try {
8257                 return mService.setTime(admin, millis);
8258             } catch (RemoteException e) {
8259                 throw e.rethrowFromSystemServer();
8260             }
8261         }
8262         return false;
8263     }
8264 
8265     /**
8266      * Called by device owner to set the system's persistent default time zone. This only takes
8267      * effect if called when {@link android.provider.Settings.Global#AUTO_TIME_ZONE} is 0, otherwise
8268      * {@code false} will be returned.
8269      *
8270      * @see android.app.AlarmManager#setTimeZone(String)
8271      * @param admin Which {@link DeviceAdminReceiver} this request is associated with
8272      * @param timeZone one of the Olson ids from the list returned by
8273      *     {@link java.util.TimeZone#getAvailableIDs}
8274      * @return {@code true} if set timezone succeeded, {@code false} otherwise.
8275      * @throws SecurityException if {@code admin} is not a device owner.
8276      */
setTimeZone(@onNull ComponentName admin, String timeZone)8277     public boolean setTimeZone(@NonNull ComponentName admin, String timeZone) {
8278         throwIfParentInstance("setTimeZone");
8279         if (mService != null) {
8280             try {
8281                 return mService.setTimeZone(admin, timeZone);
8282             } catch (RemoteException e) {
8283                 throw e.rethrowFromSystemServer();
8284             }
8285         }
8286         return false;
8287     }
8288 
8289     /**
8290      * Called by profile or device owners to update {@link android.provider.Settings.Secure}
8291      * settings. Validation that the value of the setting is in the correct form for the setting
8292      * type should be performed by the caller.
8293      * <p>
8294      * The settings that can be updated by a profile or device owner with this method are:
8295      * <ul>
8296      * <li>{@link android.provider.Settings.Secure#DEFAULT_INPUT_METHOD}</li>
8297      * <li>{@link android.provider.Settings.Secure#SKIP_FIRST_USE_HINTS}</li>
8298      * </ul>
8299      * <p>
8300      * A device owner can additionally update the following settings:
8301      * <ul>
8302      * <li>{@link android.provider.Settings.Secure#LOCATION_MODE}</li>
8303      * </ul>
8304      *
8305      * <strong>Note: Starting from Android O, apps should no longer call this method with the
8306      * setting {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS}, which is
8307      * deprecated. Instead, device owners or profile owners should use the restriction
8308      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES}.
8309      * If any app targeting {@link android.os.Build.VERSION_CODES#O} or higher calls this method
8310      * with {@link android.provider.Settings.Secure#INSTALL_NON_MARKET_APPS},
8311      * an {@link UnsupportedOperationException} is thrown.
8312      *
8313      * Starting from Android Q, the device and profile owner can also call
8314      * {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY} to restrict unknown sources for
8315      * all users.
8316      * </strong>
8317      *
8318      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8319      * @param setting The name of the setting to update.
8320      * @param value The value to update the setting to.
8321      * @throws SecurityException if {@code admin} is not a device or profile owner.
8322      */
setSecureSetting(@onNull ComponentName admin, String setting, String value)8323     public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) {
8324         throwIfParentInstance("setSecureSetting");
8325         if (mService != null) {
8326             try {
8327                 mService.setSecureSetting(admin, setting, value);
8328             } catch (RemoteException e) {
8329                 throw e.rethrowFromSystemServer();
8330             }
8331         }
8332     }
8333 
8334     /**
8335      * Designates a specific service component as the provider for making permission requests of a
8336      * local or remote administrator of the user.
8337      * <p/>
8338      * Only a profile owner can designate the restrictions provider.
8339      *
8340      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8341      * @param provider The component name of the service that implements
8342      *            {@link RestrictionsReceiver}. If this param is null, it removes the restrictions
8343      *            provider previously assigned.
8344      * @throws SecurityException if {@code admin} is not a device or profile owner.
8345      */
setRestrictionsProvider(@onNull ComponentName admin, @Nullable ComponentName provider)8346     public void setRestrictionsProvider(@NonNull ComponentName admin,
8347             @Nullable ComponentName provider) {
8348         throwIfParentInstance("setRestrictionsProvider");
8349         if (mService != null) {
8350             try {
8351                 mService.setRestrictionsProvider(admin, provider);
8352             } catch (RemoteException re) {
8353                 throw re.rethrowFromSystemServer();
8354             }
8355         }
8356     }
8357 
8358     /**
8359      * Called by profile or device owners to set the master volume mute on or off.
8360      * This has no effect when set on a managed profile.
8361      *
8362      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8363      * @param on {@code true} to mute master volume, {@code false} to turn mute off.
8364      * @throws SecurityException if {@code admin} is not a device or profile owner.
8365      */
setMasterVolumeMuted(@onNull ComponentName admin, boolean on)8366     public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) {
8367         throwIfParentInstance("setMasterVolumeMuted");
8368         if (mService != null) {
8369             try {
8370                 mService.setMasterVolumeMuted(admin, on);
8371             } catch (RemoteException re) {
8372                 throw re.rethrowFromSystemServer();
8373             }
8374         }
8375     }
8376 
8377     /**
8378      * Called by profile or device owners to check whether the master volume mute is on or off.
8379      *
8380      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8381      * @return {@code true} if master volume is muted, {@code false} if it's not.
8382      * @throws SecurityException if {@code admin} is not a device or profile owner.
8383      */
isMasterVolumeMuted(@onNull ComponentName admin)8384     public boolean isMasterVolumeMuted(@NonNull ComponentName admin) {
8385         throwIfParentInstance("isMasterVolumeMuted");
8386         if (mService != null) {
8387             try {
8388                 return mService.isMasterVolumeMuted(admin);
8389             } catch (RemoteException re) {
8390                 throw re.rethrowFromSystemServer();
8391             }
8392         }
8393         return false;
8394     }
8395 
8396     /**
8397      * Change whether a user can uninstall a package. This function can be called by a device owner,
8398      * profile owner, or by a delegate given the {@link #DELEGATION_BLOCK_UNINSTALL} scope via
8399      * {@link #setDelegatedScopes}.
8400      *
8401      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
8402      *             {@code null} if the caller is a block uninstall delegate.
8403      * @param packageName package to change.
8404      * @param uninstallBlocked true if the user shouldn't be able to uninstall the package.
8405      * @throws SecurityException if {@code admin} is not a device or profile owner.
8406      * @see #setDelegatedScopes
8407      * @see #DELEGATION_BLOCK_UNINSTALL
8408      */
setUninstallBlocked(@ullable ComponentName admin, String packageName, boolean uninstallBlocked)8409     public void setUninstallBlocked(@Nullable ComponentName admin, String packageName,
8410             boolean uninstallBlocked) {
8411         throwIfParentInstance("setUninstallBlocked");
8412         if (mService != null) {
8413             try {
8414                 mService.setUninstallBlocked(admin, mContext.getPackageName(), packageName,
8415                     uninstallBlocked);
8416             } catch (RemoteException re) {
8417                 throw re.rethrowFromSystemServer();
8418             }
8419         }
8420     }
8421 
8422     /**
8423      * Check whether the user has been blocked by device policy from uninstalling a package.
8424      * Requires the caller to be the profile owner if checking a specific admin's policy.
8425      * <p>
8426      * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the
8427      * behavior of this API is changed such that passing {@code null} as the {@code admin} parameter
8428      * will return if any admin has blocked the uninstallation. Before L MR1, passing {@code null}
8429      * will cause a NullPointerException to be raised.
8430      *
8431      * @param admin The name of the admin component whose blocking policy will be checked, or
8432      *            {@code null} to check whether any admin has blocked the uninstallation.
8433      * @param packageName package to check.
8434      * @return true if uninstallation is blocked.
8435      * @throws SecurityException if {@code admin} is not a device or profile owner.
8436      */
isUninstallBlocked(@ullable ComponentName admin, String packageName)8437     public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) {
8438         throwIfParentInstance("isUninstallBlocked");
8439         if (mService != null) {
8440             try {
8441                 return mService.isUninstallBlocked(admin, packageName);
8442             } catch (RemoteException re) {
8443                 throw re.rethrowFromSystemServer();
8444             }
8445         }
8446         return false;
8447     }
8448 
8449     /**
8450      * Called by the profile owner of a managed profile to enable widget providers from a given
8451      * package to be available in the parent profile. As a result the user will be able to add
8452      * widgets from the white-listed package running under the profile to a widget host which runs
8453      * under the parent profile, for example the home screen. Note that a package may have zero or
8454      * more provider components, where each component provides a different widget type.
8455      * <p>
8456      * <strong>Note:</strong> By default no widget provider package is white-listed.
8457      *
8458      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8459      * @param packageName The package from which widget providers are white-listed.
8460      * @return Whether the package was added.
8461      * @throws SecurityException if {@code admin} is not a profile owner.
8462      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
8463      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
8464      */
addCrossProfileWidgetProvider(@onNull ComponentName admin, String packageName)8465     public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) {
8466         throwIfParentInstance("addCrossProfileWidgetProvider");
8467         if (mService != null) {
8468             try {
8469                 return mService.addCrossProfileWidgetProvider(admin, packageName);
8470             } catch (RemoteException re) {
8471                 throw re.rethrowFromSystemServer();
8472             }
8473         }
8474         return false;
8475     }
8476 
8477     /**
8478      * Called by the profile owner of a managed profile to disable widget providers from a given
8479      * package to be available in the parent profile. For this method to take effect the package
8480      * should have been added via
8481      * {@link #addCrossProfileWidgetProvider( android.content.ComponentName, String)}.
8482      * <p>
8483      * <strong>Note:</strong> By default no widget provider package is white-listed.
8484      *
8485      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8486      * @param packageName The package from which widget providers are no longer white-listed.
8487      * @return Whether the package was removed.
8488      * @throws SecurityException if {@code admin} is not a profile owner.
8489      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
8490      * @see #getCrossProfileWidgetProviders(android.content.ComponentName)
8491      */
removeCrossProfileWidgetProvider( @onNull ComponentName admin, String packageName)8492     public boolean removeCrossProfileWidgetProvider(
8493             @NonNull ComponentName admin, String packageName) {
8494         throwIfParentInstance("removeCrossProfileWidgetProvider");
8495         if (mService != null) {
8496             try {
8497                 return mService.removeCrossProfileWidgetProvider(admin, packageName);
8498             } catch (RemoteException re) {
8499                 throw re.rethrowFromSystemServer();
8500             }
8501         }
8502         return false;
8503     }
8504 
8505     /**
8506      * Called by the profile owner of a managed profile to query providers from which packages are
8507      * available in the parent profile.
8508      *
8509      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8510      * @return The white-listed package list.
8511      * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String)
8512      * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String)
8513      * @throws SecurityException if {@code admin} is not a profile owner.
8514      */
getCrossProfileWidgetProviders(@onNull ComponentName admin)8515     public @NonNull List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) {
8516         throwIfParentInstance("getCrossProfileWidgetProviders");
8517         if (mService != null) {
8518             try {
8519                 List<String> providers = mService.getCrossProfileWidgetProviders(admin);
8520                 if (providers != null) {
8521                     return providers;
8522                 }
8523             } catch (RemoteException re) {
8524                 throw re.rethrowFromSystemServer();
8525             }
8526         }
8527         return Collections.emptyList();
8528     }
8529 
8530     /**
8531      * Called by profile or device owners to set the user's photo.
8532      *
8533      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8534      * @param icon the bitmap to set as the photo.
8535      * @throws SecurityException if {@code admin} is not a device or profile owner.
8536      */
setUserIcon(@onNull ComponentName admin, Bitmap icon)8537     public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) {
8538         throwIfParentInstance("setUserIcon");
8539         try {
8540             mService.setUserIcon(admin, icon);
8541         } catch (RemoteException re) {
8542             throw re.rethrowFromSystemServer();
8543         }
8544     }
8545 
8546     /**
8547      * Called by device owners to set a local system update policy. When a new policy is set,
8548      * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted.
8549      * <p>
8550      * If the supplied system update policy has freeze periods set but the freeze periods do not
8551      * meet 90-day maximum length or 60-day minimum separation requirement set out in
8552      * {@link SystemUpdatePolicy#setFreezePeriods},
8553      * {@link SystemUpdatePolicy.ValidationFailedException} will the thrown. Note that the system
8554      * keeps a record of freeze periods the device experienced previously, and combines them with
8555      * the new freeze periods to be set when checking the maximum freeze length and minimum freeze
8556      * separation constraints. As a result, freeze periods that passed validation during
8557      * {@link SystemUpdatePolicy#setFreezePeriods} might fail the additional checks here due to
8558      * the freeze period history. If this is causing issues during development,
8559      * {@code adb shell dpm clear-freeze-period-record} can be used to clear the record.
8560      *
8561      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All
8562      *            components in the device owner package can set system update policies and the most
8563      *            recent policy takes effect.
8564      * @param policy the new policy, or {@code null} to clear the current policy.
8565      * @throws SecurityException if {@code admin} is not a device owner.
8566      * @throws IllegalArgumentException if the policy type or maintenance window is not valid.
8567      * @throws SystemUpdatePolicy.ValidationFailedException if the policy's freeze period does not
8568      *             meet the requirement.
8569      * @see SystemUpdatePolicy
8570      * @see SystemUpdatePolicy#setFreezePeriods(List)
8571      */
setSystemUpdatePolicy(@onNull ComponentName admin, SystemUpdatePolicy policy)8572     public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) {
8573         throwIfParentInstance("setSystemUpdatePolicy");
8574         if (mService != null) {
8575             try {
8576                 mService.setSystemUpdatePolicy(admin, policy);
8577             } catch (RemoteException re) {
8578                 throw re.rethrowFromSystemServer();
8579             }
8580         }
8581     }
8582 
8583     /**
8584      * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}.
8585      *
8586      * @return The current policy object, or {@code null} if no policy is set.
8587      */
getSystemUpdatePolicy()8588     public @Nullable SystemUpdatePolicy getSystemUpdatePolicy() {
8589         throwIfParentInstance("getSystemUpdatePolicy");
8590         if (mService != null) {
8591             try {
8592                 return mService.getSystemUpdatePolicy();
8593             } catch (RemoteException re) {
8594                 throw re.rethrowFromSystemServer();
8595             }
8596         }
8597         return null;
8598     }
8599 
8600     /**
8601      * Reset record of previous system update freeze period the device went through.
8602      * Only callable by ADB.
8603      * @hide
8604      */
clearSystemUpdatePolicyFreezePeriodRecord()8605     public void clearSystemUpdatePolicyFreezePeriodRecord() {
8606         throwIfParentInstance("clearSystemUpdatePolicyFreezePeriodRecord");
8607         if (mService == null) {
8608             return;
8609         }
8610         try {
8611             mService.clearSystemUpdatePolicyFreezePeriodRecord();
8612         } catch (RemoteException re) {
8613             throw re.rethrowFromSystemServer();
8614         }
8615     }
8616 
8617     /**
8618      * Called by a device owner or profile owner of secondary users that is affiliated with the
8619      * device to disable the keyguard altogether.
8620      * <p>
8621      * Setting the keyguard to disabled has the same effect as choosing "None" as the screen lock
8622      * type. However, this call has no effect if a password, pin or pattern is currently set. If a
8623      * password, pin or pattern is set after the keyguard was disabled, the keyguard stops being
8624      * disabled.
8625      *
8626      * <p>
8627      * As of {@link android.os.Build.VERSION_CODES#P}, this call also dismisses the
8628      * keyguard if it is currently shown.
8629      *
8630      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8631      * @param disabled {@code true} disables the keyguard, {@code false} reenables it.
8632      * @return {@code false} if attempting to disable the keyguard while a lock password was in
8633      *         place. {@code true} otherwise.
8634      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
8635      * secondary user that is affiliated with the device.
8636      * @see #isAffiliatedUser
8637      * @see #getSecondaryUsers
8638      */
setKeyguardDisabled(@onNull ComponentName admin, boolean disabled)8639     public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) {
8640         throwIfParentInstance("setKeyguardDisabled");
8641         try {
8642             return mService.setKeyguardDisabled(admin, disabled);
8643         } catch (RemoteException re) {
8644             throw re.rethrowFromSystemServer();
8645         }
8646     }
8647 
8648     /**
8649      * Called by device owner or profile owner of secondary users  that is affiliated with the
8650      * device to disable the status bar. Disabling the status bar blocks notifications, quick
8651      * settings and other screen overlays that allow escaping from a single use device.
8652      * <p>
8653      * <strong>Note:</strong> This method has no effect for LockTask mode. The behavior of the
8654      * status bar in LockTask mode can be configured with
8655      * {@link #setLockTaskFeatures(ComponentName, int)}. Calls to this method when the device is in
8656      * LockTask mode will be registered, but will only take effect when the device leaves LockTask
8657      * mode.
8658      *
8659      * <p>This policy does not have any effect while on the lock screen, where the status bar will
8660      * not be disabled. Using LockTask instead of this method is recommended.
8661      *
8662      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
8663      * @param disabled {@code true} disables the status bar, {@code false} reenables it.
8664      * @return {@code false} if attempting to disable the status bar failed. {@code true} otherwise.
8665      * @throws SecurityException if {@code admin} is not the device owner, or a profile owner of
8666      * secondary user that is affiliated with the device.
8667      * @see #isAffiliatedUser
8668      * @see #getSecondaryUsers
8669      */
setStatusBarDisabled(@onNull ComponentName admin, boolean disabled)8670     public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) {
8671         throwIfParentInstance("setStatusBarDisabled");
8672         try {
8673             return mService.setStatusBarDisabled(admin, disabled);
8674         } catch (RemoteException re) {
8675             throw re.rethrowFromSystemServer();
8676         }
8677     }
8678 
8679     /**
8680      * Called by the system update service to notify device and profile owners of pending system
8681      * updates.
8682      *
8683      * This method should only be used when it is unknown whether the pending system
8684      * update is a security patch. Otherwise, use
8685      * {@link #notifyPendingSystemUpdate(long, boolean)}.
8686      *
8687      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
8688      *         indicating when the current pending update was first available. {@code -1} if no
8689      *         update is available.
8690      * @see #notifyPendingSystemUpdate(long, boolean)
8691      * @hide
8692      */
8693     @SystemApi
8694     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime)8695     public void notifyPendingSystemUpdate(long updateReceivedTime) {
8696         throwIfParentInstance("notifyPendingSystemUpdate");
8697         if (mService != null) {
8698             try {
8699                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime));
8700             } catch (RemoteException re) {
8701                 throw re.rethrowFromSystemServer();
8702             }
8703         }
8704     }
8705 
8706     /**
8707      * Called by the system update service to notify device and profile owners of pending system
8708      * updates.
8709      *
8710      * This method should be used instead of {@link #notifyPendingSystemUpdate(long)}
8711      * when it is known whether the pending system update is a security patch.
8712      *
8713      * @param updateReceivedTime The time as given by {@link System#currentTimeMillis()}
8714      *         indicating when the current pending update was first available. {@code -1} if no
8715      *         update is available.
8716      * @param isSecurityPatch {@code true} if this system update is purely a security patch;
8717      *         {@code false} if not.
8718      * @see #notifyPendingSystemUpdate(long)
8719      * @hide
8720      */
8721     @SystemApi
8722     @RequiresPermission(android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE)
notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch)8723     public void notifyPendingSystemUpdate(long updateReceivedTime, boolean isSecurityPatch) {
8724         throwIfParentInstance("notifyPendingSystemUpdate");
8725         if (mService != null) {
8726             try {
8727                 mService.notifyPendingSystemUpdate(SystemUpdateInfo.of(updateReceivedTime,
8728                         isSecurityPatch));
8729             } catch (RemoteException re) {
8730                 throw re.rethrowFromSystemServer();
8731             }
8732         }
8733     }
8734 
8735     /**
8736      * Called by device or profile owners to get information about a pending system update.
8737      *
8738      * @param admin Which profile or device owner this request is associated with.
8739      * @return Information about a pending system update or {@code null} if no update pending.
8740      * @throws SecurityException if {@code admin} is not a device or profile owner.
8741      * @see DeviceAdminReceiver#onSystemUpdatePending(Context, Intent, long)
8742      */
getPendingSystemUpdate(@onNull ComponentName admin)8743     public @Nullable SystemUpdateInfo getPendingSystemUpdate(@NonNull ComponentName admin) {
8744         throwIfParentInstance("getPendingSystemUpdate");
8745         try {
8746             return mService.getPendingSystemUpdate(admin);
8747         } catch (RemoteException re) {
8748             throw re.rethrowFromSystemServer();
8749         }
8750     }
8751 
8752     /**
8753      * Set the default response for future runtime permission requests by applications. This
8754      * function can be called by a device owner, profile owner, or by a delegate given the
8755      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
8756      * The policy can allow for normal operation which prompts the user to grant a permission, or
8757      * can allow automatic granting or denying of runtime permission requests by an application.
8758      * This also applies to new permissions declared by app updates. When a permission is denied or
8759      * granted this way, the effect is equivalent to setting the permission * grant state via
8760      * {@link #setPermissionGrantState}.
8761      * <p/>
8762      * As this policy only acts on runtime permission requests, it only applies to applications
8763      * built with a {@code targetSdkVersion} of {@link android.os.Build.VERSION_CODES#M} or later.
8764      *
8765      * @param admin Which profile or device owner this request is associated with.
8766      * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT},
8767      *            {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}.
8768      * @throws SecurityException if {@code admin} is not a device or profile owner.
8769      * @see #setPermissionGrantState
8770      * @see #setDelegatedScopes
8771      * @see #DELEGATION_PERMISSION_GRANT
8772      */
setPermissionPolicy(@onNull ComponentName admin, int policy)8773     public void setPermissionPolicy(@NonNull ComponentName admin, int policy) {
8774         throwIfParentInstance("setPermissionPolicy");
8775         try {
8776             mService.setPermissionPolicy(admin, mContext.getPackageName(), policy);
8777         } catch (RemoteException re) {
8778             throw re.rethrowFromSystemServer();
8779         }
8780     }
8781 
8782     /**
8783      * Returns the current runtime permission policy set by the device or profile owner. The
8784      * default is {@link #PERMISSION_POLICY_PROMPT}.
8785      *
8786      * @param admin Which profile or device owner this request is associated with.
8787      * @return the current policy for future permission requests.
8788      */
getPermissionPolicy(ComponentName admin)8789     public int getPermissionPolicy(ComponentName admin) {
8790         throwIfParentInstance("getPermissionPolicy");
8791         try {
8792             return mService.getPermissionPolicy(admin);
8793         } catch (RemoteException re) {
8794             throw re.rethrowFromSystemServer();
8795         }
8796     }
8797 
8798     /**
8799      * Sets the grant state of a runtime permission for a specific application. The state can be
8800      * {@link #PERMISSION_GRANT_STATE_DEFAULT default} in which a user can manage it through the UI,
8801      * {@link #PERMISSION_GRANT_STATE_DENIED denied}, in which the permission is denied and the user
8802      * cannot manage it through the UI, and {@link #PERMISSION_GRANT_STATE_GRANTED granted} in which
8803      * the permission is granted and the user cannot manage it through the UI. This method can only
8804      * be called by a profile owner, device owner, or a delegate given the
8805      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
8806      * <p/>
8807      * Note that user cannot manage other permissions in the affected group through the UI
8808      * either and their granted state will be kept as the current value. Thus, it's recommended that
8809      * you set the grant state of all the permissions in the affected group.
8810      * <p/>
8811      * Setting the grant state to {@link #PERMISSION_GRANT_STATE_DEFAULT default} does not revoke
8812      * the permission. It retains the previous grant, if any.
8813      * <p/>
8814      * Device admins with a {@code targetSdkVersion} &lt; {@link android.os.Build.VERSION_CODES#Q}
8815      * cannot grant and revoke permissions for applications built with a {@code targetSdkVersion}
8816      * &lt; {@link android.os.Build.VERSION_CODES#M}.
8817      * <p/>
8818      * Admins with a {@code targetSdkVersion} &ge; {@link android.os.Build.VERSION_CODES#Q} can
8819      * grant and revoke permissions of all apps. Similar to the user revoking a permission from a
8820      * application built with a {@code targetSdkVersion} &lt;
8821      * {@link android.os.Build.VERSION_CODES#M} the app-op matching the permission is set to
8822      * {@link android.app.AppOpsManager#MODE_IGNORED}, but the permission stays granted.
8823      *
8824      * @param admin Which profile or device owner this request is associated with.
8825      * @param packageName The application to grant or revoke a permission to.
8826      * @param permission The permission to grant or revoke.
8827      * @param grantState The permission grant state which is one of
8828      *            {@link #PERMISSION_GRANT_STATE_DENIED}, {@link #PERMISSION_GRANT_STATE_DEFAULT},
8829      *            {@link #PERMISSION_GRANT_STATE_GRANTED},
8830      * @return whether the permission was successfully granted or revoked.
8831      * @throws SecurityException if {@code admin} is not a device or profile owner.
8832      * @see #PERMISSION_GRANT_STATE_DENIED
8833      * @see #PERMISSION_GRANT_STATE_DEFAULT
8834      * @see #PERMISSION_GRANT_STATE_GRANTED
8835      * @see #setDelegatedScopes
8836      * @see #DELEGATION_PERMISSION_GRANT
8837      */
setPermissionGrantState(@onNull ComponentName admin, @NonNull String packageName, @NonNull String permission, @PermissionGrantState int grantState)8838     public boolean setPermissionGrantState(@NonNull ComponentName admin,
8839             @NonNull String packageName, @NonNull String permission,
8840             @PermissionGrantState int grantState) {
8841         throwIfParentInstance("setPermissionGrantState");
8842         try {
8843             CompletableFuture<Boolean> result = new CompletableFuture<>();
8844 
8845             mService.setPermissionGrantState(admin, mContext.getPackageName(), packageName,
8846                     permission, grantState, new RemoteCallback((b) -> result.complete(b != null)));
8847 
8848             // Timeout
8849             BackgroundThread.getHandler().sendMessageDelayed(
8850                     obtainMessage(CompletableFuture::complete, result, false),
8851                     20_000);
8852 
8853             return result.get();
8854         } catch (RemoteException re) {
8855             throw re.rethrowFromSystemServer();
8856         } catch (InterruptedException | ExecutionException e) {
8857             throw new RuntimeException(e);
8858         }
8859     }
8860 
8861     /**
8862      * Returns the current grant state of a runtime permission for a specific application. This
8863      * function can be called by a device owner, profile owner, or by a delegate given the
8864      * {@link #DELEGATION_PERMISSION_GRANT} scope via {@link #setDelegatedScopes}.
8865      *
8866      * @param admin Which profile or device owner this request is associated with, or {@code null}
8867      *            if the caller is a permission grant delegate.
8868      * @param packageName The application to check the grant state for.
8869      * @param permission The permission to check for.
8870      * @return the current grant state specified by device policy. If the profile or device owner
8871      *         has not set a grant state, the return value is
8872      *         {@link #PERMISSION_GRANT_STATE_DEFAULT}. This does not indicate whether or not the
8873      *         permission is currently granted for the package.
8874      *         <p/>
8875      *         If a grant state was set by the profile or device owner, then the return value will
8876      *         be one of {@link #PERMISSION_GRANT_STATE_DENIED} or
8877      *         {@link #PERMISSION_GRANT_STATE_GRANTED}, which indicates if the permission is
8878      *         currently denied or granted.
8879      * @throws SecurityException if {@code admin} is not a device or profile owner.
8880      * @see #setPermissionGrantState(ComponentName, String, String, int)
8881      * @see PackageManager#checkPermission(String, String)
8882      * @see #setDelegatedScopes
8883      * @see #DELEGATION_PERMISSION_GRANT
8884      */
getPermissionGrantState(@ullable ComponentName admin, @NonNull String packageName, @NonNull String permission)8885     public @PermissionGrantState int getPermissionGrantState(@Nullable ComponentName admin,
8886             @NonNull String packageName, @NonNull String permission) {
8887         throwIfParentInstance("getPermissionGrantState");
8888         try {
8889             return mService.getPermissionGrantState(admin, mContext.getPackageName(), packageName,
8890                     permission);
8891         } catch (RemoteException re) {
8892             throw re.rethrowFromSystemServer();
8893         }
8894     }
8895 
8896     /**
8897      * Returns whether it is possible for the caller to initiate provisioning of a managed profile
8898      * or device, setting itself as the device or profile owner.
8899      *
8900      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
8901      * {@link #ACTION_PROVISION_MANAGED_PROFILE}.
8902      * @return whether provisioning a managed profile or device is possible.
8903      * @throws IllegalArgumentException if the supplied action is not valid.
8904      */
isProvisioningAllowed(@onNull String action)8905     public boolean isProvisioningAllowed(@NonNull String action) {
8906         throwIfParentInstance("isProvisioningAllowed");
8907         try {
8908             return mService.isProvisioningAllowed(action, mContext.getPackageName());
8909         } catch (RemoteException re) {
8910             throw re.rethrowFromSystemServer();
8911         }
8912     }
8913 
8914     /**
8915      * Checks whether it is possible to initiate provisioning a managed device,
8916      * profile or user, setting the given package as owner.
8917      *
8918      * @param action One of {@link #ACTION_PROVISION_MANAGED_DEVICE},
8919      *        {@link #ACTION_PROVISION_MANAGED_PROFILE},
8920      *        {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE},
8921      *        {@link #ACTION_PROVISION_MANAGED_USER}
8922      * @param packageName The package of the component that would be set as device, user, or profile
8923      *        owner.
8924      * @return A {@link ProvisioningPreCondition} value indicating whether provisioning is allowed.
8925      * @hide
8926      */
checkProvisioningPreCondition( String action, @NonNull String packageName)8927     public @ProvisioningPreCondition int checkProvisioningPreCondition(
8928             String action, @NonNull String packageName) {
8929         try {
8930             return mService.checkProvisioningPreCondition(action, packageName);
8931         } catch (RemoteException re) {
8932             throw re.rethrowFromSystemServer();
8933         }
8934     }
8935 
8936     /**
8937      * Return if this user is a managed profile of another user. An admin can become the profile
8938      * owner of a managed profile with {@link #ACTION_PROVISION_MANAGED_PROFILE} and of a managed
8939      * user with {@link #createAndManageUser}
8940      * @param admin Which profile owner this request is associated with.
8941      * @return if this user is a managed profile of another user.
8942      */
isManagedProfile(@onNull ComponentName admin)8943     public boolean isManagedProfile(@NonNull ComponentName admin) {
8944         throwIfParentInstance("isManagedProfile");
8945         try {
8946             return mService.isManagedProfile(admin);
8947         } catch (RemoteException re) {
8948             throw re.rethrowFromSystemServer();
8949         }
8950     }
8951 
8952     /**
8953      * @hide
8954      * Return if this user is a system-only user. An admin can manage a device from a system only
8955      * user by calling {@link #ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE}.
8956      * @param admin Which device owner this request is associated with.
8957      * @return if this user is a system-only user.
8958      */
isSystemOnlyUser(@onNull ComponentName admin)8959     public boolean isSystemOnlyUser(@NonNull ComponentName admin) {
8960         try {
8961             return mService.isSystemOnlyUser(admin);
8962         } catch (RemoteException re) {
8963             throw re.rethrowFromSystemServer();
8964         }
8965     }
8966 
8967     /**
8968      * Called by device owner to get the MAC address of the Wi-Fi device.
8969      *
8970      * @param admin Which device owner this request is associated with.
8971      * @return the MAC address of the Wi-Fi device, or null when the information is not available.
8972      *         (For example, Wi-Fi hasn't been enabled, or the device doesn't support Wi-Fi.)
8973      *         <p>
8974      *         The address will be in the {@code XX:XX:XX:XX:XX:XX} format.
8975      * @throws SecurityException if {@code admin} is not a device owner.
8976      */
getWifiMacAddress(@onNull ComponentName admin)8977     public @Nullable String getWifiMacAddress(@NonNull ComponentName admin) {
8978         throwIfParentInstance("getWifiMacAddress");
8979         try {
8980             return mService.getWifiMacAddress(admin);
8981         } catch (RemoteException re) {
8982             throw re.rethrowFromSystemServer();
8983         }
8984     }
8985 
8986     /**
8987      * Called by device owner to reboot the device. If there is an ongoing call on the device,
8988      * throws an {@link IllegalStateException}.
8989      * @param admin Which device owner the request is associated with.
8990      * @throws IllegalStateException if device has an ongoing call.
8991      * @throws SecurityException if {@code admin} is not a device owner.
8992      * @see TelephonyManager#CALL_STATE_IDLE
8993      */
reboot(@onNull ComponentName admin)8994     public void reboot(@NonNull ComponentName admin) {
8995         throwIfParentInstance("reboot");
8996         try {
8997             mService.reboot(admin);
8998         } catch (RemoteException re) {
8999             throw re.rethrowFromSystemServer();
9000         }
9001     }
9002 
9003     /**
9004      * Called by a device admin to set the short support message. This will be displayed to the user
9005      * in settings screens where funtionality has been disabled by the admin. The message should be
9006      * limited to a short statement such as "This setting is disabled by your administrator. Contact
9007      * someone@example.com for support." If the message is longer than 200 characters it may be
9008      * truncated.
9009      * <p>
9010      * If the short support message needs to be localized, it is the responsibility of the
9011      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9012      * and set a new version of this string accordingly.
9013      *
9014      * @see #setLongSupportMessage
9015      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9016      * @param message Short message to be displayed to the user in settings or null to clear the
9017      *            existing message.
9018      * @throws SecurityException if {@code admin} is not an active administrator.
9019      */
setShortSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)9020     public void setShortSupportMessage(@NonNull ComponentName admin,
9021             @Nullable CharSequence message) {
9022         throwIfParentInstance("setShortSupportMessage");
9023         if (mService != null) {
9024             try {
9025                 mService.setShortSupportMessage(admin, message);
9026             } catch (RemoteException e) {
9027                 throw e.rethrowFromSystemServer();
9028             }
9029         }
9030     }
9031 
9032     /**
9033      * Called by a device admin to get the short support message.
9034      *
9035      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9036      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)} or
9037      *         null if no message has been set.
9038      * @throws SecurityException if {@code admin} is not an active administrator.
9039      */
getShortSupportMessage(@onNull ComponentName admin)9040     public CharSequence getShortSupportMessage(@NonNull ComponentName admin) {
9041         throwIfParentInstance("getShortSupportMessage");
9042         if (mService != null) {
9043             try {
9044                 return mService.getShortSupportMessage(admin);
9045             } catch (RemoteException e) {
9046                 throw e.rethrowFromSystemServer();
9047             }
9048         }
9049         return null;
9050     }
9051 
9052     /**
9053      * Called by a device admin to set the long support message. This will be displayed to the user
9054      * in the device administators settings screen.
9055      * <p>
9056      * If the long support message needs to be localized, it is the responsibility of the
9057      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
9058      * and set a new version of this string accordingly.
9059      *
9060      * @see #setShortSupportMessage
9061      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9062      * @param message Long message to be displayed to the user in settings or null to clear the
9063      *            existing message.
9064      * @throws SecurityException if {@code admin} is not an active administrator.
9065      */
setLongSupportMessage(@onNull ComponentName admin, @Nullable CharSequence message)9066     public void setLongSupportMessage(@NonNull ComponentName admin,
9067             @Nullable CharSequence message) {
9068         throwIfParentInstance("setLongSupportMessage");
9069         if (mService != null) {
9070             try {
9071                 mService.setLongSupportMessage(admin, message);
9072             } catch (RemoteException e) {
9073                 throw e.rethrowFromSystemServer();
9074             }
9075         }
9076     }
9077 
9078     /**
9079      * Called by a device admin to get the long support message.
9080      *
9081      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9082      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)} or
9083      *         null if no message has been set.
9084      * @throws SecurityException if {@code admin} is not an active administrator.
9085      */
getLongSupportMessage(@onNull ComponentName admin)9086     public @Nullable CharSequence getLongSupportMessage(@NonNull ComponentName admin) {
9087         throwIfParentInstance("getLongSupportMessage");
9088         if (mService != null) {
9089             try {
9090                 return mService.getLongSupportMessage(admin);
9091             } catch (RemoteException e) {
9092                 throw e.rethrowFromSystemServer();
9093             }
9094         }
9095         return null;
9096     }
9097 
9098     /**
9099      * Called by the system to get the short support message.
9100      *
9101      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9102      * @param userHandle user id the admin is running as.
9103      * @return The message set by {@link #setShortSupportMessage(ComponentName, CharSequence)}
9104      *
9105      * @hide
9106      */
getShortSupportMessageForUser(@onNull ComponentName admin, int userHandle)9107     public @Nullable CharSequence getShortSupportMessageForUser(@NonNull ComponentName admin,
9108             int userHandle) {
9109         if (mService != null) {
9110             try {
9111                 return mService.getShortSupportMessageForUser(admin, userHandle);
9112             } catch (RemoteException e) {
9113                 throw e.rethrowFromSystemServer();
9114             }
9115         }
9116         return null;
9117     }
9118 
9119 
9120     /**
9121      * Called by the system to get the long support message.
9122      *
9123      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9124      * @param userHandle user id the admin is running as.
9125      * @return The message set by {@link #setLongSupportMessage(ComponentName, CharSequence)}
9126      *
9127      * @hide
9128      */
getLongSupportMessageForUser( @onNull ComponentName admin, int userHandle)9129     public @Nullable CharSequence getLongSupportMessageForUser(
9130             @NonNull ComponentName admin, int userHandle) {
9131         if (mService != null) {
9132             try {
9133                 return mService.getLongSupportMessageForUser(admin, userHandle);
9134             } catch (RemoteException e) {
9135                 throw e.rethrowFromSystemServer();
9136             }
9137         }
9138         return null;
9139     }
9140 
9141     /**
9142      * Called by the profile owner of a managed profile to obtain a {@link DevicePolicyManager}
9143      * whose calls act on the parent profile.
9144      *
9145      * <p>The following methods are supported for the parent instance, all other methods will
9146      * throw a SecurityException when called on the parent instance:
9147      * <ul>
9148      * <li>{@link #getPasswordQuality}</li>
9149      * <li>{@link #setPasswordQuality}</li>
9150      * <li>{@link #getPasswordMinimumLength}</li>
9151      * <li>{@link #setPasswordMinimumLength}</li>
9152      * <li>{@link #getPasswordMinimumUpperCase}</li>
9153      * <li>{@link #setPasswordMinimumUpperCase}</li>
9154      * <li>{@link #getPasswordMinimumLowerCase}</li>
9155      * <li>{@link #setPasswordMinimumLowerCase}</li>
9156      * <li>{@link #getPasswordMinimumLetters}</li>
9157      * <li>{@link #setPasswordMinimumLetters}</li>
9158      * <li>{@link #getPasswordMinimumNumeric}</li>
9159      * <li>{@link #setPasswordMinimumNumeric}</li>
9160      * <li>{@link #getPasswordMinimumSymbols}</li>
9161      * <li>{@link #setPasswordMinimumSymbols}</li>
9162      * <li>{@link #getPasswordMinimumNonLetter}</li>
9163      * <li>{@link #setPasswordMinimumNonLetter}</li>
9164      * <li>{@link #getPasswordHistoryLength}</li>
9165      * <li>{@link #setPasswordHistoryLength}</li>
9166      * <li>{@link #getPasswordExpirationTimeout}</li>
9167      * <li>{@link #setPasswordExpirationTimeout}</li>
9168      * <li>{@link #getPasswordExpiration}</li>
9169      * <li>{@link #getPasswordMaximumLength}</li>
9170      * <li>{@link #isActivePasswordSufficient}</li>
9171      * <li>{@link #getCurrentFailedPasswordAttempts}</li>
9172      * <li>{@link #getMaximumFailedPasswordsForWipe}</li>
9173      * <li>{@link #setMaximumFailedPasswordsForWipe}</li>
9174      * <li>{@link #getMaximumTimeToLock}</li>
9175      * <li>{@link #setMaximumTimeToLock}</li>
9176      * <li>{@link #lockNow}</li>
9177      * <li>{@link #getKeyguardDisabledFeatures}</li>
9178      * <li>{@link #setKeyguardDisabledFeatures}</li>
9179      * <li>{@link #getTrustAgentConfiguration}</li>
9180      * <li>{@link #setTrustAgentConfiguration}</li>
9181      * <li>{@link #getRequiredStrongAuthTimeout}</li>
9182      * <li>{@link #setRequiredStrongAuthTimeout}</li>
9183      * </ul>
9184      *
9185      * @return a new instance of {@link DevicePolicyManager} that acts on the parent profile.
9186      * @throws SecurityException if {@code admin} is not a profile owner.
9187      */
getParentProfileInstance(@onNull ComponentName admin)9188     public @NonNull DevicePolicyManager getParentProfileInstance(@NonNull ComponentName admin) {
9189         throwIfParentInstance("getParentProfileInstance");
9190         try {
9191             if (!mService.isManagedProfile(admin)) {
9192                 throw new SecurityException("The current user does not have a parent profile.");
9193             }
9194             return new DevicePolicyManager(mContext, mService, true);
9195         } catch (RemoteException e) {
9196             throw e.rethrowFromSystemServer();
9197         }
9198     }
9199 
9200     /**
9201      * Called by device owner to control the security logging feature.
9202      *
9203      * <p> Security logs contain various information intended for security auditing purposes.
9204      * See {@link SecurityEvent} for details.
9205      *
9206      * <p><strong>Note:</strong> The device owner won't be able to retrieve security logs if there
9207      * are unaffiliated secondary users or profiles on the device, regardless of whether the
9208      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
9209      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
9210      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
9211      *
9212      * @param admin Which device owner this request is associated with.
9213      * @param enabled whether security logging should be enabled or not.
9214      * @throws SecurityException if {@code admin} is not a device owner.
9215      * @see #setAffiliationIds
9216      * @see #retrieveSecurityLogs
9217      */
setSecurityLoggingEnabled(@onNull ComponentName admin, boolean enabled)9218     public void setSecurityLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
9219         throwIfParentInstance("setSecurityLoggingEnabled");
9220         try {
9221             mService.setSecurityLoggingEnabled(admin, enabled);
9222         } catch (RemoteException re) {
9223             throw re.rethrowFromSystemServer();
9224         }
9225     }
9226 
9227     /**
9228      * Return whether security logging is enabled or not by the device owner.
9229      *
9230      * <p>Can only be called by the device owner, otherwise a {@link SecurityException} will be
9231      * thrown.
9232      *
9233      * @param admin Which device owner this request is associated with.
9234      * @return {@code true} if security logging is enabled by device owner, {@code false} otherwise.
9235      * @throws SecurityException if {@code admin} is not a device owner.
9236      */
isSecurityLoggingEnabled(@ullable ComponentName admin)9237     public boolean isSecurityLoggingEnabled(@Nullable ComponentName admin) {
9238         throwIfParentInstance("isSecurityLoggingEnabled");
9239         try {
9240             return mService.isSecurityLoggingEnabled(admin);
9241         } catch (RemoteException re) {
9242             throw re.rethrowFromSystemServer();
9243         }
9244     }
9245 
9246     /**
9247      * Called by device owner to retrieve all new security logging entries since the last call to
9248      * this API after device boots.
9249      *
9250      * <p> Access to the logs is rate limited and it will only return new logs after the device
9251      * owner has been notified via {@link DeviceAdminReceiver#onSecurityLogsAvailable}.
9252      *
9253      * <p>If there is any other user or profile on the device, it must be affiliated with the
9254      * device. Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
9255      *
9256      * @param admin Which device owner this request is associated with.
9257      * @return the new batch of security logs which is a list of {@link SecurityEvent},
9258      * or {@code null} if rate limitation is exceeded or if logging is currently disabled.
9259      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
9260      * profile or secondary user that is not affiliated with the device.
9261      * @see #isAffiliatedUser
9262      * @see DeviceAdminReceiver#onSecurityLogsAvailable
9263      */
retrieveSecurityLogs(@onNull ComponentName admin)9264     public @Nullable List<SecurityEvent> retrieveSecurityLogs(@NonNull ComponentName admin) {
9265         throwIfParentInstance("retrieveSecurityLogs");
9266         try {
9267             ParceledListSlice<SecurityEvent> list = mService.retrieveSecurityLogs(admin);
9268             if (list != null) {
9269                 return list.getList();
9270             } else {
9271                 // Rate limit exceeded.
9272                 return null;
9273             }
9274         } catch (RemoteException re) {
9275             throw re.rethrowFromSystemServer();
9276         }
9277     }
9278 
9279     /**
9280      * Makes all accumulated network logs available to DPC in a new batch.
9281      * Only callable by ADB. If throttled, returns time to wait in milliseconds, otherwise 0.
9282      * @hide
9283      */
forceNetworkLogs()9284     public long forceNetworkLogs() {
9285         if (mService == null) {
9286             return -1;
9287         }
9288         try {
9289             return mService.forceNetworkLogs();
9290         } catch (RemoteException re) {
9291             throw re.rethrowFromSystemServer();
9292         }
9293     }
9294 
9295     /**
9296      * Forces a batch of security logs to be fetched from logd and makes it available for DPC.
9297      * Only callable by ADB. If throttled, returns time to wait in milliseconds, otherwise 0.
9298      * @hide
9299      */
forceSecurityLogs()9300     public long forceSecurityLogs() {
9301         if (mService == null) {
9302             return 0;
9303         }
9304         try {
9305             return mService.forceSecurityLogs();
9306         } catch (RemoteException re) {
9307             throw re.rethrowFromSystemServer();
9308         }
9309     }
9310 
9311     /**
9312      * Called by the system to obtain a {@link DevicePolicyManager} whose calls act on the parent
9313      * profile.
9314      *
9315      * @hide
9316      */
getParentProfileInstance(UserInfo uInfo)9317     public @NonNull DevicePolicyManager getParentProfileInstance(UserInfo uInfo) {
9318         mContext.checkSelfPermission(
9319                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
9320         if (!uInfo.isManagedProfile()) {
9321             throw new SecurityException("The user " + uInfo.id
9322                     + " does not have a parent profile.");
9323         }
9324         return new DevicePolicyManager(mContext, mService, true);
9325     }
9326 
9327     /**
9328      * Called by a device or profile owner to restrict packages from using metered data.
9329      *
9330      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9331      * @param packageNames the list of package names to be restricted.
9332      * @return a list of package names which could not be restricted.
9333      * @throws SecurityException if {@code admin} is not a device or profile owner.
9334      */
setMeteredDataDisabledPackages(@onNull ComponentName admin, @NonNull List<String> packageNames)9335     public @NonNull List<String> setMeteredDataDisabledPackages(@NonNull ComponentName admin,
9336             @NonNull List<String> packageNames) {
9337         throwIfParentInstance("setMeteredDataDisabled");
9338         if (mService != null) {
9339             try {
9340                 return mService.setMeteredDataDisabledPackages(admin, packageNames);
9341             } catch (RemoteException re) {
9342                 throw re.rethrowFromSystemServer();
9343             }
9344         }
9345         return packageNames;
9346     }
9347 
9348     /**
9349      * Called by a device or profile owner to retrieve the list of packages which are restricted
9350      * by the admin from using metered data.
9351      *
9352      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9353      * @return the list of restricted package names.
9354      * @throws SecurityException if {@code admin} is not a device or profile owner.
9355      */
getMeteredDataDisabledPackages(@onNull ComponentName admin)9356     public @NonNull List<String> getMeteredDataDisabledPackages(@NonNull ComponentName admin) {
9357         throwIfParentInstance("getMeteredDataDisabled");
9358         if (mService != null) {
9359             try {
9360                 return mService.getMeteredDataDisabledPackages(admin);
9361             } catch (RemoteException re) {
9362                 throw re.rethrowFromSystemServer();
9363             }
9364         }
9365         return new ArrayList<>();
9366     }
9367 
9368     /**
9369      * Called by the system to check if a package is restricted from using metered data
9370      * by {@param admin}.
9371      *
9372      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
9373      * @param packageName the package whose restricted status is needed.
9374      * @param userId the user to which {@param packageName} belongs.
9375      * @return {@code true} if the package is restricted by admin, otherwise {@code false}
9376      * @throws SecurityException if the caller doesn't run with {@link Process#SYSTEM_UID}
9377      * @hide
9378      */
isMeteredDataDisabledPackageForUser(@onNull ComponentName admin, String packageName, @UserIdInt int userId)9379     public boolean isMeteredDataDisabledPackageForUser(@NonNull ComponentName admin,
9380             String packageName, @UserIdInt int userId) {
9381         throwIfParentInstance("getMeteredDataDisabledForUser");
9382         if (mService != null) {
9383             try {
9384                 return mService.isMeteredDataDisabledPackageForUser(admin, packageName, userId);
9385             } catch (RemoteException re) {
9386                 throw re.rethrowFromSystemServer();
9387             }
9388         }
9389         return false;
9390     }
9391 
9392     /**
9393      * Called by device owners to retrieve device logs from before the device's last reboot.
9394      * <p>
9395      * <strong> This API is not supported on all devices. Calling this API on unsupported devices
9396      * will result in {@code null} being returned. The device logs are retrieved from a RAM region
9397      * which is not guaranteed to be corruption-free during power cycles, as a result be cautious
9398      * about data corruption when parsing. </strong>
9399      *
9400      * <p>If there is any other user or profile on the device, it must be affiliated with the
9401      * device. Otherwise a {@link SecurityException} will be thrown. See {@link #isAffiliatedUser}.
9402      *
9403      * @param admin Which device owner this request is associated with.
9404      * @return Device logs from before the latest reboot of the system, or {@code null} if this API
9405      *         is not supported on the device.
9406      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
9407      * profile or secondary user that is not affiliated with the device.
9408      * @see #isAffiliatedUser
9409      * @see #retrieveSecurityLogs
9410      */
retrievePreRebootSecurityLogs( @onNull ComponentName admin)9411     public @Nullable List<SecurityEvent> retrievePreRebootSecurityLogs(
9412             @NonNull ComponentName admin) {
9413         throwIfParentInstance("retrievePreRebootSecurityLogs");
9414         try {
9415             ParceledListSlice<SecurityEvent> list = mService.retrievePreRebootSecurityLogs(admin);
9416             if (list != null) {
9417                 return list.getList();
9418             } else {
9419                 return null;
9420             }
9421         } catch (RemoteException re) {
9422             throw re.rethrowFromSystemServer();
9423         }
9424     }
9425 
9426     /**
9427      * Called by a profile owner of a managed profile to set the color used for customization. This
9428      * color is used as background color of the confirm credentials screen for that user. The
9429      * default color is teal (#00796B).
9430      * <p>
9431      * The confirm credentials screen can be created using
9432      * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
9433      *
9434      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9435      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
9436      * @throws SecurityException if {@code admin} is not a profile owner.
9437      */
setOrganizationColor(@onNull ComponentName admin, int color)9438     public void setOrganizationColor(@NonNull ComponentName admin, int color) {
9439         throwIfParentInstance("setOrganizationColor");
9440         try {
9441             // always enforce alpha channel to have 100% opacity
9442             color |= 0xFF000000;
9443             mService.setOrganizationColor(admin, color);
9444         } catch (RemoteException re) {
9445             throw re.rethrowFromSystemServer();
9446         }
9447     }
9448 
9449     /**
9450      * @hide
9451      *
9452      * Sets the color used for customization.
9453      *
9454      * @param color The 24bit (0xRRGGBB) representation of the color to be used.
9455      * @param userId which user to set the color to.
9456      * @RequiresPermission(allOf = {
9457      *       Manifest.permission.MANAGE_USERS,
9458      *       Manifest.permission.INTERACT_ACROSS_USERS_FULL})
9459      */
setOrganizationColorForUser(@olorInt int color, @UserIdInt int userId)9460     public void setOrganizationColorForUser(@ColorInt int color, @UserIdInt int userId) {
9461         try {
9462             // always enforce alpha channel to have 100% opacity
9463             color |= 0xFF000000;
9464             mService.setOrganizationColorForUser(color, userId);
9465         } catch (RemoteException re) {
9466             throw re.rethrowFromSystemServer();
9467         }
9468     }
9469 
9470     /**
9471      * Called by a profile owner of a managed profile to retrieve the color used for customization.
9472      * This color is used as background color of the confirm credentials screen for that user.
9473      *
9474      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9475      * @return The 24bit (0xRRGGBB) representation of the color to be used.
9476      * @throws SecurityException if {@code admin} is not a profile owner.
9477      */
getOrganizationColor(@onNull ComponentName admin)9478     public @ColorInt int getOrganizationColor(@NonNull ComponentName admin) {
9479         throwIfParentInstance("getOrganizationColor");
9480         try {
9481             return mService.getOrganizationColor(admin);
9482         } catch (RemoteException re) {
9483             throw re.rethrowFromSystemServer();
9484         }
9485     }
9486 
9487     /**
9488      * @hide
9489      * Retrieve the customization color for a given user.
9490      *
9491      * @param userHandle The user id of the user we're interested in.
9492      * @return The 24bit (0xRRGGBB) representation of the color to be used.
9493      */
getOrganizationColorForUser(int userHandle)9494     public @ColorInt int getOrganizationColorForUser(int userHandle) {
9495         try {
9496             return mService.getOrganizationColorForUser(userHandle);
9497         } catch (RemoteException re) {
9498             throw re.rethrowFromSystemServer();
9499         }
9500     }
9501 
9502     /**
9503      * Called by the device owner (since API 26) or profile owner (since API 24) to set the name of
9504      * the organization under management.
9505      *
9506      * <p>If the organization name needs to be localized, it is the responsibility of the {@link
9507      * DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast and set
9508      * a new version of this string accordingly.
9509      *
9510      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9511      * @param title The organization name or {@code null} to clear a previously set name.
9512      * @throws SecurityException if {@code admin} is not a device or profile owner.
9513      */
setOrganizationName(@onNull ComponentName admin, @Nullable CharSequence title)9514     public void setOrganizationName(@NonNull ComponentName admin, @Nullable CharSequence title) {
9515         throwIfParentInstance("setOrganizationName");
9516         try {
9517             mService.setOrganizationName(admin, title);
9518         } catch (RemoteException re) {
9519             throw re.rethrowFromSystemServer();
9520         }
9521     }
9522 
9523     /**
9524      * Called by a profile owner of a managed profile to retrieve the name of the organization under
9525      * management.
9526      *
9527      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9528      * @return The organization name or {@code null} if none is set.
9529      * @throws SecurityException if {@code admin} is not a profile owner.
9530      */
getOrganizationName(@onNull ComponentName admin)9531     public @Nullable CharSequence getOrganizationName(@NonNull ComponentName admin) {
9532         throwIfParentInstance("getOrganizationName");
9533         try {
9534             return mService.getOrganizationName(admin);
9535         } catch (RemoteException re) {
9536             throw re.rethrowFromSystemServer();
9537         }
9538     }
9539 
9540     /**
9541      * Called by the system to retrieve the name of the organization managing the device.
9542      *
9543      * @return The organization name or {@code null} if none is set.
9544      * @throws SecurityException if the caller is not the device owner, does not hold the
9545      *         MANAGE_USERS permission and is not the system.
9546      *
9547      * @hide
9548      */
9549     @SystemApi
9550     @TestApi
9551     @SuppressLint("Doclava125")
getDeviceOwnerOrganizationName()9552     public @Nullable CharSequence getDeviceOwnerOrganizationName() {
9553         try {
9554             return mService.getDeviceOwnerOrganizationName();
9555         } catch (RemoteException re) {
9556             throw re.rethrowFromSystemServer();
9557         }
9558     }
9559 
9560     /**
9561      * Retrieve the default title message used in the confirm credentials screen for a given user.
9562      *
9563      * @param userHandle The user id of the user we're interested in.
9564      * @return The organization name or {@code null} if none is set.
9565      *
9566      * @hide
9567      */
getOrganizationNameForUser(int userHandle)9568     public @Nullable CharSequence getOrganizationNameForUser(int userHandle) {
9569         try {
9570             return mService.getOrganizationNameForUser(userHandle);
9571         } catch (RemoteException re) {
9572             throw re.rethrowFromSystemServer();
9573         }
9574     }
9575 
9576     /**
9577      * @return the {@link UserProvisioningState} for the current user - for unmanaged users will
9578      *         return {@link #STATE_USER_UNMANAGED}
9579      * @hide
9580      */
9581     @SystemApi
9582     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
9583     @UserProvisioningState
getUserProvisioningState()9584     public int getUserProvisioningState() {
9585         throwIfParentInstance("getUserProvisioningState");
9586         if (mService != null) {
9587             try {
9588                 return mService.getUserProvisioningState();
9589             } catch (RemoteException e) {
9590                 throw e.rethrowFromSystemServer();
9591             }
9592         }
9593         return STATE_USER_UNMANAGED;
9594     }
9595 
9596     /**
9597      * Set the {@link UserProvisioningState} for the supplied user, if they are managed.
9598      *
9599      * @param state to store
9600      * @param userHandle for user
9601      * @hide
9602      */
setUserProvisioningState(@serProvisioningState int state, int userHandle)9603     public void setUserProvisioningState(@UserProvisioningState int state, int userHandle) {
9604         if (mService != null) {
9605             try {
9606                 mService.setUserProvisioningState(state, userHandle);
9607             } catch (RemoteException e) {
9608                 throw e.rethrowFromSystemServer();
9609             }
9610         }
9611     }
9612 
9613     /**
9614      * Indicates the entity that controls the device or profile owner. Two users/profiles are
9615      * affiliated if the set of ids set by their device or profile owners intersect.
9616      *
9617      * <p>A user/profile that is affiliated with the device owner user is considered to be
9618      * affiliated with the device.
9619      *
9620      * <p><strong>Note:</strong> Features that depend on user affiliation (such as security logging
9621      * or {@link #bindDeviceAdminServiceAsUser}) won't be available when a secondary user or profile
9622      * is created, until it becomes affiliated. Therefore it is recommended that the appropriate
9623      * affiliation ids are set by its profile owner as soon as possible after the user/profile is
9624      * created.
9625      *
9626      * @param admin Which profile or device owner this request is associated with.
9627      * @param ids A set of opaque non-empty affiliation ids.
9628      *
9629      * @throws IllegalArgumentException if {@code ids} is null or contains an empty string.
9630      * @see #isAffiliatedUser
9631      */
setAffiliationIds(@onNull ComponentName admin, @NonNull Set<String> ids)9632     public void setAffiliationIds(@NonNull ComponentName admin, @NonNull Set<String> ids) {
9633         throwIfParentInstance("setAffiliationIds");
9634         if (ids == null) {
9635             throw new IllegalArgumentException("ids must not be null");
9636         }
9637         try {
9638             mService.setAffiliationIds(admin, new ArrayList<>(ids));
9639         } catch (RemoteException e) {
9640             throw e.rethrowFromSystemServer();
9641         }
9642     }
9643 
9644     /**
9645      * Returns the set of affiliation ids previously set via {@link #setAffiliationIds}, or an
9646      * empty set if none have been set.
9647      */
getAffiliationIds(@onNull ComponentName admin)9648     public @NonNull Set<String> getAffiliationIds(@NonNull ComponentName admin) {
9649         throwIfParentInstance("getAffiliationIds");
9650         try {
9651             return new ArraySet<>(mService.getAffiliationIds(admin));
9652         } catch (RemoteException e) {
9653             throw e.rethrowFromSystemServer();
9654         }
9655     }
9656 
9657     /**
9658      * Returns whether this user/profile is affiliated with the device.
9659      * <p>
9660      * By definition, the user that the device owner runs on is always affiliated with the device.
9661      * Any other user/profile is considered affiliated with the device if the set specified by its
9662      * profile owner via {@link #setAffiliationIds} intersects with the device owner's.
9663      * @see #setAffiliationIds
9664      */
isAffiliatedUser()9665     public boolean isAffiliatedUser() {
9666         throwIfParentInstance("isAffiliatedUser");
9667         try {
9668             return mService.isAffiliatedUser();
9669         } catch (RemoteException e) {
9670             throw e.rethrowFromSystemServer();
9671         }
9672     }
9673 
9674     /**
9675      * @hide
9676      * Returns whether the uninstall for {@code packageName} for the current user is in queue
9677      * to be started
9678      * @param packageName the package to check for
9679      * @return whether the uninstall intent for {@code packageName} is pending
9680      */
isUninstallInQueue(String packageName)9681     public boolean isUninstallInQueue(String packageName) {
9682         try {
9683             return mService.isUninstallInQueue(packageName);
9684         } catch (RemoteException re) {
9685             throw re.rethrowFromSystemServer();
9686         }
9687     }
9688 
9689     /**
9690      * @hide
9691      * @param packageName the package containing active DAs to be uninstalled
9692      */
uninstallPackageWithActiveAdmins(String packageName)9693     public void uninstallPackageWithActiveAdmins(String packageName) {
9694         try {
9695             mService.uninstallPackageWithActiveAdmins(packageName);
9696         } catch (RemoteException re) {
9697             throw re.rethrowFromSystemServer();
9698         }
9699     }
9700 
9701     /**
9702      * @hide
9703      * Remove a test admin synchronously without sending it a broadcast about being removed.
9704      * If the admin is a profile owner or device owner it will still be removed.
9705      *
9706      * @param userHandle user id to remove the admin for.
9707      * @param admin The administration compononent to remove.
9708      * @throws SecurityException if the caller is not shell / root or the admin package
9709      *         isn't a test application see {@link ApplicationInfo#FLAG_TEST_APP}.
9710      */
forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle)9711     public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
9712         try {
9713             mService.forceRemoveActiveAdmin(adminReceiver, userHandle);
9714         } catch (RemoteException re) {
9715             throw re.rethrowFromSystemServer();
9716         }
9717     }
9718 
9719     /**
9720      * Returns whether the device has been provisioned.
9721      *
9722      * <p>Not for use by third-party applications.
9723      *
9724      * @hide
9725      */
9726     @SystemApi
9727     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioned()9728     public boolean isDeviceProvisioned() {
9729         try {
9730             return mService.isDeviceProvisioned();
9731         } catch (RemoteException re) {
9732             throw re.rethrowFromSystemServer();
9733         }
9734     }
9735 
9736     /**
9737       * Writes that the provisioning configuration has been applied.
9738       *
9739       * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS}
9740       * permission.
9741       *
9742       * <p>Not for use by third-party applications.
9743       *
9744       * @hide
9745       */
9746     @SystemApi
9747     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
setDeviceProvisioningConfigApplied()9748     public void setDeviceProvisioningConfigApplied() {
9749         try {
9750             mService.setDeviceProvisioningConfigApplied();
9751         } catch (RemoteException re) {
9752             throw re.rethrowFromSystemServer();
9753         }
9754     }
9755 
9756     /**
9757      * Returns whether the provisioning configuration has been applied.
9758      *
9759      * <p>The caller must hold the {@link android.Manifest.permission#MANAGE_USERS} permission.
9760      *
9761      * <p>Not for use by third-party applications.
9762      *
9763      * @return whether the provisioning configuration has been applied.
9764      *
9765      * @hide
9766      */
9767     @SystemApi
9768     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isDeviceProvisioningConfigApplied()9769     public boolean isDeviceProvisioningConfigApplied() {
9770         try {
9771             return mService.isDeviceProvisioningConfigApplied();
9772         } catch (RemoteException re) {
9773             throw re.rethrowFromSystemServer();
9774         }
9775     }
9776 
9777     /**
9778      * @hide
9779      * Force update user setup completed status. This API has no effect on user build.
9780      * @throws {@link SecurityException} if the caller has no
9781      *         {@code android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS} or the caller is
9782      *         not {@link UserHandle#SYSTEM_USER}
9783      */
forceUpdateUserSetupComplete()9784     public void forceUpdateUserSetupComplete() {
9785         try {
9786             mService.forceUpdateUserSetupComplete();
9787         } catch (RemoteException re) {
9788             throw re.rethrowFromSystemServer();
9789         }
9790     }
9791 
9792     @UnsupportedAppUsage
throwIfParentInstance(String functionName)9793     private void throwIfParentInstance(String functionName) {
9794         if (mParentInstance) {
9795             throw new SecurityException(functionName + " cannot be called on the parent instance");
9796         }
9797     }
9798 
9799     /**
9800      * Allows the device owner or profile owner to enable or disable the backup service.
9801      *
9802      * <p> Each user has its own backup service which manages the backup and restore mechanisms in
9803      * that user. Disabling the backup service will prevent data from being backed up or restored.
9804      *
9805      * <p> Device owner calls this API to control backup services across all users on the device.
9806      * Profile owner can use this API to enable or disable the profile's backup service. However,
9807      * for a managed profile its backup functionality is only enabled if both the device owner
9808      * and the profile owner have enabled the backup service.
9809      *
9810      * <p> By default, backup service is disabled on a device with device owner, and within a
9811      * managed profile.
9812      *
9813      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9814      * @param enabled {@code true} to enable the backup service, {@code false} to disable it.
9815      * @throws SecurityException if {@code admin} is not a device owner or a profile owner.
9816      */
setBackupServiceEnabled(@onNull ComponentName admin, boolean enabled)9817     public void setBackupServiceEnabled(@NonNull ComponentName admin, boolean enabled) {
9818         throwIfParentInstance("setBackupServiceEnabled");
9819         try {
9820             mService.setBackupServiceEnabled(admin, enabled);
9821         } catch (RemoteException re) {
9822             throw re.rethrowFromSystemServer();
9823         }
9824     }
9825 
9826     /**
9827      * Return whether the backup service is enabled by the device owner or profile owner for the
9828      * current user, as previously set by {@link #setBackupServiceEnabled(ComponentName, boolean)}.
9829      *
9830      * <p> Whether the backup functionality is actually enabled or not depends on settings from both
9831      * the current user and the device owner, please see
9832      * {@link #setBackupServiceEnabled(ComponentName, boolean)} for details.
9833      *
9834      * <p> Backup service manages all backup and restore mechanisms on the device.
9835      *
9836      * @return {@code true} if backup service is enabled, {@code false} otherwise.
9837      * @see #setBackupServiceEnabled
9838      */
isBackupServiceEnabled(@onNull ComponentName admin)9839     public boolean isBackupServiceEnabled(@NonNull ComponentName admin) {
9840         throwIfParentInstance("isBackupServiceEnabled");
9841         try {
9842             return mService.isBackupServiceEnabled(admin);
9843         } catch (RemoteException re) {
9844             throw re.rethrowFromSystemServer();
9845         }
9846     }
9847 
9848     /**
9849      * Called by a device owner or delegated app with {@link #DELEGATION_NETWORK_LOGGING} to
9850      * control the network logging feature.
9851      *
9852      * <p> Network logs contain DNS lookup and connect() library call events. The following library
9853      *     functions are recorded while network logging is active:
9854      *     <ul>
9855      *       <li>{@code getaddrinfo()}</li>
9856      *       <li>{@code gethostbyname()}</li>
9857      *       <li>{@code connect()}</li>
9858      *     </ul>
9859      *
9860      * <p> Network logging is a low-overhead tool for forensics but it is not guaranteed to use
9861      *     full system call logging; event reporting is enabled by default for all processes but not
9862      *     strongly enforced.
9863      *     Events from applications using alternative implementations of libc, making direct kernel
9864      *     calls, or deliberately obfuscating traffic may not be recorded.
9865      *
9866      * <p> Some common network events may not be reported. For example:
9867      *     <ul>
9868      *       <li>Applications may hardcode IP addresses to reduce the number of DNS lookups, or use
9869      *           an alternative system for name resolution, and so avoid calling
9870      *           {@code getaddrinfo()} or {@code gethostbyname}.</li>
9871      *       <li>Applications may use datagram sockets for performance reasons, for example
9872      *           for a game client. Calling {@code connect()} is unnecessary for this kind of
9873      *           socket, so it will not trigger a network event.</li>
9874      *     </ul>
9875      *
9876      * <p> It is possible to directly intercept layer 3 traffic leaving the device using an
9877      *     always-on VPN service.
9878      *     See {@link #setAlwaysOnVpnPackage(ComponentName, String, boolean)}
9879      *     and {@link android.net.VpnService} for details.
9880      *
9881      * <p><strong>Note:</strong> The device owner won't be able to retrieve network logs if there
9882      * are unaffiliated secondary users or profiles on the device, regardless of whether the
9883      * feature is enabled. Logs will be discarded if the internal buffer fills up while waiting for
9884      * all users to become affiliated. Therefore it's recommended that affiliation ids are set for
9885      * new users as soon as possible after provisioning via {@link #setAffiliationIds}.
9886      *
9887      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9888      *        {@code null} if called by a delegated app.
9889      * @param enabled whether network logging should be enabled or not.
9890      * @throws SecurityException if {@code admin} is not a device owner.
9891      * @see #setAffiliationIds
9892      * @see #retrieveNetworkLogs
9893      */
setNetworkLoggingEnabled(@ullable ComponentName admin, boolean enabled)9894     public void setNetworkLoggingEnabled(@Nullable ComponentName admin, boolean enabled) {
9895         throwIfParentInstance("setNetworkLoggingEnabled");
9896         try {
9897             mService.setNetworkLoggingEnabled(admin, mContext.getPackageName(), enabled);
9898         } catch (RemoteException re) {
9899             throw re.rethrowFromSystemServer();
9900         }
9901     }
9902 
9903     /**
9904      * Return whether network logging is enabled by a device owner.
9905      *
9906      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
9907      * be {@code null} if the caller is a delegated app with {@link #DELEGATION_NETWORK_LOGGING}
9908      * or has MANAGE_USERS permission.
9909      * @return {@code true} if network logging is enabled by device owner, {@code false} otherwise.
9910      * @throws SecurityException if {@code admin} is not a device owner and caller has
9911      * no MANAGE_USERS permission
9912      */
isNetworkLoggingEnabled(@ullable ComponentName admin)9913     public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
9914         throwIfParentInstance("isNetworkLoggingEnabled");
9915         try {
9916             return mService.isNetworkLoggingEnabled(admin, mContext.getPackageName());
9917         } catch (RemoteException re) {
9918             throw re.rethrowFromSystemServer();
9919         }
9920     }
9921 
9922     /**
9923      * Called by device owner or delegated app with {@link #DELEGATION_NETWORK_LOGGING} to retrieve
9924      * the most recent batch of network logging events.
9925      * A device owner has to provide a batchToken provided as part of
9926      * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
9927      * token of the most recent available batch of logs, {@code null} will be returned.
9928      *
9929      * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
9930      *
9931      * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
9932      *
9933      * <p> Access to the logs is rate limited and this method will only return a new batch of logs
9934      * after the device device owner has been notified via
9935      * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
9936      *
9937      * <p>If a secondary user or profile is created, calling this method will throw a
9938      * {@link SecurityException} until all users become affiliated again. It will also no longer be
9939      * possible to retrieve the network logs batch with the most recent batchToken provided
9940      * by {@link DeviceAdminReceiver#onNetworkLogsAvailable}. See
9941      * {@link DevicePolicyManager#setAffiliationIds}.
9942      *
9943      * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or
9944      *        {@code null} if called by a delegated app.
9945      * @param batchToken A token of the batch to retrieve
9946      * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
9947      *        {@code null} if the batch represented by batchToken is no longer available or if
9948      *        logging is disabled.
9949      * @throws SecurityException if {@code admin} is not a device owner, or there is at least one
9950      * profile or secondary user that is not affiliated with the device.
9951      * @see #setAffiliationIds
9952      * @see DeviceAdminReceiver#onNetworkLogsAvailable
9953      */
retrieveNetworkLogs(@ullable ComponentName admin, long batchToken)9954     public @Nullable List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin,
9955             long batchToken) {
9956         throwIfParentInstance("retrieveNetworkLogs");
9957         try {
9958             return mService.retrieveNetworkLogs(admin, mContext.getPackageName(), batchToken);
9959         } catch (RemoteException re) {
9960             throw re.rethrowFromSystemServer();
9961         }
9962     }
9963 
9964     /**
9965      * Called by a device owner to bind to a service from a profile owner or vice versa.
9966      * See {@link #getBindDeviceAdminTargetUsers} for a definition of which
9967      * device/profile owners are allowed to bind to services of another profile/device owner.
9968      * <p>
9969      * The service must be protected by {@link android.Manifest.permission#BIND_DEVICE_ADMIN}.
9970      * Note that the {@link Context} used to obtain this
9971      * {@link DevicePolicyManager} instance via {@link Context#getSystemService(Class)} will be used
9972      * to bind to the {@link android.app.Service}.
9973      *
9974      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
9975      * @param serviceIntent Identifies the service to connect to.  The Intent must specify either an
9976      *        explicit component name or a package name to match an
9977      *        {@link IntentFilter} published by a service.
9978      * @param conn Receives information as the service is started and stopped in main thread. This
9979      *        must be a valid {@link ServiceConnection} object; it must not be {@code null}.
9980      * @param flags Operation options for the binding operation. See
9981      *        {@link Context#bindService(Intent, ServiceConnection, int)}.
9982      * @param targetUser Which user to bind to. Must be one of the users returned by
9983      *        {@link #getBindDeviceAdminTargetUsers}, otherwise a {@link SecurityException} will
9984      *        be thrown.
9985      * @return If you have successfully bound to the service, {@code true} is returned;
9986      *         {@code false} is returned if the connection is not made and you will not
9987      *         receive the service object.
9988      *
9989      * @see Context#bindService(Intent, ServiceConnection, int)
9990      * @see #getBindDeviceAdminTargetUsers(ComponentName)
9991      */
bindDeviceAdminServiceAsUser( @onNull ComponentName admin, Intent serviceIntent, @NonNull ServiceConnection conn, @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser)9992     public boolean bindDeviceAdminServiceAsUser(
9993             @NonNull ComponentName admin,  Intent serviceIntent, @NonNull ServiceConnection conn,
9994             @Context.BindServiceFlags int flags, @NonNull UserHandle targetUser) {
9995         throwIfParentInstance("bindDeviceAdminServiceAsUser");
9996         // Keep this in sync with ContextImpl.bindServiceCommon.
9997         try {
9998             final IServiceConnection sd = mContext.getServiceDispatcher(
9999                     conn, mContext.getMainThreadHandler(), flags);
10000             serviceIntent.prepareToLeaveProcess(mContext);
10001             return mService.bindDeviceAdminServiceAsUser(admin,
10002                     mContext.getIApplicationThread(), mContext.getActivityToken(), serviceIntent,
10003                     sd, flags, targetUser.getIdentifier());
10004         } catch (RemoteException re) {
10005             throw re.rethrowFromSystemServer();
10006         }
10007     }
10008 
10009     /**
10010      * Returns the list of target users that the calling device or profile owner can use when
10011      * calling {@link #bindDeviceAdminServiceAsUser}.
10012      * <p>
10013      * A device owner can bind to a service from a profile owner and vice versa, provided that:
10014      * <ul>
10015      * <li>Both belong to the same package name.
10016      * <li>Both users are affiliated. See {@link #setAffiliationIds}.
10017      * </ul>
10018      */
getBindDeviceAdminTargetUsers(@onNull ComponentName admin)10019     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
10020         throwIfParentInstance("getBindDeviceAdminTargetUsers");
10021         try {
10022             return mService.getBindDeviceAdminTargetUsers(admin);
10023         } catch (RemoteException re) {
10024             throw re.rethrowFromSystemServer();
10025         }
10026     }
10027 
10028     /**
10029      * Called by the system to get the time at which the device owner last retrieved security
10030      * logging entries.
10031      *
10032      * @return the time at which the device owner most recently retrieved security logging entries,
10033      *         in milliseconds since epoch; -1 if security logging entries were never retrieved.
10034      * @throws SecurityException if the caller is not the device owner, does not hold the
10035      *         MANAGE_USERS permission and is not the system.
10036      *
10037      * @hide
10038      */
10039     @TestApi
getLastSecurityLogRetrievalTime()10040     public long getLastSecurityLogRetrievalTime() {
10041         try {
10042             return mService.getLastSecurityLogRetrievalTime();
10043         } catch (RemoteException re) {
10044             throw re.rethrowFromSystemServer();
10045         }
10046     }
10047 
10048     /**
10049      * Called by the system to get the time at which the device owner last requested a bug report.
10050      *
10051      * @return the time at which the device owner most recently requested a bug report, in
10052      *         milliseconds since epoch; -1 if a bug report was never requested.
10053      * @throws SecurityException if the caller is not the device owner, does not hold the
10054      *         MANAGE_USERS permission and is not the system.
10055      *
10056      * @hide
10057      */
10058     @TestApi
getLastBugReportRequestTime()10059     public long getLastBugReportRequestTime() {
10060         try {
10061             return mService.getLastBugReportRequestTime();
10062         } catch (RemoteException re) {
10063             throw re.rethrowFromSystemServer();
10064         }
10065     }
10066 
10067     /**
10068      * Called by the system to get the time at which the device owner last retrieved network logging
10069      * events.
10070      *
10071      * @return the time at which the device owner most recently retrieved network logging events, in
10072      *         milliseconds since epoch; -1 if network logging events were never retrieved.
10073      * @throws SecurityException if the caller is not the device owner, does not hold the
10074      *         MANAGE_USERS permission and is not the system.
10075      *
10076      * @hide
10077      */
10078     @TestApi
getLastNetworkLogRetrievalTime()10079     public long getLastNetworkLogRetrievalTime() {
10080         try {
10081             return mService.getLastNetworkLogRetrievalTime();
10082         } catch (RemoteException re) {
10083             throw re.rethrowFromSystemServer();
10084         }
10085     }
10086 
10087     /**
10088      * Called by the system to find out whether the current user's IME was set by the device/profile
10089      * owner or the user.
10090      *
10091      * @return {@code true} if the user's IME was set by the device or profile owner, {@code false}
10092      *         otherwise.
10093      * @throws SecurityException if the caller is not the device owner/profile owner.
10094      *
10095      * @hide
10096      */
10097     @TestApi
isCurrentInputMethodSetByOwner()10098     public boolean isCurrentInputMethodSetByOwner() {
10099         try {
10100             return mService.isCurrentInputMethodSetByOwner();
10101         } catch (RemoteException re) {
10102             throw re.rethrowFromSystemServer();
10103         }
10104     }
10105 
10106     /**
10107      * Called by the system to get a list of CA certificates that were installed by the device or
10108      * profile owner.
10109      *
10110      * <p> The caller must be the target user's device owner/profile Owner or hold the
10111      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL} permission.
10112      *
10113      * @param user The user for whom to retrieve information.
10114      * @return list of aliases identifying CA certificates installed by the device or profile owner
10115      * @throws SecurityException if the caller does not have permission to retrieve information
10116      *         about the given user's CA certificates.
10117      *
10118      * @hide
10119      */
10120     @TestApi
getOwnerInstalledCaCerts(@onNull UserHandle user)10121     public List<String> getOwnerInstalledCaCerts(@NonNull UserHandle user) {
10122         try {
10123             return mService.getOwnerInstalledCaCerts(user).getList();
10124         } catch (RemoteException re) {
10125             throw re.rethrowFromSystemServer();
10126         }
10127     }
10128 
10129     /**
10130      * Called by the device owner or profile owner to clear application user data of a given
10131      * package. The behaviour of this is equivalent to the target application calling
10132      * {@link android.app.ActivityManager#clearApplicationUserData()}.
10133      *
10134      * <p><strong>Note:</strong> an application can store data outside of its application data, e.g.
10135      * external storage or user dictionary. This data will not be wiped by calling this API.
10136      *
10137      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10138      * @param packageName The name of the package which will have its user data wiped.
10139      * @param executor The executor through which the listener should be invoked.
10140      * @param listener A callback object that will inform the caller when the clearing is done.
10141      * @throws SecurityException if the caller is not the device owner/profile owner.
10142      */
clearApplicationUserData(@onNull ComponentName admin, @NonNull String packageName, @NonNull @CallbackExecutor Executor executor, @NonNull OnClearApplicationUserDataListener listener)10143     public void clearApplicationUserData(@NonNull ComponentName admin,
10144             @NonNull String packageName, @NonNull @CallbackExecutor Executor executor,
10145             @NonNull OnClearApplicationUserDataListener listener) {
10146         throwIfParentInstance("clearAppData");
10147         Preconditions.checkNotNull(executor);
10148         Preconditions.checkNotNull(listener);
10149         try {
10150             mService.clearApplicationUserData(admin, packageName,
10151                     new IPackageDataObserver.Stub() {
10152                         public void onRemoveCompleted(String pkg, boolean succeeded) {
10153                             executor.execute(() ->
10154                                     listener.onApplicationUserDataCleared(pkg, succeeded));
10155                         }
10156                     });
10157         } catch (RemoteException re) {
10158             throw re.rethrowFromSystemServer();
10159         }
10160     }
10161 
10162     /**
10163      * Called by a device owner to specify whether logout is enabled for all secondary users. The
10164      * system may show a logout button that stops the user and switches back to the primary user.
10165      *
10166      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10167      * @param enabled whether logout should be enabled or not.
10168      * @throws SecurityException if {@code admin} is not a device owner.
10169      */
setLogoutEnabled(@onNull ComponentName admin, boolean enabled)10170     public void setLogoutEnabled(@NonNull ComponentName admin, boolean enabled) {
10171         throwIfParentInstance("setLogoutEnabled");
10172         try {
10173             mService.setLogoutEnabled(admin, enabled);
10174         } catch (RemoteException re) {
10175             throw re.rethrowFromSystemServer();
10176         }
10177     }
10178 
10179     /**
10180      * Returns whether logout is enabled by a device owner.
10181      *
10182      * @return {@code true} if logout is enabled by device owner, {@code false} otherwise.
10183      */
isLogoutEnabled()10184     public boolean isLogoutEnabled() {
10185         throwIfParentInstance("isLogoutEnabled");
10186         try {
10187             return mService.isLogoutEnabled();
10188         } catch (RemoteException re) {
10189             throw re.rethrowFromSystemServer();
10190         }
10191     }
10192 
10193     /**
10194      * Callback used in {@link #clearApplicationUserData}
10195      * to indicate that the clearing of an application's user data is done.
10196      */
10197     public interface OnClearApplicationUserDataListener {
10198         /**
10199          * Method invoked when clearing the application user data has completed.
10200          *
10201          * @param packageName The name of the package which had its user data cleared.
10202          * @param succeeded Whether the clearing succeeded. Clearing fails for device administrator
10203          *                  apps and protected system packages.
10204          */
onApplicationUserDataCleared(String packageName, boolean succeeded)10205         void onApplicationUserDataCleared(String packageName, boolean succeeded);
10206     }
10207 
10208     /**
10209      * Returns set of system apps that should be removed during provisioning.
10210      *
10211      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
10212      * @param userId ID of the user to be provisioned.
10213      * @param provisioningAction action indicating type of provisioning, should be one of
10214      * {@link #ACTION_PROVISION_MANAGED_DEVICE}, {@link #ACTION_PROVISION_MANAGED_PROFILE} or
10215      * {@link #ACTION_PROVISION_MANAGED_USER}.
10216      *
10217      * @hide
10218      */
getDisallowedSystemApps(ComponentName admin, int userId, String provisioningAction)10219     public Set<String> getDisallowedSystemApps(ComponentName admin, int userId,
10220             String provisioningAction) {
10221         try {
10222             return new ArraySet<>(
10223                     mService.getDisallowedSystemApps(admin, userId, provisioningAction));
10224         } catch (RemoteException re) {
10225             throw re.rethrowFromSystemServer();
10226         }
10227     }
10228 
10229     /**
10230      * Changes the current administrator to another one. All policies from the current
10231      * administrator are migrated to the new administrator. The whole operation is atomic -
10232      * the transfer is either complete or not done at all.
10233      *
10234      * <p>Depending on the current administrator (device owner, profile owner), you have the
10235      * following expected behaviour:
10236      * <ul>
10237      *     <li>A device owner can only be transferred to a new device owner</li>
10238      *     <li>A profile owner can only be transferred to a new profile owner</li>
10239      * </ul>
10240      *
10241      * <p>Use the {@code bundle} parameter to pass data to the new administrator. The data
10242      * will be received in the
10243      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}
10244      * callback of the new administrator.
10245      *
10246      * <p>The transfer has failed if the original administrator is still the corresponding owner
10247      * after calling this method.
10248      *
10249      * <p>The incoming target administrator must have the
10250      * <code>&lt;support-transfer-ownership /&gt;</code> tag inside the
10251      * <code>&lt;device-admin&gt;&lt;/device-admin&gt;</code> tags in the xml file referenced by
10252      * {@link DeviceAdminReceiver#DEVICE_ADMIN_META_DATA}. Otherwise an
10253      * {@link IllegalArgumentException} will be thrown.
10254      *
10255      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10256      * @param target which {@link DeviceAdminReceiver} we want the new administrator to be
10257      * @param bundle data to be sent to the new administrator
10258      * @throws SecurityException if {@code admin} is not a device owner nor a profile owner
10259      * @throws IllegalArgumentException if {@code admin} or {@code target} is {@code null}, they
10260      * are components in the same package or {@code target} is not an active admin
10261      */
transferOwnership(@onNull ComponentName admin, @NonNull ComponentName target, @Nullable PersistableBundle bundle)10262     public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
10263             @Nullable PersistableBundle bundle) {
10264         throwIfParentInstance("transferOwnership");
10265         try {
10266             mService.transferOwnership(admin, target, bundle);
10267         } catch (RemoteException re) {
10268             throw re.rethrowFromSystemServer();
10269         }
10270     }
10271 
10272     /**
10273      * Called by a device owner to specify the user session start message. This may be displayed
10274      * during a user switch.
10275      * <p>
10276      * The message should be limited to a short statement or it may be truncated.
10277      * <p>
10278      * If the message needs to be localized, it is the responsibility of the
10279      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
10280      * and set a new version of this message accordingly.
10281      *
10282      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10283      * @param startUserSessionMessage message for starting user session, or {@code null} to use
10284      * system default message.
10285      * @throws SecurityException if {@code admin} is not a device owner.
10286      */
setStartUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence startUserSessionMessage)10287     public void setStartUserSessionMessage(
10288             @NonNull ComponentName admin, @Nullable CharSequence startUserSessionMessage) {
10289         throwIfParentInstance("setStartUserSessionMessage");
10290         try {
10291             mService.setStartUserSessionMessage(admin, startUserSessionMessage);
10292         } catch (RemoteException re) {
10293             throw re.rethrowFromSystemServer();
10294         }
10295     }
10296 
10297     /**
10298      * Called by a device owner to specify the user session end message. This may be displayed
10299      * during a user switch.
10300      * <p>
10301      * The message should be limited to a short statement or it may be truncated.
10302      * <p>
10303      * If the message needs to be localized, it is the responsibility of the
10304      * {@link DeviceAdminReceiver} to listen to the {@link Intent#ACTION_LOCALE_CHANGED} broadcast
10305      * and set a new version of this message accordingly.
10306      *
10307      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10308      * @param endUserSessionMessage message for ending user session, or {@code null} to use system
10309      * default message.
10310      * @throws SecurityException if {@code admin} is not a device owner.
10311      */
setEndUserSessionMessage( @onNull ComponentName admin, @Nullable CharSequence endUserSessionMessage)10312     public void setEndUserSessionMessage(
10313             @NonNull ComponentName admin, @Nullable CharSequence endUserSessionMessage) {
10314         throwIfParentInstance("setEndUserSessionMessage");
10315         try {
10316             mService.setEndUserSessionMessage(admin, endUserSessionMessage);
10317         } catch (RemoteException re) {
10318             throw re.rethrowFromSystemServer();
10319         }
10320     }
10321 
10322     /**
10323      * Returns the user session start message.
10324      *
10325      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10326      * @throws SecurityException if {@code admin} is not a device owner.
10327      */
getStartUserSessionMessage(@onNull ComponentName admin)10328     public CharSequence getStartUserSessionMessage(@NonNull ComponentName admin) {
10329         throwIfParentInstance("getStartUserSessionMessage");
10330         try {
10331             return mService.getStartUserSessionMessage(admin);
10332         } catch (RemoteException re) {
10333             throw re.rethrowFromSystemServer();
10334         }
10335     }
10336 
10337     /**
10338      * Returns the user session end message.
10339      *
10340      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10341      * @throws SecurityException if {@code admin} is not a device owner.
10342      */
getEndUserSessionMessage(@onNull ComponentName admin)10343     public CharSequence getEndUserSessionMessage(@NonNull ComponentName admin) {
10344         throwIfParentInstance("getEndUserSessionMessage");
10345         try {
10346             return mService.getEndUserSessionMessage(admin);
10347         } catch (RemoteException re) {
10348             throw re.rethrowFromSystemServer();
10349         }
10350     }
10351 
10352     /**
10353      * Called by device owner to add an override APN.
10354      *
10355      * <p>This method may returns {@code -1} if {@code apnSetting} conflicts with an existing
10356      * override APN. Update the existing conflicted APN with
10357      * {@link #updateOverrideApn(ComponentName, int, ApnSetting)} instead of adding a new entry.
10358      * <p>Two override APNs are considered to conflict when all the following APIs return
10359      * the same values on both override APNs:
10360      * <ul>
10361      *   <li>{@link ApnSetting#getOperatorNumeric()}</li>
10362      *   <li>{@link ApnSetting#getApnName()}</li>
10363      *   <li>{@link ApnSetting#getProxyAddressAsString()}</li>
10364      *   <li>{@link ApnSetting#getProxyPort()}</li>
10365      *   <li>{@link ApnSetting#getMmsProxyAddressAsString()}</li>
10366      *   <li>{@link ApnSetting#getMmsProxyPort()}</li>
10367      *   <li>{@link ApnSetting#getMmsc()}</li>
10368      *   <li>{@link ApnSetting#isEnabled()}</li>
10369      *   <li>{@link ApnSetting#getMvnoType()}</li>
10370      *   <li>{@link ApnSetting#getProtocol()}</li>
10371      *   <li>{@link ApnSetting#getRoamingProtocol()}</li>
10372      * </ul>
10373      *
10374      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10375      * @param apnSetting the override APN to insert
10376      * @return The {@code id} of inserted override APN. Or {@code -1} when failed to insert into
10377      *         the database.
10378      * @throws SecurityException if {@code admin} is not a device owner.
10379      *
10380      * @see #setOverrideApnsEnabled(ComponentName, boolean)
10381      */
addOverrideApn(@onNull ComponentName admin, @NonNull ApnSetting apnSetting)10382     public int addOverrideApn(@NonNull ComponentName admin, @NonNull ApnSetting apnSetting) {
10383         throwIfParentInstance("addOverrideApn");
10384         if (mService != null) {
10385             try {
10386                 return mService.addOverrideApn(admin, apnSetting);
10387             } catch (RemoteException e) {
10388                 throw e.rethrowFromSystemServer();
10389             }
10390         }
10391         return -1;
10392     }
10393 
10394     /**
10395      * Called by device owner to update an override APN.
10396      *
10397      * <p>This method may returns {@code false} if there is no override APN with the given
10398      * {@code apnId}.
10399      * <p>This method may also returns {@code false} if {@code apnSetting} conflicts with an
10400      * existing override APN. Update the existing conflicted APN instead.
10401      * <p>See {@link #addOverrideApn} for the definition of conflict.
10402      *
10403      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10404      * @param apnId the {@code id} of the override APN to update
10405      * @param apnSetting the override APN to update
10406      * @return {@code true} if the required override APN is successfully updated,
10407      *         {@code false} otherwise.
10408      * @throws SecurityException if {@code admin} is not a device owner.
10409      *
10410      * @see #setOverrideApnsEnabled(ComponentName, boolean)
10411      */
updateOverrideApn(@onNull ComponentName admin, int apnId, @NonNull ApnSetting apnSetting)10412     public boolean updateOverrideApn(@NonNull ComponentName admin, int apnId,
10413             @NonNull ApnSetting apnSetting) {
10414         throwIfParentInstance("updateOverrideApn");
10415         if (mService != null) {
10416             try {
10417                 return mService.updateOverrideApn(admin, apnId, apnSetting);
10418             } catch (RemoteException e) {
10419                 throw e.rethrowFromSystemServer();
10420             }
10421         }
10422         return false;
10423     }
10424 
10425     /**
10426      * Called by device owner to remove an override APN.
10427      *
10428      * <p>This method may returns {@code false} if there is no override APN with the given
10429      * {@code apnId}.
10430      *
10431      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10432      * @param apnId the {@code id} of the override APN to remove
10433      * @return {@code true} if the required override APN is successfully removed, {@code false}
10434      *         otherwise.
10435      * @throws SecurityException if {@code admin} is not a device owner.
10436      *
10437      * @see #setOverrideApnsEnabled(ComponentName, boolean)
10438      */
removeOverrideApn(@onNull ComponentName admin, int apnId)10439     public boolean removeOverrideApn(@NonNull ComponentName admin, int apnId) {
10440         throwIfParentInstance("removeOverrideApn");
10441         if (mService != null) {
10442             try {
10443                 return mService.removeOverrideApn(admin, apnId);
10444             } catch (RemoteException e) {
10445                 throw e.rethrowFromSystemServer();
10446             }
10447         }
10448         return false;
10449     }
10450 
10451     /**
10452      * Called by device owner to get all override APNs inserted by device owner.
10453      *
10454      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10455      * @return A list of override APNs inserted by device owner.
10456      * @throws SecurityException if {@code admin} is not a device owner.
10457      *
10458      * @see #setOverrideApnsEnabled(ComponentName, boolean)
10459      */
getOverrideApns(@onNull ComponentName admin)10460     public List<ApnSetting> getOverrideApns(@NonNull ComponentName admin) {
10461         throwIfParentInstance("getOverrideApns");
10462         if (mService != null) {
10463             try {
10464                 return mService.getOverrideApns(admin);
10465             } catch (RemoteException e) {
10466                 throw e.rethrowFromSystemServer();
10467             }
10468         }
10469         return Collections.emptyList();
10470     }
10471 
10472     /**
10473      * Called by device owner to set if override APNs should be enabled.
10474      * <p> Override APNs are separated from other APNs on the device, and can only be inserted or
10475      * modified by the device owner. When enabled, only override APNs are in use, any other APNs
10476      * are ignored.
10477      *
10478      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10479      * @param enabled {@code true} if override APNs should be enabled, {@code false} otherwise
10480      * @throws SecurityException if {@code admin} is not a device owner.
10481      */
setOverrideApnsEnabled(@onNull ComponentName admin, boolean enabled)10482     public void setOverrideApnsEnabled(@NonNull ComponentName admin, boolean enabled) {
10483         throwIfParentInstance("setOverrideApnEnabled");
10484         if (mService != null) {
10485             try {
10486                 mService.setOverrideApnsEnabled(admin, enabled);
10487             } catch (RemoteException e) {
10488                 throw e.rethrowFromSystemServer();
10489             }
10490         }
10491     }
10492 
10493     /**
10494      * Called by device owner to check if override APNs are currently enabled.
10495      *
10496      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10497      * @return {@code true} if override APNs are currently enabled, {@code false} otherwise.
10498      * @throws SecurityException if {@code admin} is not a device owner.
10499      *
10500      * @see #setOverrideApnsEnabled(ComponentName, boolean)
10501      */
isOverrideApnEnabled(@onNull ComponentName admin)10502     public boolean isOverrideApnEnabled(@NonNull ComponentName admin) {
10503         throwIfParentInstance("isOverrideApnEnabled");
10504         if (mService != null) {
10505             try {
10506                 return mService.isOverrideApnEnabled(admin);
10507             } catch (RemoteException e) {
10508                 throw e.rethrowFromSystemServer();
10509             }
10510         }
10511         return false;
10512     }
10513 
10514     /**
10515      * Returns the data passed from the current administrator to the new administrator during an
10516      * ownership transfer. This is the same {@code bundle} passed in
10517      * {@link #transferOwnership(ComponentName, ComponentName, PersistableBundle)}. The bundle is
10518      * persisted until the profile owner or device owner is removed.
10519      *
10520      * <p>This is the same <code>bundle</code> received in the
10521      * {@link DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)}.
10522      * Use this method to retrieve it after the transfer as long as the new administrator is the
10523      * active device or profile owner.
10524      *
10525      * <p>Returns <code>null</code> if no ownership transfer was started for the calling user.
10526      *
10527      * @see #transferOwnership
10528      * @see DeviceAdminReceiver#onTransferOwnershipComplete(Context, PersistableBundle)
10529      * @throws SecurityException if the caller is not a device or profile owner.
10530      */
10531     @Nullable
getTransferOwnershipBundle()10532     public PersistableBundle getTransferOwnershipBundle() {
10533         throwIfParentInstance("getTransferOwnershipBundle");
10534         try {
10535             return mService.getTransferOwnershipBundle();
10536         } catch (RemoteException re) {
10537             throw re.rethrowFromSystemServer();
10538         }
10539     }
10540 
10541     /**
10542      * Sets the global Private DNS mode to opportunistic.
10543      * May only be called by the device owner.
10544      *
10545      * <p>In this mode, the DNS subsystem will attempt a TLS handshake to the network-supplied
10546      * resolver prior to attempting name resolution in cleartext.
10547      *
10548      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10549      *
10550      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully, or
10551      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set.
10552      *
10553      * @throws SecurityException if the caller is not the device owner.
10554      */
setGlobalPrivateDnsModeOpportunistic( @onNull ComponentName admin)10555     public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeOpportunistic(
10556             @NonNull ComponentName admin) {
10557         throwIfParentInstance("setGlobalPrivateDnsModeOpportunistic");
10558 
10559         if (mService == null) {
10560             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
10561         }
10562 
10563         try {
10564             return mService.setGlobalPrivateDns(admin, PRIVATE_DNS_MODE_OPPORTUNISTIC, null);
10565         } catch (RemoteException re) {
10566             throw re.rethrowFromSystemServer();
10567         }
10568     }
10569 
10570     /**
10571      * Sets the global Private DNS host to be used.
10572      * May only be called by the device owner.
10573      *
10574      * <p>Note that the method is blocking as it will perform a connectivity check to the resolver,
10575      * to ensure it is valid. Because of that, the method should not be called on any thread that
10576      * relates to user interaction, such as the UI thread.
10577      *
10578      * <p>In case a VPN is used in conjunction with Private DNS resolver, the Private DNS resolver
10579      * must be reachable both from within and outside the VPN. Otherwise, the device may lose
10580      * the ability to resolve hostnames as system traffic to the resolver may not go through the
10581      * VPN.
10582      *
10583      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10584      * @param privateDnsHost The hostname of a server that implements DNS over TLS (RFC7858).
10585      *
10586      * @return {@code PRIVATE_DNS_SET_NO_ERROR} if the mode was set successfully,
10587      *         {@code PRIVATE_DNS_SET_ERROR_FAILURE_SETTING} if it could not be set or
10588      *         {@code PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING} if the specified host does not
10589      *         implement RFC7858.
10590      *
10591      * @throws IllegalArgumentException if the {@code privateDnsHost} is not a valid hostname.
10592      *
10593      * @throws SecurityException if the caller is not the device owner.
10594      */
setGlobalPrivateDnsModeSpecifiedHost( @onNull ComponentName admin, @NonNull String privateDnsHost)10595     @WorkerThread public @PrivateDnsModeErrorCodes int setGlobalPrivateDnsModeSpecifiedHost(
10596             @NonNull ComponentName admin, @NonNull String privateDnsHost) {
10597         throwIfParentInstance("setGlobalPrivateDnsModeSpecifiedHost");
10598         Preconditions.checkNotNull(privateDnsHost, "dns resolver is null");
10599 
10600         if (mService == null) {
10601             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
10602         }
10603 
10604         if (NetworkUtils.isWeaklyValidatedHostname(privateDnsHost)) {
10605             if (!PrivateDnsConnectivityChecker.canConnectToPrivateDnsServer(privateDnsHost)) {
10606                 return PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING;
10607             }
10608         }
10609 
10610         try {
10611             return mService.setGlobalPrivateDns(
10612                     admin, PRIVATE_DNS_MODE_PROVIDER_HOSTNAME, privateDnsHost);
10613         } catch (RemoteException re) {
10614             throw re.rethrowFromSystemServer();
10615         }
10616     }
10617 
10618     /**
10619      * Called by device owner to install a system update from the given file. The device will be
10620      * rebooted in order to finish installing the update. Note that if the device is rebooted, this
10621      * doesn't necessarily mean that the update has been applied successfully. The caller should
10622      * additionally check the system version with {@link android.os.Build#FINGERPRINT} or {@link
10623      * android.os.Build.VERSION}. If an error occurs during processing the OTA before the reboot,
10624      * the caller will be notified by {@link InstallSystemUpdateCallback}. If device does not have
10625      * sufficient battery level, the installation will fail with error {@link
10626      * InstallSystemUpdateCallback#UPDATE_ERROR_BATTERY_LOW}.
10627      *
10628      * @param admin The {@link DeviceAdminReceiver} that this request is associated with.
10629      * @param updateFilePath An Uri of the file that contains the update. The file should be
10630      * readable by the calling app.
10631      * @param executor The executor through which the callback should be invoked.
10632      * @param callback A callback object that will inform the caller when installing an update
10633      * fails.
10634      */
installSystemUpdate( @onNull ComponentName admin, @NonNull Uri updateFilePath, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)10635     public void installSystemUpdate(
10636             @NonNull ComponentName admin, @NonNull Uri updateFilePath,
10637             @NonNull @CallbackExecutor Executor executor,
10638             @NonNull InstallSystemUpdateCallback callback) {
10639         throwIfParentInstance("installUpdate");
10640         if (mService == null) {
10641             return;
10642         }
10643         try (ParcelFileDescriptor fileDescriptor = mContext.getContentResolver()
10644                     .openFileDescriptor(updateFilePath, "r")) {
10645             mService.installUpdateFromFile(
10646                     admin, fileDescriptor, new StartInstallingUpdateCallback.Stub() {
10647                         @Override
10648                         public void onStartInstallingUpdateError(
10649                                 int errorCode, String errorMessage) {
10650                             executeCallback(errorCode, errorMessage, executor, callback);
10651                         }
10652                     });
10653         } catch (RemoteException e) {
10654             throw e.rethrowFromSystemServer();
10655         } catch (FileNotFoundException e) {
10656             Log.w(TAG, e);
10657             executeCallback(
10658                     InstallSystemUpdateCallback.UPDATE_ERROR_FILE_NOT_FOUND,
10659                     Log.getStackTraceString(e),
10660                     executor, callback);
10661         } catch (IOException e) {
10662             Log.w(TAG, e);
10663             executeCallback(
10664                     InstallSystemUpdateCallback.UPDATE_ERROR_UNKNOWN, Log.getStackTraceString(e),
10665                     executor, callback);
10666         }
10667     }
10668 
executeCallback(int errorCode, String errorMessage, @NonNull @CallbackExecutor Executor executor, @NonNull InstallSystemUpdateCallback callback)10669     private void executeCallback(int errorCode, String errorMessage,
10670             @NonNull @CallbackExecutor Executor executor,
10671             @NonNull InstallSystemUpdateCallback callback) {
10672         executor.execute(() -> callback.onInstallUpdateError(errorCode, errorMessage));
10673     }
10674 
10675     /**
10676      * Returns the system-wide Private DNS mode.
10677      *
10678      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10679      * @return one of {@code PRIVATE_DNS_MODE_OFF}, {@code PRIVATE_DNS_MODE_OPPORTUNISTIC},
10680      * {@code PRIVATE_DNS_MODE_PROVIDER_HOSTNAME} or {@code PRIVATE_DNS_MODE_UNKNOWN}.
10681      * @throws SecurityException if the caller is not the device owner.
10682      */
getGlobalPrivateDnsMode(@onNull ComponentName admin)10683     public int getGlobalPrivateDnsMode(@NonNull ComponentName admin) {
10684         throwIfParentInstance("setGlobalPrivateDns");
10685         if (mService == null) {
10686             return PRIVATE_DNS_MODE_UNKNOWN;
10687         }
10688 
10689         try {
10690             return mService.getGlobalPrivateDnsMode(admin);
10691         } catch (RemoteException re) {
10692             throw re.rethrowFromSystemServer();
10693         }
10694     }
10695 
10696     /**
10697      * Returns the system-wide Private DNS host.
10698      *
10699      * @param admin which {@link DeviceAdminReceiver} this request is associated with.
10700      * @return The hostname used for Private DNS queries, null if none is set.
10701      * @throws SecurityException if the caller is not the device owner.
10702      */
getGlobalPrivateDnsHost(@onNull ComponentName admin)10703     public @Nullable String getGlobalPrivateDnsHost(@NonNull ComponentName admin) {
10704         throwIfParentInstance("setGlobalPrivateDns");
10705         if (mService == null) {
10706             return null;
10707         }
10708 
10709         try {
10710             return mService.getGlobalPrivateDnsHost(admin);
10711         } catch (RemoteException re) {
10712             throw re.rethrowFromSystemServer();
10713         }
10714     }
10715 
10716     /**
10717      * Grants the profile owner of the given user access to device identifiers (such as
10718      * serial number, IMEI and MEID).
10719      *
10720      * <p>This lets the profile owner request inclusion of device identifiers when calling
10721      * {@link generateKeyPair}.
10722      *
10723      * <p>This grant is necessary to guarantee that profile owners can access device identifiers.
10724      *
10725      * <p>Privileged system API - meant to be called by the system, particularly the managed
10726      * provisioning app, when a work profile is set up.
10727      *
10728      * @hide
10729      */
10730     @SystemApi
10731     @RequiresPermission(value = android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS,
10732             conditional = true)
setProfileOwnerCanAccessDeviceIds(@onNull ComponentName who)10733     public void setProfileOwnerCanAccessDeviceIds(@NonNull ComponentName who) {
10734         if (mService == null) {
10735             return;
10736         }
10737         try {
10738             mService.grantDeviceIdsAccessToProfileOwner(who, myUserId());
10739         } catch (RemoteException re) {
10740             throw re.rethrowFromSystemServer();
10741         }
10742     }
10743 
10744     /**
10745      * Allows a set of packages to access cross-profile calendar APIs.
10746      *
10747      * <p>Called by a profile owner of a managed profile.
10748      *
10749      * <p>Calling with a {@code null} value for the set disables the restriction so that all
10750      * packages are allowed to access cross-profile calendar APIs. Calling with an empty set
10751      * disallows all packages from accessing cross-profile calendar APIs. If this method isn't
10752      * called, no package is allowed to access cross-profile calendar APIs by default.
10753      *
10754      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10755      * @param packageNames set of packages to be whitelisted
10756      * @throws SecurityException if {@code admin} is not a profile owner
10757      *
10758      * @see #getCrossProfileCalendarPackages(ComponentName)
10759      */
setCrossProfileCalendarPackages(@onNull ComponentName admin, @Nullable Set<String> packageNames)10760     public void setCrossProfileCalendarPackages(@NonNull ComponentName admin,
10761             @Nullable Set<String> packageNames) {
10762         throwIfParentInstance("setCrossProfileCalendarPackages");
10763         if (mService != null) {
10764             try {
10765                 mService.setCrossProfileCalendarPackages(admin, packageNames == null ? null
10766                         : new ArrayList<>(packageNames));
10767             } catch (RemoteException e) {
10768                 throw e.rethrowFromSystemServer();
10769             }
10770         }
10771     }
10772 
10773     /**
10774      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
10775      *
10776      * <p>Called by a profile owner of a managed profile.
10777      *
10778      * @param admin which {@link DeviceAdminReceiver} this request is associated with
10779      * @return the set of names of packages that were previously allowed via
10780      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
10781      * empty set if none have been allowed
10782      * @throws SecurityException if {@code admin} is not a profile owner
10783      *
10784      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
10785      */
getCrossProfileCalendarPackages(@onNull ComponentName admin)10786     public @Nullable Set<String> getCrossProfileCalendarPackages(@NonNull ComponentName admin) {
10787         throwIfParentInstance("getCrossProfileCalendarPackages");
10788         if (mService != null) {
10789             try {
10790                 final List<String> packageNames = mService.getCrossProfileCalendarPackages(admin);
10791                 return packageNames == null ? null : new ArraySet<>(packageNames);
10792             } catch (RemoteException e) {
10793                 throw e.rethrowFromSystemServer();
10794             }
10795         }
10796         return Collections.emptySet();
10797     }
10798 
10799     /**
10800      * Returns if a package is allowed to access cross-profile calendar APIs.
10801      *
10802      * <p>A package is allowed to access cross-profile calendar APIs if it's allowed by
10803      * admins via {@link #setCrossProfileCalendarPackages(ComponentName, Set)} and
10804      * {@link android.provider.Settings.Secure#CROSS_PROFILE_CALENDAR_ENABLED}
10805      * is turned on in the managed profile.
10806      *
10807      * <p>To query for a specific user, use
10808      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
10809      * that user, and get a {@link DevicePolicyManager} from this context.
10810      *
10811      * @param packageName the name of the package
10812      * @return {@code true} if the package is allowed to access cross-profile calendar APIs,
10813      * {@code false} otherwise
10814      *
10815      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
10816      * @see #getCrossProfileCalendarPackages(ComponentName)
10817      * @hide
10818      */
isPackageAllowedToAccessCalendar(@onNull String packageName)10819     public boolean isPackageAllowedToAccessCalendar(@NonNull  String packageName) {
10820         throwIfParentInstance("isPackageAllowedToAccessCalendar");
10821         if (mService != null) {
10822             try {
10823                 return mService.isPackageAllowedToAccessCalendarForUser(packageName,
10824                         myUserId());
10825             } catch (RemoteException e) {
10826                 throw e.rethrowFromSystemServer();
10827             }
10828         }
10829         return false;
10830     }
10831 
10832     /**
10833      * Gets a set of package names that are allowed to access cross-profile calendar APIs.
10834      *
10835      * <p>To query for a specific user, use
10836      * {@link Context#createPackageContextAsUser(String, int, UserHandle)} to create a context for
10837      * that user, and get a {@link DevicePolicyManager} from this context.
10838      *
10839      * @return the set of names of packages that were previously allowed via
10840      * {@link #setCrossProfileCalendarPackages(ComponentName, Set)}, or an
10841      * empty set if none have been allowed
10842      *
10843      * @see #setCrossProfileCalendarPackages(ComponentName, Set)
10844      * @see #getCrossProfileCalendarPackages(ComponentName)
10845      * @hide
10846      */
getCrossProfileCalendarPackages()10847     public @Nullable Set<String> getCrossProfileCalendarPackages() {
10848         throwIfParentInstance("getCrossProfileCalendarPackages");
10849         if (mService != null) {
10850             try {
10851                 final List<String> packageNames = mService.getCrossProfileCalendarPackagesForUser(
10852                         myUserId());
10853                 return packageNames == null ? null : new ArraySet<>(packageNames);
10854             } catch (RemoteException e) {
10855                 throw e.rethrowFromSystemServer();
10856             }
10857         }
10858         return Collections.emptySet();
10859     }
10860 
10861     /**
10862      * Returns whether the device is being used as a managed kiosk. These requirements are as
10863      * follows:
10864      * <ul>
10865      *     <li>The device is in Lock Task (therefore there is also a Device Owner app on the
10866      *     device)</li>
10867      *     <li>The Lock Task feature {@link DevicePolicyManager#LOCK_TASK_FEATURE_SYSTEM_INFO} is
10868      *     not enabled, so the system info in the status bar is not visible</li>
10869      *     <li>The device does not have a secure lock screen (e.g. it has no lock screen or has
10870      *     swipe-to-unlock)</li>
10871      *     <li>The device is not in the middle of an ephemeral user session</li>
10872      * </ul>
10873      *
10874      * <p>Publicly-accessible dedicated devices don't have the same privacy model as
10875      * personally-used devices. In particular, user consent popups don't make sense as a barrier to
10876      * accessing persistent data on these devices since the user giving consent and the user whose
10877      * data is on the device are unlikely to be the same. These consent popups prevent the true
10878      * remote management of these devices.
10879      *
10880      * <p>This condition is not sufficient to cover APIs that would access data that only lives for
10881      * the duration of the user's session, since the user has an expectation of privacy in these
10882      * conditions that more closely resembles use of a personal device. In those cases, see {@link
10883      * #isUnattendedManagedKiosk()}.
10884      *
10885      * @hide
10886      */
10887     @SystemApi
10888     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isManagedKiosk()10889     public boolean isManagedKiosk() {
10890         throwIfParentInstance("isManagedKiosk");
10891         if (mService != null) {
10892             try {
10893                 return mService.isManagedKiosk();
10894             } catch (RemoteException e) {
10895                 throw e.rethrowFromSystemServer();
10896             }
10897         }
10898         return false;
10899     }
10900 
10901     /**
10902      * Returns whether the device is being used as an unattended managed kiosk. These requirements
10903      * are as follows:
10904      * <ul>
10905      *     <li>The device is being used as a managed kiosk, as defined at {@link
10906      *     #isManagedKiosk()}</li>
10907      *     <li>The device has not received user input for at least 30 minutes</li>
10908      * </ul>
10909      *
10910      * <p>See {@link #isManagedKiosk()} for context. This is a stronger requirement that also
10911      * ensures that the device hasn't been interacted with recently, making it an appropriate check
10912      * for privacy-sensitive APIs that wouldn't be appropriate during an active user session.
10913      *
10914      * @hide
10915      */
10916     @SystemApi
10917     @RequiresPermission(android.Manifest.permission.MANAGE_USERS)
isUnattendedManagedKiosk()10918     public boolean isUnattendedManagedKiosk() {
10919         throwIfParentInstance("isUnattendedManagedKiosk");
10920         if (mService != null) {
10921             try {
10922                 return mService.isUnattendedManagedKiosk();
10923             } catch (RemoteException e) {
10924                 throw e.rethrowFromSystemServer();
10925             }
10926         }
10927         return false;
10928     }
10929 
10930     /**
10931      * Starts an activity to view calendar events in the managed profile.
10932      *
10933      * @param eventId the id of the event to be viewed
10934      * @param start the start time of the event
10935      * @param end the end time of the event
10936      * @param allDay if the event is an all-day event
10937      * @param flags flags to be set for the intent
10938      * @return {@code true} if the activity is started successfully, {@code false} otherwise
10939      *
10940      * @see CalendarContract#startViewCalendarEventInManagedProfile(Context, String, long, long,
10941      * long, boolean, int)
10942      *
10943      * @hide
10944      */
startViewCalendarEventInManagedProfile(long eventId, long start, long end, boolean allDay, int flags)10945     public boolean startViewCalendarEventInManagedProfile(long eventId, long start, long end,
10946             boolean allDay, int flags) {
10947         throwIfParentInstance("startViewCalendarEventInManagedProfile");
10948         if (mService != null) {
10949             try {
10950                 return mService.startViewCalendarEventInManagedProfile(mContext.getPackageName(),
10951                         eventId, start, end, allDay, flags);
10952             } catch (RemoteException e) {
10953                 throw e.rethrowFromSystemServer();
10954             }
10955         }
10956         return false;
10957     }
10958 }
10959